mirror of
https://github.com/signalapp/Signal-Server.git
synced 2026-12-01 06:56:47 +00:00
Compare commits
30
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
065e730200 | ||
|
|
7e7bef32cc | ||
|
|
5b1d4ce95e | ||
|
|
12d9637f21 | ||
|
|
924ab88e93 | ||
|
|
187cd9e163 | ||
|
|
2ed60209b1 | ||
|
|
9ffb588c6a | ||
|
|
5043175cb4 | ||
|
|
953a473c74 | ||
|
|
3b87527f39 | ||
|
|
023296feaf | ||
|
|
b4db86a39b | ||
|
|
e0b89d6228 | ||
|
|
bcd8ed8d35 | ||
|
|
cb9b90b81d | ||
|
|
265bcfe51b | ||
|
|
4b1a0259fc | ||
|
|
14e7652339 | ||
|
|
8d53b2d8a6 | ||
|
|
8ee097d25a | ||
|
|
94c9d48da1 | ||
|
|
a1b1d051f5 | ||
|
|
77eaec0150 | ||
|
|
7d39f72ed6 | ||
|
|
8c3a38979a | ||
|
|
af02cb93c0 | ||
|
|
c25c8807a6 | ||
|
|
dad2bd5c29 | ||
|
|
7e511d1f66 |
No files matched your search
@@ -45,10 +45,10 @@
|
||||
</modules>
|
||||
|
||||
<properties>
|
||||
<aws.sdk2.version>2.33.8</aws.sdk2.version>
|
||||
<braintree.version>3.44.0</braintree.version>
|
||||
<aws.sdk2.version>2.41.11</aws.sdk2.version>
|
||||
<braintree.version>3.47.0</braintree.version>
|
||||
<commons-csv.version>1.14.1</commons-csv.version>
|
||||
<commons-io.version>2.20.0</commons-io.version>
|
||||
<commons-io.version>2.21.0</commons-io.version>
|
||||
<dropwizard.version>4.0.16</dropwizard.version>
|
||||
<!-- Note: when updating FoundationDB, also include a copy of `libfdb_c.so` from the FoundationDB release at
|
||||
src/main/jib/usr/lib/libfdb_c.so. We use x86_64 builds without AVX instructions enabled (i.e. FoundationDB versions
|
||||
@@ -57,38 +57,39 @@
|
||||
<foundationdb.version>7.3.62</foundationdb.version>
|
||||
<foundationdb.api-version>730</foundationdb.api-version>
|
||||
<foundationdb.client-library-sha256>bfed237b787fae3cde1222676e6bfbb0d218fc27bf9e903397a7a7aa96fb2d33</foundationdb.client-library-sha256>
|
||||
<google-cloud-libraries.version>26.67.0</google-cloud-libraries.version>
|
||||
<google-cloud-libraries.version>26.74.0</google-cloud-libraries.version>
|
||||
<grpc.version>1.73.0</grpc.version> <!-- should be kept in sync with the value from Google libraries-bom -->
|
||||
<gson.version>2.13.2</gson.version>
|
||||
<guava.version>33.5.0-jre</guava.version>
|
||||
<!-- several libraries (AWS, Google Cloud) use Apache http components transitively, and we need to align them -->
|
||||
<httpcore.version>4.4.16</httpcore.version>
|
||||
<httpclient.version>4.5.14</httpclient.version>
|
||||
<jackson.version>2.20.0</jackson.version>
|
||||
<jackson.version>2.21.0</jackson.version>
|
||||
<junit-pioneer.version>2.3.0</junit-pioneer.version>
|
||||
<jsr305.version>3.0.2</jsr305.version>
|
||||
<kotlin.version>2.2.20</kotlin.version>
|
||||
<logback.version>1.5.23</logback.version>
|
||||
<kotlin.version>2.3.0</kotlin.version>
|
||||
<logback.version>1.5.25</logback.version>
|
||||
<logback-access-common.version>2.0.6</logback-access-common.version>
|
||||
<lettuce.version>6.8.1.RELEASE</lettuce.version>
|
||||
<libphonenumber.version>9.0.13</libphonenumber.version>
|
||||
<logstash.logback.version>8.1</logstash.logback.version>
|
||||
<log4j-bom.version>2.25.1</log4j-bom.version>
|
||||
<log4j-bom.version>2.25.3</log4j-bom.version>
|
||||
<luajava.version>3.5.0</luajava.version>
|
||||
<micrometer.version>1.15.4</micrometer.version>
|
||||
<micrometer.version>1.16.2</micrometer.version>
|
||||
<netty.version>4.1.127.Final</netty.version>
|
||||
<!-- Must be less than or equal to the value from Google libraries-bom which controls the protobuf runtime version.
|
||||
See https://protobuf.dev/support/cross-version-runtime-guarantee/. -->
|
||||
<protoc.version>4.29.4</protoc.version>
|
||||
<pushy.version>0.15.4</pushy.version>
|
||||
<reactive.grpc.version>1.2.4</reactive.grpc.version>
|
||||
<reactor-bom.version>2024.0.10</reactor-bom.version> <!-- 3.7.11, see https://github.com/reactor/reactor#bom-versioning-scheme -->
|
||||
<reactor-bom.version>2025.0.2</reactor-bom.version> <!-- 3.8.2, see https://github.com/reactor/reactor#bom-versioning-scheme -->
|
||||
<resilience4j.version>2.3.0</resilience4j.version>
|
||||
<semver4j.version>3.1.0</semver4j.version>
|
||||
<simple-grpc.version>0.1.0</simple-grpc.version>
|
||||
<simple-grpc.version>0.2.0</simple-grpc.version>
|
||||
<slf4j.version>2.0.17</slf4j.version>
|
||||
<stripe.version>30.2.0</stripe.version>
|
||||
<swagger.version>2.2.36</swagger.version>
|
||||
<testcontainers.version>1.21.3</testcontainers.version>
|
||||
<stripe.version>31.2.0</stripe.version>
|
||||
<swagger.version>2.2.42</swagger.version>
|
||||
<testcontainers.version>2.0.3</testcontainers.version>
|
||||
|
||||
<!-- images to use in tests via testcontainers -->
|
||||
<dynamodb.image>amazon/dynamodb-local:3.0.0@sha256:2fed5e3a965a4ba5aa6ac82baec57058b5a3848e959d705518f3fd579a77e76b</dynamodb.image>
|
||||
@@ -284,6 +285,11 @@
|
||||
<artifactId>gson</artifactId>
|
||||
<version>${gson.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.google.guava</groupId>
|
||||
<artifactId>guava</artifactId>
|
||||
<version>${guava.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.redis</groupId>
|
||||
<artifactId>testcontainers-redis</artifactId>
|
||||
|
||||
@@ -97,3 +97,6 @@ turn.cloudflare.apiToken: ABCDEFGHIJKLM
|
||||
linkDevice.secret: AAAAAAAAAAA=
|
||||
|
||||
tlsKeyStore.password: unset
|
||||
|
||||
hlrLookup.apiKey: AAAAAAAAAAA
|
||||
hlrLookup.apiSecret: AAAAAAAAAAA
|
||||
@@ -276,6 +276,7 @@ unidentifiedDelivery:
|
||||
certificate: CgIIAQ==
|
||||
privateKey: secret://unidentifiedDelivery.privateKey
|
||||
expiresDays: 7
|
||||
embedSigner: true
|
||||
|
||||
shortCode:
|
||||
baseUrl: https://example.com/shortcodes/
|
||||
@@ -527,3 +528,7 @@ callQualitySurvey:
|
||||
{
|
||||
"credential": "configuration"
|
||||
}
|
||||
|
||||
hlrLookup:
|
||||
apiKey: secret://hlrLookup.apiKey
|
||||
apiSecret: secret://hlrLookup.apiSecret
|
||||
+6
-25
@@ -11,11 +11,11 @@
|
||||
<artifactId>service</artifactId>
|
||||
|
||||
<properties>
|
||||
<firebase-admin.version>9.6.0</firebase-admin.version>
|
||||
<java-uuid-generator.version>5.1.0</java-uuid-generator.version>
|
||||
<firebase-admin.version>9.7.0</firebase-admin.version>
|
||||
<java-uuid-generator.version>5.2.0</java-uuid-generator.version>
|
||||
<google-androidpublisher.version>v3-rev20250904-2.0.0</google-androidpublisher.version>
|
||||
<storekit.version>3.6.0</storekit.version>
|
||||
<webauthn4j.version>0.29.6.RELEASE</webauthn4j.version>
|
||||
<storekit.version>4.0.0</storekit.version>
|
||||
<webauthn4j.version>0.30.2.RELEASE</webauthn4j.version>
|
||||
<java-jwt.version>4.5.0</java-jwt.version>
|
||||
</properties>
|
||||
|
||||
@@ -266,26 +266,12 @@
|
||||
<dependency>
|
||||
<groupId>com.google.cloud</groupId>
|
||||
<artifactId>google-cloud-pubsub</artifactId>
|
||||
<exclusions>
|
||||
<!-- our direct import of guava brings in a more recent version of failureaccess, so excluding it here -->
|
||||
<exclusion>
|
||||
<groupId>com.google.guava</groupId>
|
||||
<artifactId>failureaccess</artifactId>
|
||||
</exclusion>
|
||||
</exclusions>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>com.google.firebase</groupId>
|
||||
<artifactId>firebase-admin</artifactId>
|
||||
<version>${firebase-admin.version}</version>
|
||||
<exclusions>
|
||||
<!-- our direct import of guava brings in a more recent version of failureaccess, so excluding it here -->
|
||||
<exclusion>
|
||||
<groupId>com.google.guava</groupId>
|
||||
<artifactId>failureaccess</artifactId>
|
||||
</exclusion>
|
||||
</exclusions>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
@@ -297,11 +283,6 @@
|
||||
<groupId>io.opentelemetry.instrumentation</groupId>
|
||||
<artifactId>opentelemetry-instrumentation-api-incubator</artifactId>
|
||||
</exclusion>
|
||||
<!-- our direct import of guava brings in a more recent version of failureaccess, so excluding it here -->
|
||||
<exclusion>
|
||||
<groupId>com.google.guava</groupId>
|
||||
<artifactId>failureaccess</artifactId>
|
||||
</exclusion>
|
||||
</exclusions>
|
||||
</dependency>
|
||||
|
||||
@@ -521,13 +502,13 @@
|
||||
|
||||
<dependency>
|
||||
<groupId>org.testcontainers</groupId>
|
||||
<artifactId>localstack</artifactId>
|
||||
<artifactId>testcontainers-localstack</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.testcontainers</groupId>
|
||||
<artifactId>junit-jupiter</artifactId>
|
||||
<artifactId>testcontainers-junit-jupiter</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
|
||||
+10
@@ -39,6 +39,7 @@ import org.whispersystems.textsecuregcm.configuration.GcpAttachmentsConfiguratio
|
||||
import org.whispersystems.textsecuregcm.configuration.GenericZkConfig;
|
||||
import org.whispersystems.textsecuregcm.configuration.GooglePlayBillingConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.GrpcConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.HlrLookupConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.IdlePrimaryDeviceReminderConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.KeyTransparencyServiceConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.LinkDeviceSecretConfiguration;
|
||||
@@ -332,6 +333,11 @@ public class WhisperServerConfiguration extends Configuration {
|
||||
@JsonProperty
|
||||
private Map<String, @Valid RetryConfiguration> retries = Collections.emptyMap();
|
||||
|
||||
@Valid
|
||||
@NotNull
|
||||
@JsonProperty
|
||||
private HlrLookupConfiguration hlrLookup;
|
||||
|
||||
@JsonProperty
|
||||
@Valid
|
||||
@NotNull
|
||||
@@ -590,4 +596,8 @@ public class WhisperServerConfiguration extends Configuration {
|
||||
public CallQualitySurveyConfiguration getCallQualitySurveyConfiguration() {
|
||||
return callQualitySurvey;
|
||||
}
|
||||
|
||||
public HlrLookupConfiguration getHlrLookupConfiguration() {
|
||||
return hlrLookup;
|
||||
}
|
||||
}
|
||||
@@ -166,6 +166,7 @@ import org.whispersystems.textsecuregcm.limits.RateLimitByIpFilter;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimitChallengeManager;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimiters;
|
||||
import org.whispersystems.textsecuregcm.limits.RedisMessageDeliveryLoopMonitor;
|
||||
import org.whispersystems.textsecuregcm.mappers.BackupExceptionMapper;
|
||||
import org.whispersystems.textsecuregcm.mappers.CompletionExceptionMapper;
|
||||
import org.whispersystems.textsecuregcm.mappers.DeviceLimitExceededExceptionMapper;
|
||||
import org.whispersystems.textsecuregcm.mappers.GrpcStatusRuntimeExceptionMapper;
|
||||
@@ -208,6 +209,7 @@ import org.whispersystems.textsecuregcm.s3.S3MonitoringSupplier;
|
||||
import org.whispersystems.textsecuregcm.securestorage.SecureStorageClient;
|
||||
import org.whispersystems.textsecuregcm.securevaluerecovery.SecureValueRecoveryClient;
|
||||
import org.whispersystems.textsecuregcm.spam.ChallengeConstraintChecker;
|
||||
import org.whispersystems.textsecuregcm.spam.MessageDeliveryListener;
|
||||
import org.whispersystems.textsecuregcm.spam.RegistrationFraudChecker;
|
||||
import org.whispersystems.textsecuregcm.spam.RegistrationRecoveryChecker;
|
||||
import org.whispersystems.textsecuregcm.spam.SpamChecker;
|
||||
@@ -256,6 +258,8 @@ import org.whispersystems.textsecuregcm.subscriptions.BankMandateTranslator;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.BraintreeManager;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.GooglePlayBillingManager;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.StripeManager;
|
||||
import org.whispersystems.textsecuregcm.telephony.CarrierDataProvider;
|
||||
import org.whispersystems.textsecuregcm.telephony.hlrlookup.HlrLookupCarrierDataProvider;
|
||||
import org.whispersystems.textsecuregcm.util.BufferingInterceptor;
|
||||
import org.whispersystems.textsecuregcm.util.ManagedAwsCrt;
|
||||
import org.whispersystems.textsecuregcm.util.ManagedExecutors;
|
||||
@@ -579,6 +583,10 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
.maxThreads(2)
|
||||
.minThreads(2)
|
||||
.build();
|
||||
ExecutorService hlrLookupHttpExecutor = ExecutorServiceBuilder.of(environment, "hlrLookup")
|
||||
.maxThreads(2)
|
||||
.minThreads(2)
|
||||
.build();
|
||||
|
||||
ExecutorService subscriptionProcessorExecutor = ManagedExecutors.newVirtualThreadPerTaskExecutor(
|
||||
"subscriptionProcessor",
|
||||
@@ -633,6 +641,14 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
new RegistrationRecoveryPasswordsManager(registrationRecoveryPasswords);
|
||||
UsernameHashZkProofVerifier usernameHashZkProofVerifier = new UsernameHashZkProofVerifier();
|
||||
|
||||
final CarrierDataProvider carrierDataProvider =
|
||||
new HlrLookupCarrierDataProvider(config.getHlrLookupConfiguration().apiKey().value(),
|
||||
config.getHlrLookupConfiguration().apiSecret().value(),
|
||||
hlrLookupHttpExecutor,
|
||||
config.getHlrLookupConfiguration().circuitBreakerConfigurationName(),
|
||||
config.getHlrLookupConfiguration().retryConfigurationName(),
|
||||
retryExecutor);
|
||||
|
||||
RegistrationServiceClient registrationServiceClient = config.getRegistrationServiceConfiguration()
|
||||
.build(environment, registrationCallbackExecutor, registrationIdentityTokenRefreshExecutor);
|
||||
KeyTransparencyServiceClient keyTransparencyServiceClient = new KeyTransparencyServiceClient(
|
||||
@@ -1038,6 +1054,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
});
|
||||
|
||||
spamFilter.map(SpamFilter::getReportedMessageListener).ifPresent(reportMessageManager::addListener);
|
||||
spamFilter.map(SpamFilter::getMessageDeliveryListener).ifPresent(messageSender::addMessageDeliveryListener);
|
||||
|
||||
final HttpClient shortCodeRetrieverHttpClient = HttpClient.newBuilder().version(HttpClient.Version.HTTP_2)
|
||||
.connectTimeout(Duration.ofSeconds(10)).build();
|
||||
@@ -1070,7 +1087,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
new CallLinkController(rateLimiters, callingGenericZkSecretParams),
|
||||
new CallQualitySurveyController(callQualitySurveyManager),
|
||||
new CertificateController(accountsManager, new CertificateGenerator(config.getDeliveryCertificate().certificate(),
|
||||
config.getDeliveryCertificate().ecPrivateKey(), config.getDeliveryCertificate().expiresDays()),
|
||||
config.getDeliveryCertificate().ecPrivateKey(), config.getDeliveryCertificate().expiresDays(), config.getDeliveryCertificate().embedSigner()),
|
||||
zkAuthOperations, callingGenericZkSecretParams, clock),
|
||||
new ChallengeController(accountsManager, rateLimitChallengeManager, challengeConstraintChecker),
|
||||
new DeviceController(accountsManager, clientPublicKeysManager, rateLimiters, persistentTimer, config.getMaxDevices()),
|
||||
@@ -1102,7 +1119,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
config.getCdnConfiguration().bucket()),
|
||||
new VerificationController(registrationServiceClient, new VerificationSessionManager(verificationSessions),
|
||||
pushNotificationManager, registrationCaptchaManager, registrationRecoveryPasswordsManager,
|
||||
phoneNumberIdentifiers, rateLimiters, accountsManager, registrationFraudChecker,
|
||||
phoneNumberIdentifiers, rateLimiters, accountsManager, carrierDataProvider, registrationFraudChecker,
|
||||
dynamicConfigurationManager, clock)
|
||||
);
|
||||
if (config.getSubscription() != null && config.getOneTimeDonations() != null) {
|
||||
@@ -1184,6 +1201,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
new ObsoletePhoneNumberFormatExceptionMapper(),
|
||||
new RegistrationServiceSenderExceptionMapper(),
|
||||
new SubscriptionExceptionMapper(),
|
||||
new BackupExceptionMapper(),
|
||||
new JsonMappingExceptionMapper()
|
||||
).forEach(exceptionMapper -> {
|
||||
environment.jersey().register(exceptionMapper);
|
||||
|
||||
+26
-17
@@ -7,39 +7,48 @@ package org.whispersystems.textsecuregcm.auth;
|
||||
|
||||
import com.google.protobuf.ByteString;
|
||||
import com.google.protobuf.InvalidProtocolBufferException;
|
||||
import java.security.InvalidKeyException;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import org.signal.libsignal.protocol.ecc.ECPrivateKey;
|
||||
import org.whispersystems.textsecuregcm.entities.MessageProtos.SenderCertificate;
|
||||
import org.whispersystems.textsecuregcm.entities.MessageProtos.ServerCertificate;
|
||||
import org.whispersystems.textsecuregcm.identity.IdentityType;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.Device;
|
||||
import org.whispersystems.textsecuregcm.util.UUIDUtil;
|
||||
|
||||
public class CertificateGenerator {
|
||||
|
||||
private final ECPrivateKey privateKey;
|
||||
private final int expiresDays;
|
||||
private final ECPrivateKey privateKey;
|
||||
private final int expiresDays;
|
||||
private final boolean embedSigner;
|
||||
private final ServerCertificate serverCertificate;
|
||||
private final int serverCertificateId;
|
||||
|
||||
public CertificateGenerator(byte[] serverCertificate, ECPrivateKey privateKey, int expiresDays)
|
||||
throws InvalidProtocolBufferException
|
||||
{
|
||||
this.privateKey = privateKey;
|
||||
this.expiresDays = expiresDays;
|
||||
public CertificateGenerator(byte[] serverCertificate, ECPrivateKey privateKey, int expiresDays, boolean embedSigner)
|
||||
throws InvalidProtocolBufferException {
|
||||
this.privateKey = privateKey;
|
||||
this.expiresDays = expiresDays;
|
||||
this.embedSigner = embedSigner;
|
||||
this.serverCertificate = ServerCertificate.parseFrom(serverCertificate);
|
||||
this.serverCertificateId = ServerCertificate.Certificate
|
||||
.parseFrom(this.serverCertificate.getCertificate())
|
||||
.getId();
|
||||
}
|
||||
|
||||
public byte[] createFor(final Account account, final byte deviceId, boolean includeE164) throws InvalidKeyException {
|
||||
public byte[] createFor(final Account account, final byte deviceId, boolean includeE164) {
|
||||
SenderCertificate.Certificate.Builder builder = SenderCertificate.Certificate.newBuilder()
|
||||
.setSenderDevice(Math.toIntExact(deviceId))
|
||||
.setExpires(System.currentTimeMillis() + TimeUnit.DAYS.toMillis(expiresDays))
|
||||
.setIdentityKey(ByteString.copyFrom(account.getIdentityKey(IdentityType.ACI).serialize()))
|
||||
.setSigner(serverCertificate)
|
||||
.setSenderUuid(account.getUuid().toString());
|
||||
.setSenderUuid(UUIDUtil.toByteString(account.getUuid()));
|
||||
|
||||
if (includeE164) {
|
||||
builder.setSender(account.getNumber());
|
||||
builder.setSenderE164(account.getNumber());
|
||||
}
|
||||
|
||||
if (embedSigner) {
|
||||
builder.setSignerCertificate(serverCertificate);
|
||||
} else {
|
||||
builder.setSignerId(serverCertificateId);
|
||||
}
|
||||
|
||||
byte[] certificate = builder.build().toByteArray();
|
||||
@@ -47,10 +56,10 @@ public class CertificateGenerator {
|
||||
signature = privateKey.calculateSignature(certificate);
|
||||
|
||||
return SenderCertificate.newBuilder()
|
||||
.setCertificate(ByteString.copyFrom(certificate))
|
||||
.setSignature(ByteString.copyFrom(signature))
|
||||
.build()
|
||||
.toByteArray();
|
||||
.setCertificate(ByteString.copyFrom(certificate))
|
||||
.setSignature(ByteString.copyFrom(signature))
|
||||
.build()
|
||||
.toByteArray();
|
||||
}
|
||||
|
||||
}
|
||||
+13
-17
@@ -6,8 +6,8 @@
|
||||
package org.whispersystems.textsecuregcm.auth.grpc;
|
||||
|
||||
import io.grpc.Context;
|
||||
import io.grpc.Status;
|
||||
import javax.annotation.Nullable;
|
||||
import org.whispersystems.textsecuregcm.grpc.GrpcExceptions;
|
||||
import org.whispersystems.textsecuregcm.storage.Device;
|
||||
|
||||
/**
|
||||
@@ -18,13 +18,11 @@ public class AuthenticationUtil {
|
||||
static final Context.Key<AuthenticatedDevice> CONTEXT_AUTHENTICATED_DEVICE = Context.key("authenticated-device");
|
||||
|
||||
/**
|
||||
* Returns the account/device authenticated in the current gRPC context or throws an "unauthenticated" exception if
|
||||
* no authenticated account/device is available.
|
||||
* Returns the account/device authenticated in the current gRPC context. Should only be called from a service run with
|
||||
* the {@link RequireAuthenticationInterceptor}.
|
||||
*
|
||||
* @return the account/device identifier authenticated in the current gRPC context
|
||||
*
|
||||
* @throws io.grpc.StatusRuntimeException with a status of {@code UNAUTHENTICATED} if no authenticated account/device
|
||||
* could be retrieved from the current gRPC context
|
||||
* @throws IllegalStateException if no authenticated account/device could be retrieved from the current gRPC context
|
||||
*/
|
||||
public static AuthenticatedDevice requireAuthenticatedDevice() {
|
||||
@Nullable final AuthenticatedDevice authenticatedDevice = CONTEXT_AUTHENTICATED_DEVICE.get();
|
||||
@@ -33,27 +31,25 @@ public class AuthenticationUtil {
|
||||
return authenticatedDevice;
|
||||
}
|
||||
|
||||
throw Status.UNAUTHENTICATED.asRuntimeException();
|
||||
throw new IllegalStateException(
|
||||
"Configuration issue: service expects an authenticated device, but none was found. Request should have failed from an interceptor");
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the account/device authenticated in the current gRPC context or throws an "unauthenticated" exception if
|
||||
* no authenticated account/device is available or "permission denied" if the authenticated device is not the primary
|
||||
* device for the account.
|
||||
* Returns the account/device authenticated in the current gRPC context or "invalid argument" if the authenticated
|
||||
* device is not the primary device for the account.
|
||||
*
|
||||
* @return the account/device identifier authenticated in the current gRPC context
|
||||
*
|
||||
* @throws io.grpc.StatusRuntimeException with a status of {@code UNAUTHENTICATED} if no authenticated account/device
|
||||
* could be retrieved from the current gRPC context or a status of {@code PERMISSION_DENIED} if the authenticated
|
||||
* device is not the primary device for the authenticated account
|
||||
* @throws io.grpc.StatusRuntimeException with a status of {@code INVALID_ARGUMENT} if the authenticated device is not
|
||||
* the primary device for the authenticated account
|
||||
* @throws IllegalStateException if no authenticated account/device could be retrieved from the current gRPC
|
||||
* context
|
||||
*/
|
||||
public static AuthenticatedDevice requireAuthenticatedPrimaryDevice() {
|
||||
final AuthenticatedDevice authenticatedDevice = requireAuthenticatedDevice();
|
||||
|
||||
if (authenticatedDevice.deviceId() != Device.PRIMARY_ID) {
|
||||
throw Status.PERMISSION_DENIED.asRuntimeException();
|
||||
throw GrpcExceptions.badAuthentication("RPC requires a primary device");
|
||||
}
|
||||
|
||||
return authenticatedDevice;
|
||||
}
|
||||
}
|
||||
+4
-2
@@ -9,6 +9,8 @@ import io.grpc.ServerCall;
|
||||
import io.grpc.ServerCallHandler;
|
||||
import io.grpc.ServerInterceptor;
|
||||
import io.grpc.Status;
|
||||
import org.whispersystems.textsecuregcm.grpc.GrpcExceptions;
|
||||
import org.whispersystems.textsecuregcm.grpc.ServerInterceptorUtil;
|
||||
|
||||
/**
|
||||
* A "prohibit authentication" interceptor ensures that requests to endpoints that should be invoked anonymously do not
|
||||
@@ -22,8 +24,8 @@ public class ProhibitAuthenticationInterceptor implements ServerInterceptor {
|
||||
final Metadata headers, final ServerCallHandler<ReqT, RespT> next) {
|
||||
final String authHeaderString = headers.get(Metadata.Key.of(RequireAuthenticationInterceptor.AUTHORIZATION_HEADER, Metadata.ASCII_STRING_MARSHALLER));
|
||||
if (authHeaderString != null) {
|
||||
call.close(Status.UNAUTHENTICATED.withDescription("authorization header forbidden"), new Metadata());
|
||||
return new ServerCall.Listener<>() {};
|
||||
return ServerInterceptorUtil.closeWithStatusException(call,
|
||||
GrpcExceptions.badAuthentication("The service forbids requests with an authentication header"));
|
||||
}
|
||||
return next.startCall(call, headers);
|
||||
}
|
||||
|
||||
+7
-6
@@ -14,6 +14,7 @@ import io.grpc.ServerInterceptor;
|
||||
import io.grpc.Status;
|
||||
import java.util.Optional;
|
||||
import org.whispersystems.textsecuregcm.auth.AccountAuthenticator;
|
||||
import org.whispersystems.textsecuregcm.grpc.GrpcExceptions;
|
||||
import org.whispersystems.textsecuregcm.grpc.ServerInterceptorUtil;
|
||||
import org.whispersystems.textsecuregcm.util.HeaderUtils;
|
||||
|
||||
@@ -40,21 +41,21 @@ public class RequireAuthenticationInterceptor implements ServerInterceptor {
|
||||
Metadata.Key.of(AUTHORIZATION_HEADER, Metadata.ASCII_STRING_MARSHALLER));
|
||||
|
||||
if (authHeaderString == null) {
|
||||
return ServerInterceptorUtil.closeWithStatus(call,
|
||||
Status.UNAUTHENTICATED.withDescription("missing authorization header"));
|
||||
return ServerInterceptorUtil.closeWithStatusException(call,
|
||||
GrpcExceptions.invalidCredentials("missing authorization header"));
|
||||
}
|
||||
|
||||
final Optional<BasicCredentials> basicCredentials = HeaderUtils.basicCredentialsFromAuthHeader(authHeaderString);
|
||||
if (basicCredentials.isEmpty()) {
|
||||
return ServerInterceptorUtil.closeWithStatus(call,
|
||||
Status.UNAUTHENTICATED.withDescription("malformed authorization header"));
|
||||
return ServerInterceptorUtil.closeWithStatusException(call,
|
||||
GrpcExceptions.invalidCredentials("malformed authorization header"));
|
||||
}
|
||||
|
||||
final Optional<org.whispersystems.textsecuregcm.auth.AuthenticatedDevice> authenticated =
|
||||
authenticator.authenticate(basicCredentials.get());
|
||||
if (authenticated.isEmpty()) {
|
||||
return ServerInterceptorUtil.closeWithStatus(call,
|
||||
Status.UNAUTHENTICATED.withDescription("invalid credentials"));
|
||||
return ServerInterceptorUtil.closeWithStatusException(call,
|
||||
GrpcExceptions.invalidCredentials("invalid credentials"));
|
||||
}
|
||||
|
||||
final AuthenticatedDevice authenticatedDevice = new AuthenticatedDevice(
|
||||
|
||||
+39
-64
@@ -5,7 +5,8 @@
|
||||
|
||||
package org.whispersystems.textsecuregcm.backup;
|
||||
|
||||
import io.grpc.Status;
|
||||
import java.io.IOException;
|
||||
import java.io.UncheckedIOException;
|
||||
import java.security.MessageDigest;
|
||||
import java.time.Clock;
|
||||
import java.time.Duration;
|
||||
@@ -40,7 +41,6 @@ import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.Device;
|
||||
import org.whispersystems.textsecuregcm.storage.RedeemedReceiptsManager;
|
||||
import org.whispersystems.textsecuregcm.util.Util;
|
||||
|
||||
/**
|
||||
* Issues ZK backup auth credentials for authenticated accounts
|
||||
@@ -57,7 +57,6 @@ public class BackupAuthManager {
|
||||
private static final Logger logger = LoggerFactory.getLogger(BackupAuthManager.class);
|
||||
|
||||
|
||||
final static Duration MAX_REDEMPTION_DURATION = Duration.ofDays(7);
|
||||
final static String BACKUP_MEDIA_EXPERIMENT_NAME = "backupMedia";
|
||||
|
||||
private final ExperimentEnrollmentManager experimentEnrollmentManager;
|
||||
@@ -94,22 +93,20 @@ public class BackupAuthManager {
|
||||
* message backups
|
||||
* @param mediaBackupCredentialRequest A request containing the blinded backup-id the client will use to upload
|
||||
* media backups
|
||||
* @return A future that completes when the credentialRequest has been stored
|
||||
* @throws RateLimitExceededException If too many backup-ids have been committed
|
||||
*/
|
||||
public CompletableFuture<Void> commitBackupId(
|
||||
public void commitBackupId(
|
||||
final Account account,
|
||||
final Device device,
|
||||
final Optional<BackupAuthCredentialRequest> messagesBackupCredentialRequest,
|
||||
final Optional<BackupAuthCredentialRequest> mediaBackupCredentialRequest) {
|
||||
final Optional<BackupAuthCredentialRequest> mediaBackupCredentialRequest)
|
||||
throws RateLimitExceededException, BackupPermissionException, BackupInvalidArgumentException {
|
||||
if (!device.isPrimary()) {
|
||||
throw Status.PERMISSION_DENIED.withDescription("Only primary device can set backup-id").asRuntimeException();
|
||||
throw new BackupPermissionException("Only primary device can set backup-id");
|
||||
}
|
||||
|
||||
if (messagesBackupCredentialRequest.isEmpty() && mediaBackupCredentialRequest.isEmpty()) {
|
||||
throw Status.INVALID_ARGUMENT
|
||||
.withDescription("Must set at least one of message/media credential requests")
|
||||
.asRuntimeException();
|
||||
throw new BackupInvalidArgumentException("Must set at least one of message/media credential requests");
|
||||
}
|
||||
|
||||
final byte[] storedMessageCredentialRequest = account.getBackupCredentialRequest(BackupCredentialType.MESSAGES)
|
||||
@@ -133,33 +130,24 @@ public class BackupAuthManager {
|
||||
if (!requiresMessageRotation && !requiresMediaRotation) {
|
||||
// No need to update or enforce rate limits, this is the credential that the user has already
|
||||
// committed to.
|
||||
return CompletableFuture.completedFuture(null);
|
||||
return;
|
||||
}
|
||||
|
||||
CompletableFuture<Void> rateLimitFuture = CompletableFuture.completedFuture(null);
|
||||
|
||||
if (requiresMessageRotation) {
|
||||
rateLimitFuture = rateLimitFuture.thenCombine(
|
||||
rateLimiters.forDescriptor(RateLimiters.For.SET_BACKUP_ID).validateAsync(account.getUuid()),
|
||||
(_, _) -> null);
|
||||
rateLimiters.forDescriptor(RateLimiters.For.SET_BACKUP_ID).validate(account.getUuid());
|
||||
}
|
||||
|
||||
if (requiresMediaRotation && hasActiveVoucher(account)) {
|
||||
rateLimitFuture = rateLimitFuture.thenCombine(
|
||||
rateLimiters.forDescriptor(RateLimiters.For.SET_PAID_MEDIA_BACKUP_ID).validateAsync(account.getUuid()),
|
||||
(_, _) -> null);
|
||||
rateLimiters.forDescriptor(RateLimiters.For.SET_PAID_MEDIA_BACKUP_ID).validate(account.getUuid());
|
||||
}
|
||||
|
||||
return rateLimitFuture.thenCompose(ignored -> this.accountsManager
|
||||
.updateAsync(account, a ->
|
||||
a.setBackupCredentialRequests(targetMessageCredentialRequest, targetMediaCredentialRequest))
|
||||
.thenRun(Util.NOOP))
|
||||
.toCompletableFuture();
|
||||
this.accountsManager.update(account, a ->
|
||||
a.setBackupCredentialRequests(targetMessageCredentialRequest, targetMediaCredentialRequest));
|
||||
}
|
||||
|
||||
public record BackupIdRotationLimit(boolean hasPermitsRemaining, Duration nextPermitAvailable) {}
|
||||
|
||||
public CompletionStage<BackupIdRotationLimit> checkBackupIdRotationLimit(final Account account) {
|
||||
public BackupIdRotationLimit checkBackupIdRotationLimit(final Account account) {
|
||||
final RateLimiter messagesLimiter = rateLimiters.forDescriptor(RateLimiters.For.SET_BACKUP_ID);
|
||||
final RateLimiter mediaLimiter = rateLimiters.forDescriptor(RateLimiters.For.SET_PAID_MEDIA_BACKUP_ID);
|
||||
|
||||
@@ -180,7 +168,7 @@ public class BackupAuthManager {
|
||||
isPaid ? mediaLimiter.config().permitRegenerationDuration() : Duration.ZERO));
|
||||
return new BackupIdRotationLimit(false, timeToNextPermit);
|
||||
}
|
||||
});
|
||||
}).toCompletableFuture().join();
|
||||
}
|
||||
|
||||
public record Credential(BackupAuthCredentialResponse credential, Instant redemptionTime) {}
|
||||
@@ -200,31 +188,32 @@ public class BackupAuthManager {
|
||||
* @param redemptionRange The time range to return credentials for
|
||||
* @return Credentials and the day on which they may be redeemed
|
||||
*/
|
||||
public CompletableFuture<List<Credential>> getBackupAuthCredentials(
|
||||
public List<Credential> getBackupAuthCredentials(
|
||||
final Account account,
|
||||
final BackupCredentialType credentialType,
|
||||
final RedemptionRange redemptionRange) {
|
||||
final RedemptionRange redemptionRange) throws BackupNotFoundException {
|
||||
|
||||
// If the account has an expired payment, clear it before continuing
|
||||
if (hasExpiredVoucher(account)) {
|
||||
return accountsManager.updateAsync(account, a -> {
|
||||
final Account updated = accountsManager.update(account, a -> {
|
||||
// Re-check in case we raced with an update
|
||||
if (hasExpiredVoucher(a)) {
|
||||
a.setBackupVoucher(null);
|
||||
}
|
||||
}).thenCompose(updated -> getBackupAuthCredentials(updated, credentialType, redemptionRange));
|
||||
});
|
||||
return getBackupAuthCredentials(updated, credentialType, redemptionRange);
|
||||
}
|
||||
|
||||
// fetch the blinded backup-id the account should have previously committed to
|
||||
final byte[] committedBytes = account.getBackupCredentialRequest(credentialType)
|
||||
.orElseThrow(() -> Status.NOT_FOUND.withDescription("No blinded backup-id has been added to the account").asRuntimeException());
|
||||
.orElseThrow(() -> new BackupNotFoundException("No blinded backup-id has been added to the account"));
|
||||
|
||||
try {
|
||||
final BackupLevel defaultBackupLevel = configuredBackupLevel(account);
|
||||
|
||||
// create a credential for every day in the requested period
|
||||
final BackupAuthCredentialRequest credentialReq = new BackupAuthCredentialRequest(committedBytes);
|
||||
return CompletableFuture.completedFuture(StreamSupport.stream(redemptionRange.spliterator(), false)
|
||||
return StreamSupport.stream(redemptionRange.spliterator(), false)
|
||||
.map(redemptionTime -> {
|
||||
// Check if the account has a voucher that's good for a certain receiptLevel at redemption time, otherwise
|
||||
// use the default receipt level
|
||||
@@ -233,12 +222,9 @@ public class BackupAuthManager {
|
||||
credentialReq.issueCredential(redemptionTime, backupLevel, credentialType, serverSecretParams),
|
||||
redemptionTime);
|
||||
})
|
||||
.toList());
|
||||
.toList();
|
||||
} catch (InvalidInputException e) {
|
||||
throw Status.INTERNAL
|
||||
.withDescription("Could not deserialize stored request credential")
|
||||
.withCause(e)
|
||||
.asRuntimeException();
|
||||
throw new UncheckedIOException(new IOException("Could not deserialize stored request credential", e));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -247,48 +233,39 @@ public class BackupAuthManager {
|
||||
*
|
||||
* @param account The account to enable backups on
|
||||
* @param receiptCredentialPresentation A ZK receipt presentation proving payment
|
||||
* @return A future that completes successfully when the account has been updated
|
||||
*/
|
||||
public CompletableFuture<Void> redeemReceipt(
|
||||
public void redeemReceipt(
|
||||
final Account account,
|
||||
final ReceiptCredentialPresentation receiptCredentialPresentation) {
|
||||
final ReceiptCredentialPresentation receiptCredentialPresentation)
|
||||
throws BackupBadReceiptException, BackupInvalidArgumentException, BackupMissingIdCommitmentException {
|
||||
try {
|
||||
serverZkReceiptOperations.verifyReceiptCredentialPresentation(receiptCredentialPresentation);
|
||||
} catch (VerificationFailedException e) {
|
||||
throw Status.INVALID_ARGUMENT
|
||||
.withDescription("receipt credential presentation verification failed")
|
||||
.asRuntimeException();
|
||||
throw new BackupBadReceiptException("receipt credential presentation verification failed");
|
||||
}
|
||||
final ReceiptSerial receiptSerial = receiptCredentialPresentation.getReceiptSerial();
|
||||
final Instant receiptExpiration = Instant.ofEpochSecond(receiptCredentialPresentation.getReceiptExpirationTime());
|
||||
if (clock.instant().isAfter(receiptExpiration)) {
|
||||
throw Status.INVALID_ARGUMENT.withDescription("receipt is already expired").asRuntimeException();
|
||||
throw new BackupBadReceiptException("receipt is already expired");
|
||||
}
|
||||
|
||||
final long receiptLevel = receiptCredentialPresentation.getReceiptLevel();
|
||||
|
||||
if (BackupLevelUtil.fromReceiptLevel(receiptLevel) != BackupLevel.PAID) {
|
||||
throw Status.INVALID_ARGUMENT
|
||||
.withDescription("server does not recognize the requested receipt level")
|
||||
.asRuntimeException();
|
||||
throw new BackupInvalidArgumentException("server does not recognize the requested receipt level");
|
||||
}
|
||||
|
||||
if (account.getBackupCredentialRequest(BackupCredentialType.MEDIA).isEmpty()) {
|
||||
throw Status.ABORTED
|
||||
.withDescription("account must have a backup-id commitment")
|
||||
.asRuntimeException();
|
||||
throw new BackupMissingIdCommitmentException();
|
||||
}
|
||||
|
||||
return redeemedReceiptsManager
|
||||
boolean receiptAllowed = redeemedReceiptsManager
|
||||
.put(receiptSerial, receiptExpiration.getEpochSecond(), receiptLevel, account.getUuid())
|
||||
.thenCompose(receiptAllowed -> {
|
||||
if (!receiptAllowed) {
|
||||
throw Status.INVALID_ARGUMENT
|
||||
.withDescription("receipt serial is already redeemed")
|
||||
.asRuntimeException();
|
||||
}
|
||||
return extendBackupVoucher(account, new Account.BackupVoucher(receiptLevel, receiptExpiration));
|
||||
});
|
||||
.join();
|
||||
if (!receiptAllowed) {
|
||||
throw new BackupBadReceiptException("receipt serial is already redeemed");
|
||||
}
|
||||
extendBackupVoucher(account, new Account.BackupVoucher(receiptLevel, receiptExpiration));
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -296,11 +273,9 @@ public class BackupAuthManager {
|
||||
*
|
||||
* @param account The account to update
|
||||
* @param backupVoucher The backup voucher to apply to this account
|
||||
* @return A future that completes once the account has been updated to have at least the level and expiration
|
||||
* in the provided voucher.
|
||||
*/
|
||||
public CompletableFuture<Void> extendBackupVoucher(final Account account, final Account.BackupVoucher backupVoucher) {
|
||||
return accountsManager.updateAsync(account, a -> {
|
||||
public void extendBackupVoucher(final Account account, final Account.BackupVoucher backupVoucher) {
|
||||
accountsManager.update(account, a -> {
|
||||
// Receipt credential expirations must be day aligned. Make sure any manually set backupVoucher is also day
|
||||
// aligned
|
||||
final Account.BackupVoucher newPayment = new Account.BackupVoucher(
|
||||
@@ -308,7 +283,7 @@ public class BackupAuthManager {
|
||||
backupVoucher.expiration().truncatedTo(ChronoUnit.DAYS));
|
||||
final Account.BackupVoucher existingPayment = a.getBackupVoucher();
|
||||
a.setBackupVoucher(merge(existingPayment, newPayment));
|
||||
}).thenRun(Util.NOOP);
|
||||
});
|
||||
}
|
||||
|
||||
private static Account.BackupVoucher merge(@Nullable final Account.BackupVoucher prev,
|
||||
|
||||
+12
@@ -0,0 +1,12 @@
|
||||
/*
|
||||
* Copyright 2026 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
package org.whispersystems.textsecuregcm.backup;
|
||||
|
||||
public class BackupBadReceiptException extends BackupException {
|
||||
|
||||
public BackupBadReceiptException(String message) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
/*
|
||||
* Copyright 2026 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
package org.whispersystems.textsecuregcm.backup;
|
||||
|
||||
public class BackupException extends Exception {
|
||||
|
||||
public BackupException() {
|
||||
super();
|
||||
}
|
||||
|
||||
public BackupException(String message) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
+12
@@ -0,0 +1,12 @@
|
||||
/*
|
||||
* Copyright 2026 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
package org.whispersystems.textsecuregcm.backup;
|
||||
|
||||
public class BackupFailedZkAuthenticationException extends BackupException {
|
||||
|
||||
public BackupFailedZkAuthenticationException(String message) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
+11
@@ -0,0 +1,11 @@
|
||||
/*
|
||||
* Copyright 2026 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
package org.whispersystems.textsecuregcm.backup;
|
||||
|
||||
public class BackupInvalidArgumentException extends BackupException {
|
||||
public BackupInvalidArgumentException(final String message) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
+219
-219
@@ -7,7 +7,6 @@ package org.whispersystems.textsecuregcm.backup;
|
||||
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import io.dropwizard.util.DataSize;
|
||||
import io.grpc.Status;
|
||||
import io.micrometer.core.instrument.DistributionSummary;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import io.micrometer.core.instrument.Tag;
|
||||
@@ -42,12 +41,12 @@ import org.whispersystems.textsecuregcm.auth.ExternalServiceCredentials;
|
||||
import org.whispersystems.textsecuregcm.auth.ExternalServiceCredentialsGenerator;
|
||||
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicBackupConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
|
||||
import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimiters;
|
||||
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
|
||||
import org.whispersystems.textsecuregcm.metrics.UserAgentTagUtil;
|
||||
import org.whispersystems.textsecuregcm.securevaluerecovery.SecureValueRecoveryClient;
|
||||
import org.whispersystems.textsecuregcm.storage.DynamicConfigurationManager;
|
||||
import org.whispersystems.textsecuregcm.util.AsyncTimerUtil;
|
||||
import org.whispersystems.textsecuregcm.util.ExceptionUtils;
|
||||
import org.whispersystems.textsecuregcm.util.Pair;
|
||||
import org.whispersystems.textsecuregcm.util.ua.UnrecognizedUserAgentException;
|
||||
@@ -127,11 +126,12 @@ public class BackupManager {
|
||||
* @param presentation a ZK credential presentation that encodes the backupId
|
||||
* @param signature the signature of the presentation
|
||||
* @param publicKey the public key of a key-pair that the presentation must be signed with
|
||||
* @throws BackupFailedZkAuthenticationException If the provided presentation or signature were invalid
|
||||
*/
|
||||
public CompletableFuture<Void> setPublicKey(
|
||||
public void setPublicKey(
|
||||
final BackupAuthCredentialPresentation presentation,
|
||||
final byte[] signature,
|
||||
final ECPublicKey publicKey) {
|
||||
final ECPublicKey publicKey) throws BackupFailedZkAuthenticationException {
|
||||
|
||||
// Note: this is a special case where we can't validate the presentation signature against the stored public key
|
||||
// because we are currently setting it. We check against the provided public key, but we must also verify that
|
||||
@@ -139,16 +139,16 @@ public class BackupManager {
|
||||
final Pair<BackupCredentialType, BackupLevel> credentialTypeAndBackupLevel =
|
||||
verifyPresentation(presentation).verifySignature(signature, publicKey);
|
||||
|
||||
return backupsDb.setPublicKey(presentation.getBackupId(), credentialTypeAndBackupLevel.second(), publicKey)
|
||||
.exceptionally(ExceptionUtils.exceptionallyHandler(PublicKeyConflictException.class, ex -> {
|
||||
ExceptionUtils.unwrapSupply(
|
||||
BackupPublicKeyConflictException.class,
|
||||
() -> backupsDb.setPublicKey(presentation.getBackupId(), credentialTypeAndBackupLevel.second(), publicKey).join(),
|
||||
_ -> {
|
||||
Metrics.counter(ZK_AUTHN_COUNTER_NAME,
|
||||
SUCCESS_TAG_NAME, String.valueOf(false),
|
||||
FAILURE_REASON_TAG_NAME, "public_key_conflict")
|
||||
.increment();
|
||||
throw Status.UNAUTHENTICATED
|
||||
.withDescription("public key does not match existing public key for the backup-id")
|
||||
.asRuntimeException();
|
||||
}));
|
||||
return new BackupFailedZkAuthenticationException("The provided public key did not match the stored public key");
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -158,69 +158,67 @@ public class BackupManager {
|
||||
*
|
||||
* @param backupUser an already ZK authenticated backup user
|
||||
* @return the upload form
|
||||
* @throws BackupPermissionException if the credential does not have the correct level
|
||||
* @throws BackupWrongCredentialTypeException if the credential does not have the messages type
|
||||
*/
|
||||
public CompletableFuture<BackupUploadDescriptor> createMessageBackupUploadDescriptor(
|
||||
final AuthenticatedBackupUser backupUser) {
|
||||
public BackupUploadDescriptor createMessageBackupUploadDescriptor(
|
||||
final AuthenticatedBackupUser backupUser) throws BackupPermissionException, BackupWrongCredentialTypeException {
|
||||
checkBackupLevel(backupUser, BackupLevel.FREE);
|
||||
checkBackupCredentialType(backupUser, BackupCredentialType.MESSAGES);
|
||||
|
||||
// this could race with concurrent updates, but the only effect would be last-writer-wins on the timestamp
|
||||
return backupsDb
|
||||
.addMessageBackup(backupUser)
|
||||
.thenApply(_ ->
|
||||
cdn3BackupCredentialGenerator.generateUpload(cdnMessageBackupName(backupUser)));
|
||||
backupsDb.addMessageBackup(backupUser).join();
|
||||
return cdn3BackupCredentialGenerator.generateUpload(cdnMessageBackupName(backupUser));
|
||||
}
|
||||
|
||||
public CompletableFuture<BackupUploadDescriptor> createTemporaryAttachmentUploadDescriptor(
|
||||
final AuthenticatedBackupUser backupUser) {
|
||||
public BackupUploadDescriptor createTemporaryAttachmentUploadDescriptor(final AuthenticatedBackupUser backupUser)
|
||||
throws RateLimitExceededException, BackupPermissionException, BackupWrongCredentialTypeException {
|
||||
checkBackupLevel(backupUser, BackupLevel.PAID);
|
||||
checkBackupCredentialType(backupUser, BackupCredentialType.MEDIA);
|
||||
|
||||
return rateLimiters.forDescriptor(RateLimiters.For.BACKUP_ATTACHMENT)
|
||||
.validateAsync(rateLimitKey(backupUser)).thenApply(ignored -> {
|
||||
final byte[] bytes = new byte[15];
|
||||
secureRandom.nextBytes(bytes);
|
||||
final String attachmentKey = Base64.getUrlEncoder().encodeToString(bytes);
|
||||
final AttachmentGenerator.Descriptor descriptor = tusAttachmentGenerator.generateAttachment(attachmentKey);
|
||||
return new BackupUploadDescriptor(3, attachmentKey, descriptor.headers(), descriptor.signedUploadLocation());
|
||||
}).toCompletableFuture();
|
||||
rateLimiters.forDescriptor(RateLimiters.For.BACKUP_ATTACHMENT).validate(rateLimitKey(backupUser));
|
||||
final byte[] bytes = new byte[15];
|
||||
secureRandom.nextBytes(bytes);
|
||||
final String attachmentKey = Base64.getUrlEncoder().encodeToString(bytes);
|
||||
final AttachmentGenerator.Descriptor descriptor = tusAttachmentGenerator.generateAttachment(attachmentKey);
|
||||
return new BackupUploadDescriptor(3, attachmentKey, descriptor.headers(), descriptor.signedUploadLocation());
|
||||
}
|
||||
|
||||
/**
|
||||
* Update the last update timestamps for the backupId in the presentation
|
||||
*
|
||||
* @param backupUser an already ZK authenticated backup user
|
||||
* @throws BackupPermissionException if the credential does not have the correct level
|
||||
*/
|
||||
public CompletableFuture<Void> ttlRefresh(final AuthenticatedBackupUser backupUser) {
|
||||
public void ttlRefresh(final AuthenticatedBackupUser backupUser) throws BackupPermissionException {
|
||||
checkBackupLevel(backupUser, BackupLevel.FREE);
|
||||
// update message backup TTL
|
||||
return backupsDb.ttlRefresh(backupUser).thenAccept(storedBackupAttributes -> {
|
||||
if (backupUser.credentialType() == BackupCredentialType.MEDIA) {
|
||||
final long maxTotalMediaSize =
|
||||
dynamicConfigurationManager.getConfiguration().getBackupConfiguration().maxTotalMediaSize();
|
||||
final StoredBackupAttributes storedBackupAttributes = backupsDb.ttlRefresh(backupUser).join();
|
||||
if (backupUser.credentialType() == BackupCredentialType.MEDIA) {
|
||||
final long maxTotalMediaSize =
|
||||
dynamicConfigurationManager.getConfiguration().getBackupConfiguration().maxTotalMediaSize();
|
||||
|
||||
// Report that the backup is out of quota if it cannot store a max size media object
|
||||
final boolean quotaExhausted = storedBackupAttributes.bytesUsed() >=
|
||||
(maxTotalMediaSize - BackupManager.MAX_MEDIA_OBJECT_SIZE);
|
||||
// Report that the backup is out of quota if it cannot store a max size media object
|
||||
final boolean quotaExhausted = storedBackupAttributes.bytesUsed() >=
|
||||
(maxTotalMediaSize - BackupManager.MAX_MEDIA_OBJECT_SIZE);
|
||||
|
||||
final Tags tags = Tags.of(
|
||||
UserAgentTagUtil.getPlatformTag(backupUser.userAgent()),
|
||||
Tag.of("type", backupUser.credentialType().name()),
|
||||
Tag.of("tier", backupUser.backupLevel().name()),
|
||||
Tag.of("quotaExhausted", String.valueOf(quotaExhausted)));
|
||||
final Tags tags = Tags.of(
|
||||
UserAgentTagUtil.getPlatformTag(backupUser.userAgent()),
|
||||
Tag.of("type", backupUser.credentialType().name()),
|
||||
Tag.of("tier", backupUser.backupLevel().name()),
|
||||
Tag.of("quotaExhausted", String.valueOf(quotaExhausted)));
|
||||
|
||||
DistributionSummary.builder(NUM_OBJECTS_SUMMARY_NAME)
|
||||
.tags(tags)
|
||||
.publishPercentileHistogram()
|
||||
.register(Metrics.globalRegistry)
|
||||
.record(storedBackupAttributes.numObjects());
|
||||
DistributionSummary.builder(BYTES_USED_SUMMARY_NAME)
|
||||
.tags(tags)
|
||||
.publishPercentileHistogram()
|
||||
.register(Metrics.globalRegistry)
|
||||
.record(storedBackupAttributes.bytesUsed());
|
||||
}
|
||||
});
|
||||
DistributionSummary.builder(NUM_OBJECTS_SUMMARY_NAME)
|
||||
.tags(tags)
|
||||
.publishPercentileHistogram()
|
||||
.register(Metrics.globalRegistry)
|
||||
.record(storedBackupAttributes.numObjects());
|
||||
DistributionSummary.builder(BYTES_USED_SUMMARY_NAME)
|
||||
.tags(tags)
|
||||
.publishPercentileHistogram()
|
||||
.register(Metrics.globalRegistry)
|
||||
.record(storedBackupAttributes.bytesUsed());
|
||||
}
|
||||
}
|
||||
|
||||
public record BackupInfo(int cdn, String backupSubdir, String mediaSubdir, String messageBackupKey,
|
||||
@@ -231,16 +229,21 @@ public class BackupManager {
|
||||
*
|
||||
* @param backupUser an already ZK authenticated backup user
|
||||
* @return Information about the existing backup
|
||||
* @throws BackupPermissionException if the credential does not have the correct level
|
||||
* @throws BackupNotFoundException if the provided backupuser does not exist
|
||||
*/
|
||||
public CompletableFuture<BackupInfo> backupInfo(final AuthenticatedBackupUser backupUser) {
|
||||
public BackupInfo backupInfo(final AuthenticatedBackupUser backupUser)
|
||||
throws BackupNotFoundException, BackupPermissionException {
|
||||
checkBackupLevel(backupUser, BackupLevel.FREE);
|
||||
return backupsDb.describeBackup(backupUser)
|
||||
.thenApply(backupDescription -> new BackupInfo(
|
||||
backupDescription.cdn(),
|
||||
backupUser.backupDir(),
|
||||
backupUser.mediaDir(),
|
||||
MESSAGE_BACKUP_NAME,
|
||||
backupDescription.mediaUsedSpace()));
|
||||
final BackupsDb.BackupDescription backupDescription = ExceptionUtils.unwrapSupply(
|
||||
BackupNotFoundException.class,
|
||||
() -> backupsDb.describeBackup(backupUser).join());
|
||||
return new BackupInfo(
|
||||
backupDescription.cdn(),
|
||||
backupUser.backupDir(),
|
||||
backupUser.mediaDir(),
|
||||
MESSAGE_BACKUP_NAME,
|
||||
backupDescription.mediaUsedSpace());
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -255,46 +258,42 @@ public class BackupManager {
|
||||
* @return A Flux that emits the locations of the double-encrypted objects on the backup cdn, or includes an error
|
||||
* detailing why the object could not be copied.
|
||||
*/
|
||||
public Flux<CopyResult> copyToBackup(final AuthenticatedBackupUser backupUser, List<CopyParameters> toCopy) {
|
||||
checkBackupLevel(backupUser, BackupLevel.PAID);
|
||||
checkBackupCredentialType(backupUser, BackupCredentialType.MEDIA);
|
||||
|
||||
public Flux<CopyResult> copyToBackup(final CopyQuota copyQuota) {
|
||||
final AuthenticatedBackupUser backupUser = copyQuota.backupUser();
|
||||
final DynamicBackupConfiguration backupConfiguration =
|
||||
dynamicConfigurationManager.getConfiguration().getBackupConfiguration();
|
||||
|
||||
return Mono.fromFuture(() -> allowedCopies(backupUser, toCopy))
|
||||
.flatMapMany(quotaResult -> Flux.concat(
|
||||
return Flux.concat(
|
||||
|
||||
// Perform copies for requests that fit in our quota, first updating the usage. If the copy fails, our
|
||||
// estimated quota usage may not be exact since we update usage first. We make a best-effort attempt
|
||||
// to undo the usage update if we know that the copied failed for sure.
|
||||
Flux.fromIterable(quotaResult.requestsToCopy())
|
||||
// Perform copies for requests that fit in our quota, first updating the usage. If the copy fails, our
|
||||
// estimated quota usage may not be exact since we update usage first. We make a best-effort attempt
|
||||
// to undo the usage update if we know that the copied failed for sure.
|
||||
Flux.fromIterable(copyQuota.requestsToCopy())
|
||||
|
||||
// Update the usage in reasonable chunk sizes to bound how out of sync our claimed and actual usage gets
|
||||
.buffer(backupConfiguration.usageCheckpointCount())
|
||||
.concatMap(copyParameters -> {
|
||||
final long quotaToConsume = copyParameters.stream()
|
||||
.mapToLong(CopyParameters::destinationObjectSize)
|
||||
.sum();
|
||||
return Mono
|
||||
.fromFuture(backupsDb.trackMedia(backupUser, copyParameters.size(), quotaToConsume))
|
||||
.thenMany(Flux.fromIterable(copyParameters));
|
||||
})
|
||||
// Update the usage in reasonable chunk sizes to bound how out of sync our claimed and actual usage gets
|
||||
.buffer(backupConfiguration.usageCheckpointCount())
|
||||
.concatMap(copyParameters -> {
|
||||
final long quotaToConsume = copyParameters.stream()
|
||||
.mapToLong(CopyParameters::destinationObjectSize)
|
||||
.sum();
|
||||
return Mono
|
||||
.fromFuture(backupsDb.trackMedia(backupUser, copyParameters.size(), quotaToConsume))
|
||||
.thenMany(Flux.fromIterable(copyParameters));
|
||||
})
|
||||
|
||||
// Actually perform the copies now that we've updated the quota
|
||||
.flatMapSequential(copyParams -> copyToBackup(backupUser, copyParams)
|
||||
.flatMap(copyResult -> switch (copyResult.outcome()) {
|
||||
case SUCCESS -> Mono.just(copyResult);
|
||||
case SOURCE_WRONG_LENGTH, SOURCE_NOT_FOUND, OUT_OF_QUOTA -> Mono
|
||||
.fromFuture(this.backupsDb.trackMedia(backupUser, -1, -copyParams.destinationObjectSize()))
|
||||
.thenReturn(copyResult);
|
||||
}),
|
||||
backupConfiguration.copyConcurrency(), 1),
|
||||
// Actually perform the copies now that we've updated the quota
|
||||
.flatMapSequential(copyParams -> copyToBackup(backupUser, copyParams)
|
||||
.flatMap(copyResult -> switch (copyResult.outcome()) {
|
||||
case SUCCESS -> Mono.just(copyResult);
|
||||
case SOURCE_WRONG_LENGTH, SOURCE_NOT_FOUND, OUT_OF_QUOTA -> Mono
|
||||
.fromFuture(this.backupsDb.trackMedia(backupUser, -1, -copyParams.destinationObjectSize()))
|
||||
.thenReturn(copyResult);
|
||||
}),
|
||||
backupConfiguration.copyConcurrency(), 1),
|
||||
|
||||
// There wasn't enough quota remaining to perform these copies
|
||||
Flux.fromIterable(quotaResult.requestsToReject())
|
||||
.map(arg -> new CopyResult(CopyResult.Outcome.OUT_OF_QUOTA, arg.destinationMediaId(), null))
|
||||
));
|
||||
// There wasn't enough quota remaining to perform these copies
|
||||
Flux.fromIterable(copyQuota.requestsToReject())
|
||||
.map(arg -> new CopyResult(CopyResult.Outcome.OUT_OF_QUOTA, arg.destinationMediaId(), null)));
|
||||
}
|
||||
|
||||
private Mono<CopyResult> copyToBackup(final AuthenticatedBackupUser backupUser, final CopyParameters copyParameters) {
|
||||
@@ -317,64 +316,67 @@ public class BackupManager {
|
||||
Mono.just(CopyResult.fromCopyError(throwable, copyParameters.destinationMediaId()).orElseThrow()));
|
||||
}
|
||||
|
||||
private record QuotaResult(List<CopyParameters> requestsToCopy, List<CopyParameters> requestsToReject) {}
|
||||
public record CopyQuota(AuthenticatedBackupUser backupUser, List<CopyParameters> requestsToCopy, List<CopyParameters> requestsToReject) {
|
||||
private static CopyQuota create(AuthenticatedBackupUser backupUser, final List<CopyParameters> toCopy, long remainingQuota) {
|
||||
// Figure out how many of the requested objects fit in the remaining quota
|
||||
final int index = indexWhereTotalExceeds(toCopy, CopyParameters::destinationObjectSize, remainingQuota);
|
||||
return new CopyQuota(backupUser, toCopy.subList(0, index), toCopy.subList(index, toCopy.size()));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Determine which copy requests can be performed with the user's remaining quota. This does not update the quota.
|
||||
*
|
||||
* @param backupUser The user quota to check against
|
||||
* @param toCopy The proposed copy requests
|
||||
* @return list of QuotaResult indicating which requests fit into the remaining quota and which requests should be
|
||||
* @return QuotaResult indicating which requests fit into the remaining quota and which requests should be
|
||||
* rejected with {@link CopyResult.Outcome#OUT_OF_QUOTA}
|
||||
* @throws BackupInvalidArgumentException if toCopy contains an invalid copy request
|
||||
* @throws BackupPermissionException if the credential does not have the correct level
|
||||
* @throws BackupWrongCredentialTypeException if the credential does not have the media type
|
||||
*/
|
||||
private CompletableFuture<QuotaResult> allowedCopies(
|
||||
public CopyQuota getCopyQuota(
|
||||
final AuthenticatedBackupUser backupUser,
|
||||
final List<CopyParameters> toCopy) {
|
||||
final long totalBytesAdded = toCopy.stream()
|
||||
.mapToLong(copyParameters -> {
|
||||
if (copyParameters.sourceLength() > MAX_MEDIA_OBJECT_SIZE || copyParameters.sourceLength() < 0) {
|
||||
throw Status.INVALID_ARGUMENT
|
||||
.withDescription("Invalid sourceObject size")
|
||||
.asRuntimeException();
|
||||
}
|
||||
return copyParameters.destinationObjectSize();
|
||||
})
|
||||
.sum();
|
||||
final List<CopyParameters> toCopy)
|
||||
throws BackupWrongCredentialTypeException, BackupPermissionException, BackupInvalidArgumentException {
|
||||
checkBackupLevel(backupUser, BackupLevel.PAID);
|
||||
checkBackupCredentialType(backupUser, BackupCredentialType.MEDIA);
|
||||
|
||||
for (CopyParameters copyParameters : toCopy) {
|
||||
if (copyParameters.sourceLength() > MAX_MEDIA_OBJECT_SIZE || copyParameters.sourceLength() < 0) {
|
||||
throw new BackupInvalidArgumentException("Invalid sourceObject size");
|
||||
}
|
||||
}
|
||||
final long totalBytesAdded = toCopy.stream().mapToLong(CopyParameters::destinationObjectSize).sum();
|
||||
|
||||
final DynamicBackupConfiguration backupConfiguration =
|
||||
dynamicConfigurationManager.getConfiguration().getBackupConfiguration();
|
||||
final Duration maxQuotaStaleness = backupConfiguration.maxQuotaStaleness();
|
||||
final long maxTotalMediaSize = backupConfiguration.maxTotalMediaSize();
|
||||
|
||||
return backupsDb.getMediaUsage(backupUser)
|
||||
.thenComposeAsync(info -> {
|
||||
long remainingQuota = maxTotalMediaSize - info.usageInfo().bytesUsed();
|
||||
final boolean canStore = remainingQuota >= totalBytesAdded;
|
||||
if (canStore || info.lastRecalculationTime().isAfter(clock.instant().minus(maxQuotaStaleness))) {
|
||||
return CompletableFuture.completedFuture(remainingQuota);
|
||||
}
|
||||
final BackupsDb.TimestampedUsageInfo info = backupsDb.getMediaUsage(backupUser).join();
|
||||
long estimatedRemainingQuota = maxTotalMediaSize - info.usageInfo().bytesUsed();
|
||||
final boolean canStore = estimatedRemainingQuota >= totalBytesAdded;
|
||||
if (canStore || info.lastRecalculationTime().isAfter(clock.instant().minus(maxQuotaStaleness))) {
|
||||
return CopyQuota.create(backupUser, toCopy, estimatedRemainingQuota);
|
||||
}
|
||||
|
||||
// The user is out of quota, and we have not recently recalculated the user's usage. Double check by doing a
|
||||
// hard recalculation before actually forbidding the user from storing additional media.
|
||||
return this.remoteStorageManager.calculateBytesUsed(cdnMediaDirectory(backupUser))
|
||||
.thenCompose(usage -> backupsDb
|
||||
.setMediaUsage(backupUser, usage)
|
||||
.thenApply(ignored -> usage))
|
||||
.whenComplete((newUsage, throwable) -> {
|
||||
boolean usageChanged = throwable == null && !newUsage.equals(info.usageInfo());
|
||||
Metrics.counter(USAGE_RECALCULATION_COUNTER_NAME, Tags.of(
|
||||
UserAgentTagUtil.getPlatformTag(backupUser.userAgent()),
|
||||
Tag.of("usageChanged", String.valueOf(usageChanged))))
|
||||
.increment();
|
||||
})
|
||||
.thenApply(newUsage -> maxTotalMediaSize - newUsage.bytesUsed());
|
||||
})
|
||||
.thenApply(remainingQuota -> {
|
||||
// Figure out how many of the requested objects fit in the remaining quota
|
||||
final int index = indexWhereTotalExceeds(toCopy, CopyParameters::destinationObjectSize,
|
||||
remainingQuota);
|
||||
return new QuotaResult(toCopy.subList(0, index), toCopy.subList(index, toCopy.size()));
|
||||
});
|
||||
// The user is out of quota, and we have not recently recalculated the user's usage. Double check by doing a
|
||||
// hard recalculation before actually forbidding the user from storing additional media.
|
||||
boolean usageChanged = false;
|
||||
try {
|
||||
final UsageInfo usage =
|
||||
this.remoteStorageManager.calculateBytesUsed(cdnMediaDirectory(backupUser)).toCompletableFuture().join();
|
||||
backupsDb.setMediaUsage(backupUser, usage).join();
|
||||
usageChanged = !usage.equals(info.usageInfo());
|
||||
|
||||
final long remainingQuota = maxTotalMediaSize - usage.bytesUsed();
|
||||
return CopyQuota.create(backupUser, toCopy, remainingQuota);
|
||||
} finally {
|
||||
Metrics.counter(USAGE_RECALCULATION_COUNTER_NAME, Tags.of(
|
||||
UserAgentTagUtil.getPlatformTag(backupUser.userAgent()),
|
||||
Tag.of("usageChanged", String.valueOf(usageChanged))))
|
||||
.increment();
|
||||
}
|
||||
}
|
||||
|
||||
public record RecalculationResult(UsageInfo oldUsage, UsageInfo newUsage) {}
|
||||
@@ -415,11 +417,14 @@ public class BackupManager {
|
||||
* @param backupUser an already ZK authenticated backup user
|
||||
* @param cdnNumber the cdn number to get backup credentials for
|
||||
* @return A map of headers to include with CDN requests
|
||||
* @throws BackupPermissionException if the credential does not have the correct level
|
||||
* @throws BackupInvalidArgumentException if the provided cdnNumber is invalid
|
||||
*/
|
||||
public Map<String, String> generateReadAuth(final AuthenticatedBackupUser backupUser, final int cdnNumber) {
|
||||
public Map<String, String> generateReadAuth(final AuthenticatedBackupUser backupUser, final int cdnNumber)
|
||||
throws BackupInvalidArgumentException, BackupPermissionException {
|
||||
checkBackupLevel(backupUser, BackupLevel.FREE);
|
||||
if (cdnNumber != 3) {
|
||||
throw Status.INVALID_ARGUMENT.withDescription("unknown cdn").asRuntimeException();
|
||||
throw new BackupInvalidArgumentException("unknown cdn");
|
||||
}
|
||||
return cdn3BackupCredentialGenerator.readHeaders(backupUser.backupDir());
|
||||
}
|
||||
@@ -429,8 +434,11 @@ public class BackupManager {
|
||||
*
|
||||
* @param backupUser an already ZK authenticated backup user
|
||||
* @return the credential that may be used with SVRB
|
||||
* @throws BackupPermissionException if the credential does not have the correct level
|
||||
* @throws BackupWrongCredentialTypeException if the credential does not have the messages type
|
||||
*/
|
||||
public ExternalServiceCredentials generateSvrbAuth(final AuthenticatedBackupUser backupUser) {
|
||||
public ExternalServiceCredentials generateSvrbAuth(final AuthenticatedBackupUser backupUser)
|
||||
throws BackupPermissionException, BackupWrongCredentialTypeException {
|
||||
checkBackupLevel(backupUser, BackupLevel.FREE);
|
||||
// Clients may only use SVRB with their messages backup-id
|
||||
checkBackupCredentialType(backupUser, BackupCredentialType.MESSAGES);
|
||||
@@ -460,59 +468,61 @@ public class BackupManager {
|
||||
* @param cursor A cursor returned by a previous call that can be used to resume listing
|
||||
* @param limit The maximum number of list results to return
|
||||
* @return A {@link ListMediaResult}
|
||||
* @throws BackupPermissionException if the credential does not have the correct level
|
||||
*/
|
||||
public CompletionStage<ListMediaResult> list(
|
||||
public ListMediaResult list(
|
||||
final AuthenticatedBackupUser backupUser,
|
||||
final Optional<String> cursor,
|
||||
final int limit) {
|
||||
final int limit) throws BackupPermissionException {
|
||||
checkBackupLevel(backupUser, BackupLevel.FREE);
|
||||
return remoteStorageManager.list(cdnMediaDirectory(backupUser), cursor, limit)
|
||||
.thenApply(result ->
|
||||
new ListMediaResult(
|
||||
result
|
||||
.objects()
|
||||
.stream()
|
||||
.map(entry -> new StorageDescriptorWithLength(
|
||||
remoteStorageManager.cdnNumber(),
|
||||
decodeMediaIdFromCdn(entry.key()),
|
||||
entry.length()
|
||||
))
|
||||
.toList(),
|
||||
result.cursor()
|
||||
));
|
||||
final RemoteStorageManager.ListResult result =
|
||||
remoteStorageManager.list(cdnMediaDirectory(backupUser), cursor, limit).toCompletableFuture().join();
|
||||
return new ListMediaResult(result
|
||||
.objects()
|
||||
.stream()
|
||||
.map(entry -> new StorageDescriptorWithLength(
|
||||
remoteStorageManager.cdnNumber(),
|
||||
decodeMediaIdFromCdn(entry.key()),
|
||||
entry.length()
|
||||
))
|
||||
.toList(),
|
||||
result.cursor());
|
||||
}
|
||||
|
||||
public CompletableFuture<Void> deleteEntireBackup(final AuthenticatedBackupUser backupUser) {
|
||||
public void deleteEntireBackup(final AuthenticatedBackupUser backupUser) throws BackupPermissionException {
|
||||
checkBackupLevel(backupUser, BackupLevel.FREE);
|
||||
|
||||
final int deletionConcurrency =
|
||||
dynamicConfigurationManager.getConfiguration().getBackupConfiguration().deletionConcurrency();
|
||||
|
||||
// Clients only include SVRB data with their messages backup-id
|
||||
final CompletableFuture<Void> svrbRemoval = switch(backupUser.credentialType()) {
|
||||
case BackupCredentialType.MESSAGES -> secureValueRecoveryBClient.removeData(svrbIdentifier(backupUser));
|
||||
case BackupCredentialType.MEDIA -> CompletableFuture.completedFuture(null);
|
||||
};
|
||||
return svrbRemoval.thenCompose(_ -> backupsDb
|
||||
// Try to swap out the backupDir for the user
|
||||
.scheduleBackupDeletion(backupUser)
|
||||
if (backupUser.credentialType() == BackupCredentialType.MESSAGES) {
|
||||
secureValueRecoveryBClient.removeData(svrbIdentifier(backupUser)).join();
|
||||
}
|
||||
try {
|
||||
// Try to swap out the backupDir for the user
|
||||
backupsDb.scheduleBackupDeletion(backupUser).join();
|
||||
} catch (Exception e) {
|
||||
final Throwable unwrapped = ExceptionUtils.unwrap(e);
|
||||
if (unwrapped instanceof BackupsDb.PendingDeletionException) {
|
||||
// If there was already a pending swap, try to delete the cdn objects directly
|
||||
.exceptionallyCompose(ExceptionUtils.exceptionallyHandler(BackupsDb.PendingDeletionException.class, e ->
|
||||
AsyncTimerUtil.record(SYNCHRONOUS_DELETE_TIMER, () ->
|
||||
deletePrefix(backupUser.backupDir(), deletionConcurrency)))));
|
||||
SYNCHRONOUS_DELETE_TIMER.record(() -> deletePrefix(backupUser.backupDir(), deletionConcurrency).join());
|
||||
} else {
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public Flux<StorageDescriptor> deleteMedia(final AuthenticatedBackupUser backupUser,
|
||||
final List<StorageDescriptor> storageDescriptors) {
|
||||
final List<StorageDescriptor> storageDescriptors)
|
||||
throws BackupPermissionException, BackupWrongCredentialTypeException {
|
||||
checkBackupLevel(backupUser, BackupLevel.FREE);
|
||||
checkBackupCredentialType(backupUser, BackupCredentialType.MEDIA);
|
||||
|
||||
// Check for a cdn we don't know how to process
|
||||
if (storageDescriptors.stream().anyMatch(sd -> sd.cdn() != remoteStorageManager.cdnNumber())) {
|
||||
throw Status.INVALID_ARGUMENT
|
||||
.withDescription("unsupported media cdn provided")
|
||||
.asRuntimeException();
|
||||
return Flux.error(new BackupInvalidArgumentException("unsupported media cdn provided"));
|
||||
}
|
||||
final DynamicBackupConfiguration backupConfiguration =
|
||||
dynamicConfigurationManager.getConfiguration().getBackupConfiguration();
|
||||
@@ -614,42 +624,40 @@ public class BackupManager {
|
||||
* @param presentation A {@link BackupAuthCredentialPresentation}
|
||||
* @param signature An XEd25519 signature of the presentation bytes
|
||||
* @return On authentication success, the authenticated backup-id and backup-tier encoded in the presentation
|
||||
* @throws BackupFailedZkAuthenticationException If the provided presentation or signature were invalid
|
||||
*/
|
||||
public CompletableFuture<AuthenticatedBackupUser> authenticateBackupUser(
|
||||
public AuthenticatedBackupUser authenticateBackupUser(
|
||||
final BackupAuthCredentialPresentation presentation,
|
||||
final byte[] signature,
|
||||
final String userAgentString) {
|
||||
final String userAgentString) throws BackupFailedZkAuthenticationException {
|
||||
|
||||
final PresentationSignatureVerifier signatureVerifier = verifyPresentation(presentation);
|
||||
return backupsDb
|
||||
.retrieveAuthenticationData(presentation.getBackupId())
|
||||
.thenApply(optionalAuthenticationData -> {
|
||||
final UserAgent userAgent = parseUserAgent(userAgentString);
|
||||
final BackupsDb.AuthenticationData authenticationData = optionalAuthenticationData
|
||||
.orElseGet(() -> {
|
||||
Metrics.counter(ZK_AUTHN_COUNTER_NAME, Tags.of(
|
||||
Tag.of(SUCCESS_TAG_NAME, String.valueOf(false)),
|
||||
Tag.of(FAILURE_REASON_TAG_NAME, "missing_public_key"),
|
||||
UserAgentTagUtil.getPlatformTag(userAgent)))
|
||||
.increment();
|
||||
// There was no stored public key, use a bunk public key so that validation will fail
|
||||
return new BackupsDb.AuthenticationData(INVALID_PUBLIC_KEY, null, null);
|
||||
});
|
||||
|
||||
final Pair<BackupCredentialType, BackupLevel> credentialTypeAndBackupLevel =
|
||||
signatureVerifier.verifySignature(signature, authenticationData.publicKey());
|
||||
|
||||
return new AuthenticatedBackupUser(
|
||||
presentation.getBackupId(),
|
||||
credentialTypeAndBackupLevel.first(),
|
||||
credentialTypeAndBackupLevel.second(),
|
||||
authenticationData.backupDir(),
|
||||
authenticationData.mediaDir(),
|
||||
userAgent);
|
||||
})
|
||||
.thenApply(result -> {
|
||||
Metrics.counter(ZK_AUTHN_COUNTER_NAME, SUCCESS_TAG_NAME, String.valueOf(true)).increment();
|
||||
return result;
|
||||
final Optional<BackupsDb.AuthenticationData> optionalAuthenticationData =
|
||||
backupsDb.retrieveAuthenticationData(presentation.getBackupId()).join();
|
||||
final UserAgent userAgent = parseUserAgent(userAgentString);
|
||||
final BackupsDb.AuthenticationData authenticationData = optionalAuthenticationData
|
||||
.orElseGet(() -> {
|
||||
Metrics.counter(ZK_AUTHN_COUNTER_NAME, Tags.of(
|
||||
Tag.of(SUCCESS_TAG_NAME, String.valueOf(false)),
|
||||
Tag.of(FAILURE_REASON_TAG_NAME, "missing_public_key"),
|
||||
UserAgentTagUtil.getPlatformTag(userAgent)))
|
||||
.increment();
|
||||
// There was no stored public key, use a bunk public key so that validation will fail
|
||||
return new BackupsDb.AuthenticationData(INVALID_PUBLIC_KEY, null, null);
|
||||
});
|
||||
|
||||
final Pair<BackupCredentialType, BackupLevel> credentialTypeAndBackupLevel =
|
||||
signatureVerifier.verifySignature(signature, authenticationData.publicKey());
|
||||
|
||||
Metrics.counter(ZK_AUTHN_COUNTER_NAME, SUCCESS_TAG_NAME, String.valueOf(true)).increment();
|
||||
return new AuthenticatedBackupUser(
|
||||
presentation.getBackupId(),
|
||||
credentialTypeAndBackupLevel.first(),
|
||||
credentialTypeAndBackupLevel.second(),
|
||||
authenticationData.backupDir(),
|
||||
authenticationData.mediaDir(),
|
||||
userAgent);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -701,7 +709,6 @@ public class BackupManager {
|
||||
* List and delete all files associated with a prefix
|
||||
*
|
||||
* @param prefixToDelete The prefix to expire.
|
||||
* @return A stage that completes when all objects with the given prefix have been deleted
|
||||
*/
|
||||
private CompletableFuture<Void> deletePrefix(final String prefixToDelete, int concurrentDeletes) {
|
||||
if (prefixToDelete.length() != BackupsDb.BACKUP_DIRECTORY_PATH_LENGTH
|
||||
@@ -732,7 +739,7 @@ public class BackupManager {
|
||||
|
||||
interface PresentationSignatureVerifier {
|
||||
|
||||
Pair<BackupCredentialType, BackupLevel> verifySignature(byte[] signature, ECPublicKey publicKey);
|
||||
Pair<BackupCredentialType, BackupLevel> verifySignature(byte[] signature, ECPublicKey publicKey) throws BackupFailedZkAuthenticationException;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -741,7 +748,8 @@ public class BackupManager {
|
||||
* @param presentation A ZK credential presentation that encodes the backupId and the receipt level of the requester
|
||||
* @return A function that can be used to verify a signature provided with the presentation
|
||||
*/
|
||||
private PresentationSignatureVerifier verifyPresentation(final BackupAuthCredentialPresentation presentation) {
|
||||
private PresentationSignatureVerifier verifyPresentation(final BackupAuthCredentialPresentation presentation)
|
||||
throws BackupFailedZkAuthenticationException {
|
||||
try {
|
||||
presentation.verify(clock.instant(), serverSecretParams);
|
||||
} catch (VerificationFailedException e) {
|
||||
@@ -749,10 +757,7 @@ public class BackupManager {
|
||||
SUCCESS_TAG_NAME, String.valueOf(false),
|
||||
FAILURE_REASON_TAG_NAME, "presentation_verification")
|
||||
.increment();
|
||||
throw Status.UNAUTHENTICATED
|
||||
.withDescription("backup auth credential presentation verification failed")
|
||||
.withCause(e)
|
||||
.asRuntimeException();
|
||||
throw new BackupFailedZkAuthenticationException("backup auth credential presentation verification failed");
|
||||
}
|
||||
return (signature, publicKey) -> {
|
||||
if (!publicKey.verifySignature(presentation.serialize(), signature)) {
|
||||
@@ -760,9 +765,7 @@ public class BackupManager {
|
||||
SUCCESS_TAG_NAME, String.valueOf(false),
|
||||
FAILURE_REASON_TAG_NAME, "signature_validation")
|
||||
.increment();
|
||||
throw Status.UNAUTHENTICATED
|
||||
.withDescription("backup auth credential presentation signature verification failed")
|
||||
.asRuntimeException();
|
||||
throw new BackupFailedZkAuthenticationException("backup auth credential presentation signature verification failed");
|
||||
}
|
||||
return new Pair<>(presentation.getType(), presentation.getBackupLevel());
|
||||
};
|
||||
@@ -773,19 +776,18 @@ public class BackupManager {
|
||||
*
|
||||
* @param backupUser The backup user to check
|
||||
* @param backupLevel The authorization level to verify the backupUser has access to
|
||||
* @throws {@link Status#PERMISSION_DENIED} error if the backup user is not authorized to access {@code backupLevel}
|
||||
* @throws BackupPermissionException if the backupUser is not authorized to access {@code backupLevel}
|
||||
*/
|
||||
@VisibleForTesting
|
||||
static void checkBackupLevel(final AuthenticatedBackupUser backupUser, final BackupLevel backupLevel) {
|
||||
static void checkBackupLevel(final AuthenticatedBackupUser backupUser, final BackupLevel backupLevel)
|
||||
throws BackupPermissionException {
|
||||
if (backupUser.backupLevel().compareTo(backupLevel) < 0) {
|
||||
Metrics.counter(ZK_AUTHZ_FAILURE_COUNTER_NAME, Tags.of(
|
||||
UserAgentTagUtil.getPlatformTag(backupUser.userAgent()),
|
||||
Tag.of(FAILURE_REASON_TAG_NAME, "level")))
|
||||
.increment();
|
||||
|
||||
throw Status.PERMISSION_DENIED
|
||||
.withDescription("credential does not support the requested operation")
|
||||
.asRuntimeException();
|
||||
throw new BackupPermissionException("credential does not support the requested operation");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -794,19 +796,17 @@ public class BackupManager {
|
||||
*
|
||||
* @param backupUser The backup user to check
|
||||
* @param credentialType The credential type to require
|
||||
* @throws {@link Status#UNAUTHENTICATED} error if the backup user is not authenticated with the given
|
||||
* @throws BackupWrongCredentialTypeException error if the backup user is not authenticated with the given
|
||||
* {@code credentialType}
|
||||
*/
|
||||
@VisibleForTesting
|
||||
static void checkBackupCredentialType(final AuthenticatedBackupUser backupUser, final BackupCredentialType credentialType) {
|
||||
static void checkBackupCredentialType(final AuthenticatedBackupUser backupUser, final BackupCredentialType credentialType) throws BackupWrongCredentialTypeException {
|
||||
if (backupUser.credentialType() != credentialType) {
|
||||
Metrics.counter(ZK_AUTHZ_FAILURE_COUNTER_NAME,
|
||||
FAILURE_REASON_TAG_NAME, "credential_type")
|
||||
.increment();
|
||||
|
||||
throw Status.UNAUTHENTICATED
|
||||
.withDescription("wrong credential type for the requested operation")
|
||||
.asRuntimeException();
|
||||
throw new BackupWrongCredentialTypeException("wrong credential type for the requested operation");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+11
@@ -0,0 +1,11 @@
|
||||
/*
|
||||
* Copyright 2026 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
package org.whispersystems.textsecuregcm.backup;
|
||||
|
||||
public class BackupMissingIdCommitmentException extends BackupException {
|
||||
public BackupMissingIdCommitmentException() {
|
||||
super();
|
||||
}
|
||||
}
|
||||
+12
@@ -0,0 +1,12 @@
|
||||
/*
|
||||
* Copyright 2026 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
package org.whispersystems.textsecuregcm.backup;
|
||||
|
||||
public class BackupNotFoundException extends BackupException {
|
||||
|
||||
public BackupNotFoundException(final String message) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
+11
@@ -0,0 +1,11 @@
|
||||
/*
|
||||
* Copyright 2026 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
package org.whispersystems.textsecuregcm.backup;
|
||||
|
||||
public class BackupPermissionException extends BackupException {
|
||||
public BackupPermissionException(String message) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
+8
@@ -0,0 +1,8 @@
|
||||
/*
|
||||
* Copyright 2026 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
package org.whispersystems.textsecuregcm.backup;
|
||||
|
||||
public class BackupPublicKeyConflictException extends BackupException {
|
||||
}
|
||||
+11
@@ -0,0 +1,11 @@
|
||||
/*
|
||||
* Copyright 2026 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
package org.whispersystems.textsecuregcm.backup;
|
||||
|
||||
public class BackupWrongCredentialTypeException extends BackupException {
|
||||
public BackupWrongCredentialTypeException(String message) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
@@ -4,8 +4,8 @@
|
||||
*/
|
||||
package org.whispersystems.textsecuregcm.backup;
|
||||
|
||||
import io.grpc.Status;
|
||||
import java.io.IOException;
|
||||
import java.io.UncheckedIOException;
|
||||
import java.security.MessageDigest;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import java.security.SecureRandom;
|
||||
@@ -22,18 +22,12 @@ import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.function.Predicate;
|
||||
import io.micrometer.core.instrument.DistributionSummary;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import io.micrometer.core.instrument.Tag;
|
||||
import io.micrometer.core.instrument.Tags;
|
||||
import org.signal.libsignal.protocol.InvalidKeyException;
|
||||
import org.signal.libsignal.protocol.ecc.ECPublicKey;
|
||||
import org.signal.libsignal.zkgroup.backups.BackupLevel;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.auth.AuthenticatedBackupUser;
|
||||
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
|
||||
import org.whispersystems.textsecuregcm.metrics.UserAgentTagUtil;
|
||||
import org.whispersystems.textsecuregcm.util.AttributeValues;
|
||||
import org.whispersystems.textsecuregcm.util.ExceptionUtils;
|
||||
import org.whispersystems.textsecuregcm.util.Util;
|
||||
@@ -133,7 +127,7 @@ public class BackupsDb {
|
||||
* @param authenticatedBackupLevel The backup level
|
||||
* @param publicKey The public key to associate with the backup id
|
||||
* @return A stage that completes when the public key has been set. If the backup-id already has a set public key that
|
||||
* does not match, the stage will be completed exceptionally with a {@link PublicKeyConflictException}
|
||||
* does not match, the stage will be completed exceptionally with a {@link BackupPublicKeyConflictException}
|
||||
*/
|
||||
CompletableFuture<Void> setPublicKey(
|
||||
final byte[] authenticatedBackupId,
|
||||
@@ -152,7 +146,7 @@ public class BackupsDb {
|
||||
.build())
|
||||
.exceptionally(ExceptionUtils.marshal(ConditionalCheckFailedException.class, e ->
|
||||
// There was already a row for this backup-id and it contained a different publicKey
|
||||
new PublicKeyConflictException()))
|
||||
new BackupPublicKeyConflictException()))
|
||||
.thenRun(Util.NOOP);
|
||||
}
|
||||
|
||||
@@ -190,9 +184,7 @@ public class BackupsDb {
|
||||
private static String getDirName(final Map<String, AttributeValue> item, final String attr) {
|
||||
return AttributeValues.get(item, attr).map(AttributeValue::s).orElseThrow(() -> {
|
||||
logger.error("Backups with public keys should have directory names");
|
||||
return Status.INTERNAL
|
||||
.withDescription("Backups with public keys must have directory names")
|
||||
.asRuntimeException();
|
||||
throw new UncheckedIOException(new IOException("Backups with public keys must have directory names"));
|
||||
});
|
||||
}
|
||||
|
||||
@@ -208,10 +200,7 @@ public class BackupsDb {
|
||||
return new ECPublicKey(publicKeyBytes);
|
||||
} catch (InvalidKeyException e) {
|
||||
logger.error("Invalid publicKey {}", HexFormat.of().formatHex(publicKeyBytes), e);
|
||||
throw Status.INTERNAL
|
||||
.withCause(e)
|
||||
.withDescription("Could not deserialize stored public key")
|
||||
.asRuntimeException();
|
||||
throw new UncheckedIOException(new IOException("Could not deserialize stored public key"));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -330,6 +319,7 @@ public class BackupsDb {
|
||||
* @param backupUser an already authorized backup user
|
||||
* @return A {@link BackupDescription} containing the cdn of the message backup and the total number of media space
|
||||
* bytes used by the backup user.
|
||||
* @throws BackupNotFoundException If the provided backupUser's backup-id does not exist
|
||||
*/
|
||||
CompletableFuture<BackupDescription> describeBackup(final AuthenticatedBackupUser backupUser) {
|
||||
return dynamoClient.getItem(GetItemRequest.builder()
|
||||
@@ -341,7 +331,7 @@ public class BackupsDb {
|
||||
.build())
|
||||
.thenApply(response -> {
|
||||
if (!response.hasItem()) {
|
||||
throw Status.NOT_FOUND.withDescription("Backup ID not found").asRuntimeException();
|
||||
throw ExceptionUtils.wrap(new BackupNotFoundException("Backup ID not found"));
|
||||
}
|
||||
// If the client hasn't already uploaded a backup, return the cdn we would return if they did create one
|
||||
final int cdn = AttributeValues.getInt(response.item(), ATTR_CDN, BACKUP_CDN);
|
||||
|
||||
-6
@@ -1,6 +0,0 @@
|
||||
package org.whispersystems.textsecuregcm.backup;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
public class PublicKeyConflictException extends IOException {
|
||||
}
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
/*
|
||||
* Copyright 2026 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.configuration;
|
||||
|
||||
import org.whispersystems.textsecuregcm.configuration.secrets.SecretString;
|
||||
import javax.annotation.Nullable;
|
||||
|
||||
public record HlrLookupConfiguration(SecretString apiKey,
|
||||
SecretString apiSecret,
|
||||
@Nullable String circuitBreakerConfigurationName,
|
||||
@Nullable String retryConfigurationName) {
|
||||
}
|
||||
+2
-1
@@ -14,7 +14,8 @@ import org.whispersystems.textsecuregcm.util.ExactlySize;
|
||||
|
||||
public record UnidentifiedDeliveryConfiguration(@NotNull @NotEmpty byte[] certificate,
|
||||
@ExactlySize(32) SecretBytes privateKey,
|
||||
int expiresDays) {
|
||||
int expiresDays,
|
||||
boolean embedSigner) {
|
||||
public ECPrivateKey ecPrivateKey() throws InvalidKeyException {
|
||||
return new ECPrivateKey(privateKey.value());
|
||||
}
|
||||
|
||||
+24
@@ -0,0 +1,24 @@
|
||||
/*
|
||||
* Copyright 2026 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.configuration.dynamic;
|
||||
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
import java.time.Duration;
|
||||
|
||||
public record DynamicCarrierDataLookupConfiguration(boolean enabled, @NotNull Duration maxCacheAge) {
|
||||
|
||||
public static Duration DEFAULT_MAX_CACHE_AGE = Duration.ofDays(7);
|
||||
|
||||
public DynamicCarrierDataLookupConfiguration() {
|
||||
this(false, DEFAULT_MAX_CACHE_AGE);
|
||||
}
|
||||
|
||||
public DynamicCarrierDataLookupConfiguration {
|
||||
if (maxCacheAge == null) {
|
||||
maxCacheAge = DEFAULT_MAX_CACHE_AGE;
|
||||
}
|
||||
}
|
||||
}
|
||||
+8
@@ -68,6 +68,10 @@ public class DynamicConfiguration {
|
||||
@Valid
|
||||
private DynamicBackupConfiguration backup = new DynamicBackupConfiguration();
|
||||
|
||||
@JsonProperty
|
||||
@Valid
|
||||
private DynamicCarrierDataLookupConfiguration carrierDataLookup = new DynamicCarrierDataLookupConfiguration();
|
||||
|
||||
public Optional<DynamicExperimentEnrollmentConfiguration> getExperimentEnrollmentConfiguration(
|
||||
final String experimentName) {
|
||||
return Optional.ofNullable(experiments.get(experimentName));
|
||||
@@ -121,4 +125,8 @@ public class DynamicConfiguration {
|
||||
public DynamicBackupConfiguration getBackupConfiguration() {
|
||||
return backup;
|
||||
}
|
||||
|
||||
public DynamicCarrierDataLookupConfiguration getCarrierDataLookupConfiguration() {
|
||||
return carrierDataLookup;
|
||||
}
|
||||
}
|
||||
+192
-171
@@ -47,28 +47,35 @@ import java.lang.annotation.RetentionPolicy;
|
||||
import java.lang.annotation.Target;
|
||||
import java.time.Clock;
|
||||
import java.time.Instant;
|
||||
import java.util.Arrays;
|
||||
import java.util.Base64;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.CompletionStage;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.Stream;
|
||||
import org.glassfish.jersey.server.ManagedAsync;
|
||||
import org.signal.libsignal.protocol.ecc.ECPublicKey;
|
||||
import org.signal.libsignal.zkgroup.InvalidInputException;
|
||||
import org.signal.libsignal.zkgroup.backups.BackupAuthCredentialPresentation;
|
||||
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.AuthenticatedBackupUser;
|
||||
import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
|
||||
import org.whispersystems.textsecuregcm.auth.ExternalServiceCredentials;
|
||||
import org.whispersystems.textsecuregcm.auth.RedemptionRange;
|
||||
import org.whispersystems.textsecuregcm.backup.BackupAuthManager;
|
||||
import org.whispersystems.textsecuregcm.backup.BackupBadReceiptException;
|
||||
import org.whispersystems.textsecuregcm.backup.BackupFailedZkAuthenticationException;
|
||||
import org.whispersystems.textsecuregcm.backup.BackupInvalidArgumentException;
|
||||
import org.whispersystems.textsecuregcm.backup.BackupManager;
|
||||
import org.whispersystems.textsecuregcm.backup.BackupMissingIdCommitmentException;
|
||||
import org.whispersystems.textsecuregcm.backup.BackupNotFoundException;
|
||||
import org.whispersystems.textsecuregcm.backup.BackupPermissionException;
|
||||
import org.whispersystems.textsecuregcm.backup.BackupUploadDescriptor;
|
||||
import org.whispersystems.textsecuregcm.backup.BackupWrongCredentialTypeException;
|
||||
import org.whispersystems.textsecuregcm.backup.CopyParameters;
|
||||
import org.whispersystems.textsecuregcm.backup.CopyResult;
|
||||
import org.whispersystems.textsecuregcm.backup.MediaEncryptionParameters;
|
||||
@@ -83,8 +90,6 @@ import org.whispersystems.textsecuregcm.util.ByteArrayAdapter;
|
||||
import org.whispersystems.textsecuregcm.util.ByteArrayBase64UrlAdapter;
|
||||
import org.whispersystems.textsecuregcm.util.ECPublicKeyAdapter;
|
||||
import org.whispersystems.textsecuregcm.util.ExactlySize;
|
||||
import org.whispersystems.textsecuregcm.util.Util;
|
||||
import reactor.core.publisher.Mono;
|
||||
|
||||
@Path("/v1/archives")
|
||||
@io.swagger.v3.oas.annotations.tags.Tag(name = "Archive")
|
||||
@@ -149,24 +154,21 @@ public class ArchiveController {
|
||||
@ApiResponse(responseCode = "400", description = "The provided backup auth credential request was invalid")
|
||||
@ApiResponse(responseCode = "403", description = "The device did not have permission to set the backup-id. Only the primary device can set the backup-id for an account")
|
||||
@ApiResponse(responseCode = "429", description = "Rate limited. Too many attempts to change the backup-id have been made")
|
||||
public CompletionStage<Response> setBackupId(
|
||||
@ManagedAsync
|
||||
public void setBackupId(
|
||||
@Auth final AuthenticatedDevice authenticatedDevice,
|
||||
@Valid @NotNull final SetBackupIdRequest setBackupIdRequest) throws RateLimitExceededException {
|
||||
@Valid @NotNull final SetBackupIdRequest setBackupIdRequest)
|
||||
throws RateLimitExceededException, BackupInvalidArgumentException, BackupPermissionException {
|
||||
|
||||
return accountsManager.getByAccountIdentifierAsync(authenticatedDevice.accountIdentifier())
|
||||
.thenCompose(maybeAccount -> {
|
||||
final Account account = maybeAccount
|
||||
.orElseThrow(() -> new WebApplicationException(Response.Status.UNAUTHORIZED));
|
||||
final Account account = accountsManager.getByAccountIdentifier(authenticatedDevice.accountIdentifier())
|
||||
.orElseThrow(() -> new WebApplicationException(Response.Status.UNAUTHORIZED));
|
||||
final Device device = account.getDevice(authenticatedDevice.deviceId())
|
||||
.orElseThrow(() -> new WebApplicationException(Response.Status.UNAUTHORIZED));
|
||||
|
||||
final Device device = account.getDevice(authenticatedDevice.deviceId())
|
||||
.orElseThrow(() -> new WebApplicationException(Response.Status.UNAUTHORIZED));
|
||||
|
||||
return backupAuthManager
|
||||
.commitBackupId(account, device,
|
||||
Optional.ofNullable(setBackupIdRequest.messagesBackupAuthCredentialRequest),
|
||||
Optional.ofNullable(setBackupIdRequest.mediaBackupAuthCredentialRequest))
|
||||
.thenApply(Util.ASYNC_EMPTY_RESPONSE);
|
||||
});
|
||||
backupAuthManager
|
||||
.commitBackupId(account, device,
|
||||
Optional.ofNullable(setBackupIdRequest.messagesBackupAuthCredentialRequest),
|
||||
Optional.ofNullable(setBackupIdRequest.mediaBackupAuthCredentialRequest));
|
||||
}
|
||||
|
||||
|
||||
@@ -186,15 +188,13 @@ public class ArchiveController {
|
||||
""")
|
||||
@ApiResponse(responseCode = "200", description = "Successfully retrieved backup-id rotation limits", useReturnTypeSchema = true)
|
||||
@ApiResponse(responseCode = "403", description = "Invalid account authentication")
|
||||
public CompletionStage<BackupIdLimitResponse> checkLimits(@Auth final AuthenticatedDevice authenticatedDevice) {
|
||||
return accountsManager.getByAccountIdentifierAsync(authenticatedDevice.accountIdentifier())
|
||||
.thenCompose(maybeAccount -> {
|
||||
final Account account = maybeAccount
|
||||
.orElseThrow(() -> new WebApplicationException(Response.Status.UNAUTHORIZED));
|
||||
@ManagedAsync
|
||||
public BackupIdLimitResponse checkLimits(@Auth final AuthenticatedDevice authenticatedDevice) {
|
||||
final Account account = accountsManager.getByAccountIdentifier(authenticatedDevice.accountIdentifier())
|
||||
.orElseThrow(() -> new WebApplicationException(Response.Status.UNAUTHORIZED));
|
||||
|
||||
return backupAuthManager.checkBackupIdRotationLimit(account).thenApply(limit ->
|
||||
new BackupIdLimitResponse(limit.hasPermitsRemaining(), limit.nextPermitAvailable().getSeconds()));
|
||||
});
|
||||
final BackupAuthManager.BackupIdRotationLimit limit = backupAuthManager.checkBackupIdRotationLimit(account);
|
||||
return new BackupIdLimitResponse(limit.hasPermitsRemaining(), limit.nextPermitAvailable().getSeconds());
|
||||
}
|
||||
|
||||
public record RedeemBackupReceiptRequest(
|
||||
@@ -237,18 +237,17 @@ public class ArchiveController {
|
||||
@ApiResponse(responseCode = "400", description = "The provided presentation or receipt was invalid")
|
||||
@ApiResponse(responseCode = "409", description = "The target account does not have a backup-id commitment")
|
||||
@ApiResponse(responseCode = "429", description = "Rate limited.")
|
||||
public CompletionStage<Response> redeemReceipt(
|
||||
@ManagedAsync
|
||||
public Response redeemReceipt(
|
||||
@Auth final AuthenticatedDevice authenticatedDevice,
|
||||
@Valid @NotNull final RedeemBackupReceiptRequest redeemBackupReceiptRequest) {
|
||||
@Valid @NotNull final RedeemBackupReceiptRequest redeemBackupReceiptRequest)
|
||||
throws BackupInvalidArgumentException, BackupMissingIdCommitmentException, BackupBadReceiptException {
|
||||
|
||||
return accountsManager.getByAccountIdentifierAsync(authenticatedDevice.accountIdentifier())
|
||||
.thenCompose(maybeAccount -> {
|
||||
final Account account = maybeAccount
|
||||
.orElseThrow(() -> new WebApplicationException(Response.Status.UNAUTHORIZED));
|
||||
final Account account = accountsManager.getByAccountIdentifier(authenticatedDevice.accountIdentifier())
|
||||
.orElseThrow(() -> new WebApplicationException(Response.Status.UNAUTHORIZED));
|
||||
|
||||
return backupAuthManager.redeemReceipt(account, redeemBackupReceiptRequest.receiptCredentialPresentation())
|
||||
.thenApply(Util.ASYNC_EMPTY_RESPONSE);
|
||||
});
|
||||
backupAuthManager.redeemReceipt(account, redeemBackupReceiptRequest.receiptCredentialPresentation());
|
||||
return Response.noContent().build();
|
||||
}
|
||||
|
||||
public record BackupAuthCredentialsResponse(
|
||||
@@ -306,14 +305,15 @@ public class ArchiveController {
|
||||
@ApiResponse(responseCode = "400", description = "The start/end did not meet alignment/duration requirements")
|
||||
@ApiResponse(responseCode = "404", description = "Could not find an existing blinded backup id")
|
||||
@ApiResponse(responseCode = "429", description = "Rate limited.")
|
||||
public CompletionStage<BackupAuthCredentialsResponse> getBackupZKCredentials(
|
||||
@ManagedAsync
|
||||
public BackupAuthCredentialsResponse getBackupZKCredentials(
|
||||
@Auth AuthenticatedDevice authenticatedDevice,
|
||||
@HeaderParam(HttpHeaders.USER_AGENT) final String userAgent,
|
||||
@NotNull @QueryParam("redemptionStartSeconds") Long startSeconds,
|
||||
@NotNull @QueryParam("redemptionEndSeconds") Long endSeconds) {
|
||||
@NotNull @QueryParam("redemptionEndSeconds") Long endSeconds) throws BackupNotFoundException {
|
||||
|
||||
final Map<BackupCredentialType, List<BackupAuthCredentialsResponse.BackupAuthCredential>> credentialsByType =
|
||||
new ConcurrentHashMap<>();
|
||||
new HashMap<>();
|
||||
|
||||
final RedemptionRange redemptionRange;
|
||||
try {
|
||||
@@ -322,33 +322,26 @@ public class ArchiveController {
|
||||
throw new BadRequestException(e.getMessage());
|
||||
}
|
||||
|
||||
return accountsManager.getByAccountIdentifierAsync(authenticatedDevice.accountIdentifier())
|
||||
.thenCompose(maybeAccount -> {
|
||||
final Account account = maybeAccount
|
||||
.orElseThrow(() -> new WebApplicationException(Response.Status.UNAUTHORIZED));
|
||||
final Account account = accountsManager.getByAccountIdentifier(authenticatedDevice.accountIdentifier())
|
||||
.orElseThrow(() -> new WebApplicationException(Response.Status.UNAUTHORIZED));
|
||||
|
||||
return CompletableFuture.allOf(Arrays.stream(BackupCredentialType.values())
|
||||
.map(credentialType -> this.backupAuthManager.getBackupAuthCredentials(
|
||||
account,
|
||||
credentialType,
|
||||
redemptionRange)
|
||||
.thenAccept(credentials -> {
|
||||
backupMetrics.updateGetCredentialCounter(
|
||||
UserAgentTagUtil.getPlatformTag(userAgent),
|
||||
credentialType,
|
||||
credentials.size());
|
||||
credentialsByType.put(credentialType, credentials.stream()
|
||||
.map(credential -> new BackupAuthCredentialsResponse.BackupAuthCredential(
|
||||
credential.credential().serialize(),
|
||||
credential.redemptionTime().getEpochSecond()))
|
||||
.toList());
|
||||
}))
|
||||
.toArray(CompletableFuture[]::new))
|
||||
.thenApply(ignored -> new BackupAuthCredentialsResponse(credentialsByType.entrySet().stream()
|
||||
.collect(Collectors.toMap(
|
||||
e -> BackupAuthCredentialsResponse.CredentialType.fromLibsignalType(e.getKey()),
|
||||
Map.Entry::getValue))));
|
||||
});
|
||||
for (BackupCredentialType credentialType : BackupCredentialType.values()) {
|
||||
final List<BackupAuthManager.Credential> credentials =
|
||||
backupAuthManager.getBackupAuthCredentials(account, credentialType, redemptionRange);
|
||||
backupMetrics.updateGetCredentialCounter(
|
||||
UserAgentTagUtil.getPlatformTag(userAgent),
|
||||
credentialType,
|
||||
credentials.size());
|
||||
credentialsByType.put(credentialType, credentials.stream()
|
||||
.map(credential -> new BackupAuthCredentialsResponse.BackupAuthCredential(
|
||||
credential.credential().serialize(),
|
||||
credential.redemptionTime().getEpochSecond()))
|
||||
.toList());
|
||||
}
|
||||
return new BackupAuthCredentialsResponse(credentialsByType.entrySet().stream()
|
||||
.collect(Collectors.toMap(
|
||||
e -> BackupAuthCredentialsResponse.CredentialType.fromLibsignalType(e.getKey()),
|
||||
Map.Entry::getValue)));
|
||||
}
|
||||
|
||||
|
||||
@@ -408,9 +401,11 @@ public class ArchiveController {
|
||||
summary = "Get CDN read credentials",
|
||||
description = "Retrieve credentials used to read objects stored on the backup cdn")
|
||||
@ApiResponse(responseCode = "200", content = @Content(schema = @Schema(implementation = ReadAuthResponse.class)))
|
||||
@ApiResponse(responseCode = "400", description = "Bad arguments. The request may have been made on an authenticated channel, or an invalid cdn number was provided")
|
||||
@ApiResponse(responseCode = "429", description = "Rate limited.")
|
||||
@ApiResponseZkAuth
|
||||
public CompletionStage<ReadAuthResponse> readAuth(
|
||||
@ManagedAsync
|
||||
public ReadAuthResponse readAuth(
|
||||
@Auth final Optional<AuthenticatedDevice> account,
|
||||
@HeaderParam(HttpHeaders.USER_AGENT) final String userAgent,
|
||||
|
||||
@@ -422,13 +417,14 @@ public class ArchiveController {
|
||||
@NotNull
|
||||
@HeaderParam(X_SIGNAL_ZK_AUTH_SIGNATURE) final BackupAuthCredentialPresentationSignature signature,
|
||||
|
||||
@NotNull @Parameter(description = "The number of the CDN to get credentials for") @QueryParam("cdn") final Integer cdn) {
|
||||
@NotNull @Parameter(description = "The number of the CDN to get credentials for") @QueryParam("cdn") final Integer cdn)
|
||||
throws BackupFailedZkAuthenticationException, BackupInvalidArgumentException, BackupPermissionException {
|
||||
if (account.isPresent()) {
|
||||
throw new BadRequestException("must not use authenticated connection for anonymous operations");
|
||||
}
|
||||
return backupManager.authenticateBackupUser(presentation.presentation, signature.signature, userAgent)
|
||||
.thenApply(user -> backupManager.generateReadAuth(user, cdn))
|
||||
.thenApply(ReadAuthResponse::new);
|
||||
final AuthenticatedBackupUser backupUser =
|
||||
backupManager.authenticateBackupUser(presentation.presentation, signature.signature, userAgent);
|
||||
return new ReadAuthResponse(backupManager.generateReadAuth(backupUser, cdn));
|
||||
}
|
||||
|
||||
@GET
|
||||
@@ -441,7 +437,8 @@ public class ArchiveController {
|
||||
""")
|
||||
@ApiResponse(responseCode = "200", description = "`JSON` with generated credentials.", useReturnTypeSchema = true)
|
||||
@ApiResponseZkAuth
|
||||
public CompletionStage<ExternalServiceCredentials> svrbAuth(
|
||||
@ManagedAsync
|
||||
public ExternalServiceCredentials svrbAuth(
|
||||
@Auth final Optional<AuthenticatedDevice> account,
|
||||
@HeaderParam(HttpHeaders.USER_AGENT) final String userAgent,
|
||||
|
||||
@@ -451,13 +448,14 @@ public class ArchiveController {
|
||||
|
||||
@Parameter(description = BackupAuthCredentialPresentationSignature.DESCRIPTION, schema = @Schema(implementation = String.class))
|
||||
@NotNull
|
||||
@HeaderParam(X_SIGNAL_ZK_AUTH_SIGNATURE) final BackupAuthCredentialPresentationSignature signature) {
|
||||
@HeaderParam(X_SIGNAL_ZK_AUTH_SIGNATURE) final BackupAuthCredentialPresentationSignature signature)
|
||||
throws BackupFailedZkAuthenticationException, BackupWrongCredentialTypeException, BackupPermissionException {
|
||||
if (account.isPresent()) {
|
||||
throw new BadRequestException("must not use authenticated connection for anonymous operations");
|
||||
}
|
||||
return backupManager
|
||||
.authenticateBackupUser(presentation.presentation, signature.signature, userAgent)
|
||||
.thenApply(backupManager::generateSvrbAuth);
|
||||
final AuthenticatedBackupUser backupUser =
|
||||
backupManager.authenticateBackupUser(presentation.presentation, signature.signature, userAgent);
|
||||
return backupManager.generateSvrbAuth(backupUser);
|
||||
}
|
||||
|
||||
public record BackupInfoResponse(
|
||||
@@ -491,7 +489,8 @@ public class ArchiveController {
|
||||
@ApiResponse(responseCode = "404", description = "No existing backups found")
|
||||
@ApiResponse(responseCode = "429", description = "Rate limited.")
|
||||
@ApiResponseZkAuth
|
||||
public CompletionStage<BackupInfoResponse> backupInfo(
|
||||
@ManagedAsync
|
||||
public BackupInfoResponse backupInfo(
|
||||
@Auth final Optional<AuthenticatedDevice> account,
|
||||
@HeaderParam(HttpHeaders.USER_AGENT) final String userAgent,
|
||||
|
||||
@@ -501,19 +500,21 @@ public class ArchiveController {
|
||||
|
||||
@Parameter(description = BackupAuthCredentialPresentationSignature.DESCRIPTION, schema = @Schema(implementation = String.class))
|
||||
@NotNull
|
||||
@HeaderParam(X_SIGNAL_ZK_AUTH_SIGNATURE) final BackupAuthCredentialPresentationSignature signature) {
|
||||
@HeaderParam(X_SIGNAL_ZK_AUTH_SIGNATURE) final BackupAuthCredentialPresentationSignature signature)
|
||||
throws BackupFailedZkAuthenticationException, BackupNotFoundException, BackupPermissionException {
|
||||
if (account.isPresent()) {
|
||||
throw new BadRequestException("must not use authenticated connection for anonymous operations");
|
||||
}
|
||||
|
||||
return backupManager.authenticateBackupUser(presentation.presentation, signature.signature, userAgent)
|
||||
.thenCompose(backupManager::backupInfo)
|
||||
.thenApply(backupInfo -> new BackupInfoResponse(
|
||||
final AuthenticatedBackupUser backupUser =
|
||||
backupManager.authenticateBackupUser(presentation.presentation, signature.signature, userAgent);
|
||||
final BackupManager.BackupInfo backupInfo = backupManager.backupInfo(backupUser);
|
||||
return new BackupInfoResponse(
|
||||
backupInfo.cdn(),
|
||||
backupInfo.backupSubdir(),
|
||||
backupInfo.mediaSubdir(),
|
||||
backupInfo.messageBackupKey(),
|
||||
backupInfo.mediaUsedSpace().orElse(0L)));
|
||||
backupInfo.mediaUsedSpace().orElse(0L));
|
||||
}
|
||||
|
||||
public record SetPublicKeyRequest(
|
||||
@@ -531,13 +532,14 @@ public class ArchiveController {
|
||||
summary = "Set public key",
|
||||
description = """
|
||||
Permanently set the public key of an ED25519 key-pair for the backup-id. All requests that provide a anonymous
|
||||
BackupAuthCredentialPresentation (including this one!) must also sign the presentation with the private key
|
||||
BackupAuthCredentialPresentation (including this one!) must also sign the presentation with the private key
|
||||
corresponding to the provided public key.
|
||||
""")
|
||||
@ApiResponseZkAuth
|
||||
@ApiResponse(responseCode = "204", description = "The public key was set")
|
||||
@ApiResponse(responseCode = "429", description = "Rate limited.")
|
||||
public CompletionStage<Response> setPublicKey(
|
||||
@ManagedAsync
|
||||
public void setPublicKey(
|
||||
@Auth final Optional<AuthenticatedDevice> account,
|
||||
|
||||
@Parameter(description = BackupAuthCredentialPresentationHeader.DESCRIPTION, schema = @Schema(implementation = String.class))
|
||||
@@ -548,13 +550,12 @@ public class ArchiveController {
|
||||
@NotNull
|
||||
@HeaderParam(X_SIGNAL_ZK_AUTH_SIGNATURE) final BackupAuthCredentialPresentationSignature signature,
|
||||
|
||||
@Valid @NotNull SetPublicKeyRequest setPublicKeyRequest) {
|
||||
@Valid @NotNull SetPublicKeyRequest setPublicKeyRequest)
|
||||
throws BackupFailedZkAuthenticationException {
|
||||
if (account.isPresent()) {
|
||||
throw new BadRequestException("must not use authenticated connection for anonymous operations");
|
||||
}
|
||||
return backupManager
|
||||
.setPublicKey(presentation.presentation, signature.signature, setPublicKeyRequest.backupIdPublicKey)
|
||||
.thenApply(Util.ASYNC_EMPTY_RESPONSE);
|
||||
backupManager.setPublicKey(presentation.presentation, signature.signature, setPublicKeyRequest.backupIdPublicKey);
|
||||
}
|
||||
|
||||
|
||||
@@ -578,7 +579,8 @@ public class ArchiveController {
|
||||
@ApiResponse(responseCode = "429", description = "Rate limited.")
|
||||
@ApiResponse(responseCode = "413", description = "The provided uploadLength is larger than the maximum supported upload size. The maximum upload size is subject to change.")
|
||||
@ApiResponseZkAuth
|
||||
public CompletionStage<UploadDescriptorResponse> backup(
|
||||
@ManagedAsync
|
||||
public UploadDescriptorResponse backup(
|
||||
@Auth final Optional<AuthenticatedDevice> account,
|
||||
@HeaderParam(HttpHeaders.USER_AGENT) final String userAgent,
|
||||
|
||||
@@ -591,26 +593,30 @@ public class ArchiveController {
|
||||
@HeaderParam(X_SIGNAL_ZK_AUTH_SIGNATURE) final BackupAuthCredentialPresentationSignature signature,
|
||||
|
||||
@Parameter(description = "The size of the message backup to upload in bytes")
|
||||
@QueryParam("uploadLength") final Optional<Long> uploadLength) {
|
||||
@QueryParam("uploadLength") final Optional<Long> uploadLength)
|
||||
throws BackupFailedZkAuthenticationException, BackupWrongCredentialTypeException, BackupPermissionException {
|
||||
if (account.isPresent()) {
|
||||
throw new BadRequestException("must not use authenticated connection for anonymous operations");
|
||||
}
|
||||
return backupManager.authenticateBackupUser(presentation.presentation, signature.signature, userAgent)
|
||||
.thenCompose(backupUser -> {
|
||||
final boolean oversize = uploadLength
|
||||
.map(length -> length > BackupManager.MAX_MESSAGE_BACKUP_OBJECT_SIZE)
|
||||
.orElse(false);
|
||||
backupMetrics.updateMessageBackupSizeDistribution(backupUser, oversize, uploadLength);
|
||||
if (oversize) {
|
||||
throw new ClientErrorException("exceeded maximum uploadLength", Response.Status.REQUEST_ENTITY_TOO_LARGE);
|
||||
}
|
||||
return backupManager.createMessageBackupUploadDescriptor(backupUser);
|
||||
})
|
||||
.thenApply(result -> new UploadDescriptorResponse(
|
||||
result.cdn(),
|
||||
result.key(),
|
||||
result.headers(),
|
||||
result.signedUploadLocation()));
|
||||
|
||||
final AuthenticatedBackupUser backupUser =
|
||||
backupManager.authenticateBackupUser(presentation.presentation, signature.signature, userAgent);
|
||||
|
||||
final boolean oversize = uploadLength
|
||||
.map(length -> length > BackupManager.MAX_MESSAGE_BACKUP_OBJECT_SIZE)
|
||||
.orElse(false);
|
||||
|
||||
backupMetrics.updateMessageBackupSizeDistribution(backupUser, oversize, uploadLength);
|
||||
if (oversize) {
|
||||
throw new ClientErrorException("exceeded maximum uploadLength", Response.Status.REQUEST_ENTITY_TOO_LARGE);
|
||||
}
|
||||
final BackupUploadDescriptor uploadDescriptor =
|
||||
backupManager.createMessageBackupUploadDescriptor(backupUser);
|
||||
return new UploadDescriptorResponse(
|
||||
uploadDescriptor.cdn(),
|
||||
uploadDescriptor.key(),
|
||||
uploadDescriptor.headers(),
|
||||
uploadDescriptor.signedUploadLocation());
|
||||
}
|
||||
|
||||
@GET
|
||||
@@ -627,7 +633,8 @@ public class ArchiveController {
|
||||
@ApiResponse(responseCode = "200", content = @Content(schema = @Schema(implementation = UploadDescriptorResponse.class)))
|
||||
@ApiResponse(responseCode = "429", description = "Rate limited.")
|
||||
@ApiResponseZkAuth
|
||||
public CompletionStage<UploadDescriptorResponse> uploadTemporaryAttachment(
|
||||
@ManagedAsync
|
||||
public UploadDescriptorResponse uploadTemporaryAttachment(
|
||||
@Auth final Optional<AuthenticatedDevice> account,
|
||||
@HeaderParam(HttpHeaders.USER_AGENT) final String userAgent,
|
||||
|
||||
@@ -638,17 +645,20 @@ public class ArchiveController {
|
||||
|
||||
@Parameter(description = BackupAuthCredentialPresentationSignature.DESCRIPTION, schema = @Schema(implementation = String.class))
|
||||
@NotNull
|
||||
@HeaderParam(X_SIGNAL_ZK_AUTH_SIGNATURE) final BackupAuthCredentialPresentationSignature signature) {
|
||||
@HeaderParam(X_SIGNAL_ZK_AUTH_SIGNATURE) final BackupAuthCredentialPresentationSignature signature)
|
||||
throws RateLimitExceededException, BackupFailedZkAuthenticationException, BackupWrongCredentialTypeException, BackupPermissionException {
|
||||
if (account.isPresent()) {
|
||||
throw new BadRequestException("must not use authenticated connection for anonymous operations");
|
||||
}
|
||||
return backupManager.authenticateBackupUser(presentation.presentation, signature.signature, userAgent)
|
||||
.thenCompose(backupManager::createTemporaryAttachmentUploadDescriptor)
|
||||
.thenApply(result -> new UploadDescriptorResponse(
|
||||
result.cdn(),
|
||||
result.key(),
|
||||
result.headers(),
|
||||
result.signedUploadLocation()));
|
||||
final AuthenticatedBackupUser backupUser =
|
||||
backupManager.authenticateBackupUser(presentation.presentation, signature.signature, userAgent);
|
||||
final BackupUploadDescriptor uploadDescriptor =
|
||||
backupManager.createTemporaryAttachmentUploadDescriptor(backupUser);
|
||||
return new UploadDescriptorResponse(
|
||||
uploadDescriptor.cdn(),
|
||||
uploadDescriptor.key(),
|
||||
uploadDescriptor.headers(),
|
||||
uploadDescriptor.signedUploadLocation());
|
||||
}
|
||||
|
||||
public record CopyMediaRequest(
|
||||
@@ -715,7 +725,8 @@ public class ArchiveController {
|
||||
@ApiResponse(responseCode = "410", description = "The source object was not found.")
|
||||
@ApiResponse(responseCode = "429", description = "Rate limited.")
|
||||
@ApiResponseZkAuth
|
||||
public CompletionStage<CopyMediaResponse> copyMedia(
|
||||
@ManagedAsync
|
||||
public CopyMediaResponse copyMedia(
|
||||
@Auth final Optional<AuthenticatedDevice> account,
|
||||
@HeaderParam(HttpHeaders.USER_AGENT) final String userAgent,
|
||||
|
||||
@@ -728,24 +739,27 @@ public class ArchiveController {
|
||||
@HeaderParam(X_SIGNAL_ZK_AUTH_SIGNATURE) final BackupAuthCredentialPresentationSignature signature,
|
||||
|
||||
@NotNull
|
||||
@Valid final ArchiveController.CopyMediaRequest copyMediaRequest) {
|
||||
@Valid final ArchiveController.CopyMediaRequest copyMediaRequest)
|
||||
throws BackupFailedZkAuthenticationException, BackupWrongCredentialTypeException, BackupPermissionException, BackupInvalidArgumentException {
|
||||
if (account.isPresent()) {
|
||||
throw new BadRequestException("must not use authenticated connection for anonymous operations");
|
||||
}
|
||||
|
||||
return Mono
|
||||
.fromFuture(backupManager.authenticateBackupUser(presentation.presentation, signature.signature, userAgent))
|
||||
.flatMap(backupUser -> backupManager.copyToBackup(backupUser, List.of(copyMediaRequest.toCopyParameters()))
|
||||
.next()
|
||||
.doOnNext(result -> backupMetrics.updateCopyCounter(result, UserAgentTagUtil.getPlatformTag(userAgent)))
|
||||
.map(copyResult -> switch (copyResult.outcome()) {
|
||||
case SUCCESS -> new CopyMediaResponse(copyResult.cdn());
|
||||
case SOURCE_WRONG_LENGTH -> throw new BadRequestException("Invalid length");
|
||||
case SOURCE_NOT_FOUND -> throw new ClientErrorException("Source object not found", Response.Status.GONE);
|
||||
case OUT_OF_QUOTA ->
|
||||
throw new ClientErrorException("Media quota exhausted", Response.Status.REQUEST_ENTITY_TOO_LARGE);
|
||||
}))
|
||||
.toFuture();
|
||||
final AuthenticatedBackupUser backupUser =
|
||||
backupManager.authenticateBackupUser(presentation.presentation, signature.signature, userAgent);
|
||||
final BackupManager.CopyQuota copyQuota =
|
||||
backupManager.getCopyQuota(backupUser, List.of(copyMediaRequest.toCopyParameters()));
|
||||
final CopyResult copyResult = backupManager.copyToBackup(copyQuota).next()
|
||||
.blockOptional()
|
||||
.orElseThrow(() -> new IllegalStateException("Non empty copy request must return result"));
|
||||
backupMetrics.updateCopyCounter(copyResult, UserAgentTagUtil.getPlatformTag(userAgent));
|
||||
return switch (copyResult.outcome()) {
|
||||
case SUCCESS -> new CopyMediaResponse(copyResult.cdn());
|
||||
case SOURCE_WRONG_LENGTH -> throw new BadRequestException("Invalid length");
|
||||
case SOURCE_NOT_FOUND -> throw new ClientErrorException("Source object not found", Response.Status.GONE);
|
||||
case OUT_OF_QUOTA ->
|
||||
throw new ClientErrorException("Media quota exhausted", Response.Status.REQUEST_ENTITY_TOO_LARGE);
|
||||
};
|
||||
}
|
||||
|
||||
public record CopyMediaBatchRequest(
|
||||
@@ -808,13 +822,14 @@ public class ArchiveController {
|
||||
be provided as a separate entry in the response.
|
||||
""")
|
||||
@ApiResponse(responseCode = "207", description = """
|
||||
The request was processed and each operation's outcome must be inspected individually. This does NOT necessarily
|
||||
The request was processed and each operation's outcome must be inspected individually. This does NOT necessarily
|
||||
indicate the operation was a success.
|
||||
""", content = @Content(schema = @Schema(implementation = CopyMediaBatchResponse.class)))
|
||||
@ApiResponse(responseCode = "413", description = "All media capacity has been consumed. Free some space to continue.")
|
||||
@ApiResponse(responseCode = "429", description = "Rate limited.")
|
||||
@ApiResponseZkAuth
|
||||
public CompletionStage<Response> copyMedia(
|
||||
@ManagedAsync
|
||||
public Response copyMedia(
|
||||
@Auth final Optional<AuthenticatedDevice> account,
|
||||
@HeaderParam(HttpHeaders.USER_AGENT) final String userAgent,
|
||||
|
||||
@@ -827,19 +842,21 @@ public class ArchiveController {
|
||||
@HeaderParam(X_SIGNAL_ZK_AUTH_SIGNATURE) final BackupAuthCredentialPresentationSignature signature,
|
||||
|
||||
@NotNull
|
||||
@Valid final ArchiveController.CopyMediaBatchRequest copyMediaRequest) {
|
||||
@Valid final ArchiveController.CopyMediaBatchRequest copyMediaRequest)
|
||||
throws BackupFailedZkAuthenticationException, BackupWrongCredentialTypeException, BackupPermissionException, BackupInvalidArgumentException {
|
||||
|
||||
if (account.isPresent()) {
|
||||
throw new BadRequestException("must not use authenticated connection for anonymous operations");
|
||||
}
|
||||
final Stream<CopyParameters> copyParams = copyMediaRequest.items().stream().map(CopyMediaRequest::toCopyParameters);
|
||||
return Mono.fromFuture(backupManager.authenticateBackupUser(presentation.presentation, signature.signature, userAgent))
|
||||
.flatMapMany(backupUser -> backupManager.copyToBackup(backupUser, copyParams.toList()))
|
||||
final AuthenticatedBackupUser backupUser =
|
||||
backupManager.authenticateBackupUser(presentation.presentation, signature.signature, userAgent);
|
||||
final BackupManager.CopyQuota copyQuota = backupManager.getCopyQuota(backupUser, copyParams.toList());
|
||||
final List<CopyMediaBatchResponse.Entry> copyResults = backupManager.copyToBackup(copyQuota)
|
||||
.doOnNext(result -> backupMetrics.updateCopyCounter(result, UserAgentTagUtil.getPlatformTag(userAgent)))
|
||||
.map(CopyMediaBatchResponse.Entry::fromCopyResult)
|
||||
.collectList()
|
||||
.map(list -> Response.status(207).entity(new CopyMediaBatchResponse(list)).build())
|
||||
.toFuture();
|
||||
.collectList().block();
|
||||
return Response.status(207).entity(new CopyMediaBatchResponse(copyResults)).build();
|
||||
}
|
||||
|
||||
@POST
|
||||
@@ -853,7 +870,8 @@ public class ArchiveController {
|
||||
@ApiResponse(responseCode = "204", description = "The backup was successfully refreshed")
|
||||
@ApiResponse(responseCode = "429", description = "Rate limited.")
|
||||
@ApiResponseZkAuth
|
||||
public CompletionStage<Response> refresh(
|
||||
@ManagedAsync
|
||||
public void refresh(
|
||||
@Auth final Optional<AuthenticatedDevice> account,
|
||||
@HeaderParam(HttpHeaders.USER_AGENT) final String userAgent,
|
||||
|
||||
@@ -863,14 +881,14 @@ public class ArchiveController {
|
||||
|
||||
@Parameter(description = BackupAuthCredentialPresentationSignature.DESCRIPTION, schema = @Schema(implementation = String.class))
|
||||
@NotNull
|
||||
@HeaderParam(X_SIGNAL_ZK_AUTH_SIGNATURE) final BackupAuthCredentialPresentationSignature signature) {
|
||||
@HeaderParam(X_SIGNAL_ZK_AUTH_SIGNATURE) final BackupAuthCredentialPresentationSignature signature)
|
||||
throws BackupFailedZkAuthenticationException, BackupPermissionException {
|
||||
if (account.isPresent()) {
|
||||
throw new BadRequestException("must not use authenticated connection for anonymous operations");
|
||||
}
|
||||
return backupManager
|
||||
.authenticateBackupUser(presentation.presentation, signature.signature, userAgent)
|
||||
.thenCompose(backupManager::ttlRefresh)
|
||||
.thenApply(Util.ASYNC_EMPTY_RESPONSE);
|
||||
final AuthenticatedBackupUser backupUser =
|
||||
backupManager.authenticateBackupUser(presentation.presentation, signature.signature, userAgent);
|
||||
backupManager.ttlRefresh(backupUser);
|
||||
}
|
||||
|
||||
record StoredMediaObject(
|
||||
@@ -920,7 +938,8 @@ public class ArchiveController {
|
||||
@ApiResponse(responseCode = "400", description = "Invalid cursor or limit")
|
||||
@ApiResponse(responseCode = "429", description = "Rate limited.")
|
||||
@ApiResponseZkAuth
|
||||
public CompletionStage<ListResponse> listMedia(
|
||||
@ManagedAsync
|
||||
public ListResponse listMedia(
|
||||
@Auth final Optional<AuthenticatedDevice> account,
|
||||
@HeaderParam(HttpHeaders.USER_AGENT) final String userAgent,
|
||||
|
||||
@@ -936,20 +955,21 @@ public class ArchiveController {
|
||||
@QueryParam("cursor") final Optional<String> cursor,
|
||||
|
||||
@Parameter(description = "The number of entries to return per call")
|
||||
@QueryParam("limit") final Optional<@Min(1) @Max(10_000) Integer> limit) {
|
||||
@QueryParam("limit") final Optional<@Min(1) @Max(10_000) Integer> limit)
|
||||
throws BackupPermissionException, BackupFailedZkAuthenticationException {
|
||||
if (account.isPresent()) {
|
||||
throw new BadRequestException("must not use authenticated connection for anonymous operations");
|
||||
}
|
||||
return backupManager
|
||||
.authenticateBackupUser(presentation.presentation, signature.signature, userAgent)
|
||||
.thenCompose(backupUser -> backupManager.list(backupUser, cursor, limit.orElse(1000))
|
||||
.thenApply(result -> new ListResponse(
|
||||
result.media()
|
||||
.stream().map(entry -> new StoredMediaObject(entry.cdn(), entry.key(), entry.length()))
|
||||
.toList(),
|
||||
backupUser.backupDir(),
|
||||
backupUser.mediaDir(),
|
||||
result.cursor().orElse(null))));
|
||||
final AuthenticatedBackupUser backupUser =
|
||||
backupManager.authenticateBackupUser(presentation.presentation, signature.signature, userAgent);
|
||||
final BackupManager.ListMediaResult listResult =
|
||||
backupManager.list(backupUser, cursor, limit.orElse(1000));
|
||||
return new ListResponse(listResult.media()
|
||||
.stream().map(entry -> new StoredMediaObject(entry.cdn(), entry.key(), entry.length()))
|
||||
.toList(),
|
||||
backupUser.backupDir(),
|
||||
backupUser.mediaDir(),
|
||||
listResult.cursor().orElse(null));
|
||||
}
|
||||
|
||||
public record DeleteMedia(@Size(min = 1, max = 1000) List<@Valid MediaToDelete> mediaToDelete) {
|
||||
@@ -976,7 +996,8 @@ public class ArchiveController {
|
||||
@ApiResponse(responseCode = "204", description = "The provided objects were successfully deleted or they do not exist")
|
||||
@ApiResponse(responseCode = "429", description = "Rate limited.")
|
||||
@ApiResponseZkAuth
|
||||
public CompletionStage<Response> deleteMedia(
|
||||
@ManagedAsync
|
||||
public void deleteMedia(
|
||||
@Auth final Optional<AuthenticatedDevice> account,
|
||||
@HeaderParam(HttpHeaders.USER_AGENT) final String userAgent,
|
||||
|
||||
@@ -988,7 +1009,8 @@ public class ArchiveController {
|
||||
@NotNull
|
||||
@HeaderParam(X_SIGNAL_ZK_AUTH_SIGNATURE) final BackupAuthCredentialPresentationSignature signature,
|
||||
|
||||
@Valid @NotNull DeleteMedia deleteMedia) {
|
||||
@Valid @NotNull DeleteMedia deleteMedia)
|
||||
throws BackupFailedZkAuthenticationException, BackupWrongCredentialTypeException, BackupPermissionException {
|
||||
if (account.isPresent()) {
|
||||
throw new BadRequestException("must not use authenticated connection for anonymous operations");
|
||||
}
|
||||
@@ -997,12 +1019,9 @@ public class ArchiveController {
|
||||
.map(media -> new BackupManager.StorageDescriptor(media.cdn(), media.mediaId))
|
||||
.toList();
|
||||
|
||||
return backupManager
|
||||
.authenticateBackupUser(presentation.presentation, signature.signature, userAgent)
|
||||
.thenCompose(authenticatedBackupUser -> backupManager
|
||||
.deleteMedia(authenticatedBackupUser, toDelete)
|
||||
.then().toFuture())
|
||||
.thenApply(Util.ASYNC_EMPTY_RESPONSE);
|
||||
final AuthenticatedBackupUser backupUser =
|
||||
backupManager.authenticateBackupUser(presentation.presentation, signature.signature, userAgent);
|
||||
backupManager.deleteMedia(backupUser, toDelete).then().block();
|
||||
}
|
||||
|
||||
@DELETE
|
||||
@@ -1013,7 +1032,8 @@ public class ArchiveController {
|
||||
@ApiResponse(responseCode = "204", description = "The backup has been successfully removed")
|
||||
@ApiResponse(responseCode = "429", description = "Rate limited.")
|
||||
@ApiResponseZkAuth
|
||||
public CompletionStage<Response> deleteBackup(
|
||||
@ManagedAsync
|
||||
public void deleteBackup(
|
||||
@Auth final Optional<AuthenticatedDevice> account,
|
||||
@HeaderParam(HttpHeaders.USER_AGENT) final String userAgent,
|
||||
|
||||
@@ -1023,14 +1043,15 @@ public class ArchiveController {
|
||||
|
||||
@Parameter(description = BackupAuthCredentialPresentationSignature.DESCRIPTION, schema = @Schema(implementation = String.class))
|
||||
@NotNull
|
||||
@HeaderParam(X_SIGNAL_ZK_AUTH_SIGNATURE) final BackupAuthCredentialPresentationSignature signature) {
|
||||
@HeaderParam(X_SIGNAL_ZK_AUTH_SIGNATURE) final BackupAuthCredentialPresentationSignature signature)
|
||||
throws BackupPermissionException, BackupFailedZkAuthenticationException {
|
||||
if (account.isPresent()) {
|
||||
throw new BadRequestException("must not use authenticated connection for anonymous operations");
|
||||
}
|
||||
return backupManager
|
||||
.authenticateBackupUser(presentation.presentation, signature.signature, userAgent)
|
||||
.thenCompose(backupManager::deleteEntireBackup)
|
||||
.thenApply(Util.ASYNC_EMPTY_RESPONSE);
|
||||
final AuthenticatedBackupUser backupUser =
|
||||
backupManager.authenticateBackupUser(presentation.presentation, signature.signature, userAgent);
|
||||
|
||||
backupManager.deleteEntireBackup(backupUser);
|
||||
}
|
||||
|
||||
}
|
||||
+1
-2
@@ -252,8 +252,7 @@ public class DeviceCheckController {
|
||||
switch (request.assertionRequest().action()) {
|
||||
case BACKUP -> backupAuthManager.extendBackupVoucher(
|
||||
account,
|
||||
new Account.BackupVoucher(backupRedemptionLevel, clock.instant().plus(backupRedemptionDuration)))
|
||||
.join();
|
||||
new Account.BackupVoucher(backupRedemptionLevel, clock.instant().plus(backupRedemptionDuration)));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+5
-4
@@ -38,18 +38,18 @@ import java.security.MessageDigest;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import java.time.Clock;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import javax.annotation.Nullable;
|
||||
import org.glassfish.jersey.server.ManagedAsync;
|
||||
import org.signal.libsignal.protocol.IdentityKey;
|
||||
import org.signal.libsignal.zkgroup.ServerSecretParams;
|
||||
import org.signal.libsignal.zkgroup.VerificationFailedException;
|
||||
import org.signal.libsignal.zkgroup.groupsend.GroupSendDerivedKeyPair;
|
||||
import org.signal.libsignal.zkgroup.groupsend.GroupSendFullToken;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.auth.Anonymous;
|
||||
import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
|
||||
import org.whispersystems.textsecuregcm.auth.GroupSendTokenHeader;
|
||||
@@ -82,7 +82,6 @@ import reactor.core.publisher.Mono;
|
||||
@io.swagger.v3.oas.annotations.tags.Tag(name = "Keys")
|
||||
public class KeysController {
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(KeysController.class);
|
||||
private final RateLimiters rateLimiters;
|
||||
private final KeysManager keysManager;
|
||||
private final AccountsManager accounts;
|
||||
@@ -319,6 +318,7 @@ public class KeysController {
|
||||
}
|
||||
|
||||
@GET
|
||||
@ManagedAsync
|
||||
@Path("/{identifier}/{device_id}")
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@Operation(summary = "Fetch public keys for another user",
|
||||
@@ -385,7 +385,8 @@ public class KeysController {
|
||||
devicePreKeys.ecPreKey().orElse(null),
|
||||
devicePreKeys.kemSignedPreKey())))
|
||||
.collectList()
|
||||
.block();
|
||||
.blockOptional()
|
||||
.orElseGet(Collections::emptyList);
|
||||
|
||||
final IdentityKey identityKey = target.getIdentityKey(targetIdentifier.identityType());
|
||||
|
||||
|
||||
+4
-27
@@ -4,28 +4,15 @@
|
||||
*/
|
||||
package org.whispersystems.textsecuregcm.controllers;
|
||||
|
||||
import io.grpc.Metadata;
|
||||
import io.grpc.Status;
|
||||
import java.time.Duration;
|
||||
import java.util.Optional;
|
||||
import javax.annotation.Nullable;
|
||||
import io.grpc.StatusRuntimeException;
|
||||
import org.whispersystems.textsecuregcm.grpc.ConvertibleToGrpcStatus;
|
||||
import org.whispersystems.textsecuregcm.grpc.GrpcExceptions;
|
||||
|
||||
public class RateLimitExceededException extends Exception implements ConvertibleToGrpcStatus {
|
||||
|
||||
public static final Metadata.Key<Duration> RETRY_AFTER_DURATION_KEY =
|
||||
Metadata.Key.of("retry-after", new Metadata.AsciiMarshaller<>() {
|
||||
@Override
|
||||
public String toAsciiString(final Duration value) {
|
||||
return value.toString();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Duration parseAsciiString(final String serialized) {
|
||||
return Duration.parse(serialized);
|
||||
}
|
||||
});
|
||||
|
||||
@Nullable
|
||||
private final Duration retryDuration;
|
||||
|
||||
@@ -44,17 +31,7 @@ public class RateLimitExceededException extends Exception implements Convertible
|
||||
}
|
||||
|
||||
@Override
|
||||
public Status grpcStatus() {
|
||||
return Status.RESOURCE_EXHAUSTED;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Optional<Metadata> grpcMetadata() {
|
||||
return getRetryDuration()
|
||||
.map(duration -> {
|
||||
final Metadata metadata = new Metadata();
|
||||
metadata.put(RETRY_AFTER_DURATION_KEY, duration);
|
||||
return metadata;
|
||||
});
|
||||
public StatusRuntimeException toStatusRuntimeException() {
|
||||
return GrpcExceptions.rateLimitExceeded(retryDuration);
|
||||
}
|
||||
}
|
||||
+109
-60
@@ -60,7 +60,7 @@ import java.util.Optional;
|
||||
import java.util.concurrent.CancellationException;
|
||||
import java.util.concurrent.CompletionException;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.apache.commons.lang3.Strings;
|
||||
import org.apache.http.HttpStatus;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
@@ -94,6 +94,9 @@ import org.whispersystems.textsecuregcm.storage.DynamicConfigurationManager;
|
||||
import org.whispersystems.textsecuregcm.storage.PhoneNumberIdentifiers;
|
||||
import org.whispersystems.textsecuregcm.storage.RegistrationRecoveryPasswordsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.VerificationSessionManager;
|
||||
import org.whispersystems.textsecuregcm.telephony.CarrierData;
|
||||
import org.whispersystems.textsecuregcm.telephony.CarrierDataException;
|
||||
import org.whispersystems.textsecuregcm.telephony.CarrierDataProvider;
|
||||
import org.whispersystems.textsecuregcm.util.ExceptionUtils;
|
||||
import org.whispersystems.textsecuregcm.util.ObsoletePhoneNumberFormatException;
|
||||
import org.whispersystems.textsecuregcm.util.Pair;
|
||||
@@ -129,6 +132,7 @@ public class VerificationController {
|
||||
private final PhoneNumberIdentifiers phoneNumberIdentifiers;
|
||||
private final RateLimiters rateLimiters;
|
||||
private final AccountsManager accountsManager;
|
||||
private final CarrierDataProvider carrierDataProvider;
|
||||
private final RegistrationFraudChecker registrationFraudChecker;
|
||||
private final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager;
|
||||
private final Clock clock;
|
||||
@@ -141,6 +145,7 @@ public class VerificationController {
|
||||
final PhoneNumberIdentifiers phoneNumberIdentifiers,
|
||||
final RateLimiters rateLimiters,
|
||||
final AccountsManager accountsManager,
|
||||
final CarrierDataProvider carrierDataProvider,
|
||||
final RegistrationFraudChecker registrationFraudChecker,
|
||||
final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager,
|
||||
final Clock clock) {
|
||||
@@ -152,6 +157,7 @@ public class VerificationController {
|
||||
this.phoneNumberIdentifiers = phoneNumberIdentifiers;
|
||||
this.rateLimiters = rateLimiters;
|
||||
this.accountsManager = accountsManager;
|
||||
this.carrierDataProvider = carrierDataProvider;
|
||||
this.registrationFraudChecker = registrationFraudChecker;
|
||||
this.dynamicConfigurationManager = dynamicConfigurationManager;
|
||||
this.clock = clock;
|
||||
@@ -164,7 +170,7 @@ public class VerificationController {
|
||||
@Operation(
|
||||
summary = "Creates a new verification session for a specific phone number",
|
||||
description = """
|
||||
Initiates a session to be able to verify the phone number for account registration. Check the response and
|
||||
Initiates a session to be able to verify the phone number for account registration. Check the response and
|
||||
submit requested information at PATCH /session/{sessionId}
|
||||
""")
|
||||
@ApiResponse(responseCode = "200", description = "The verification session was created successfully", useReturnTypeSchema = true)
|
||||
@@ -187,14 +193,29 @@ public class VerificationController {
|
||||
throw new ServerErrorException("could not parse already validated number", Response.Status.INTERNAL_SERVER_ERROR);
|
||||
}
|
||||
|
||||
Optional<CarrierData> maybeCarrierData;
|
||||
|
||||
if (dynamicConfigurationManager.getConfiguration().getCarrierDataLookupConfiguration().enabled()) {
|
||||
try {
|
||||
maybeCarrierData = carrierDataProvider.lookupCarrierData(phoneNumber,
|
||||
dynamicConfigurationManager.getConfiguration().getCarrierDataLookupConfiguration().maxCacheAge());
|
||||
} catch (final IOException | CarrierDataException e) {
|
||||
logger.warn("Failed to retrieve carrier data", e);
|
||||
maybeCarrierData = Optional.empty();
|
||||
}
|
||||
} else {
|
||||
maybeCarrierData = Optional.empty();
|
||||
}
|
||||
|
||||
final RegistrationServiceSession registrationServiceSession;
|
||||
try {
|
||||
final String sourceHost = (String) requestContext.getProperty(RemoteAddressFilter.REMOTE_ADDRESS_ATTRIBUTE_NAME);
|
||||
|
||||
registrationServiceSession = registrationServiceClient.createRegistrationSession(phoneNumber, sourceHost,
|
||||
registrationServiceSession = registrationServiceClient.createRegistrationSession(phoneNumber,
|
||||
sourceHost,
|
||||
accountsManager.getByE164(request.number()).isPresent(),
|
||||
request.updateVerificationSessionRequest().mcc(),
|
||||
request.updateVerificationSessionRequest().mnc(),
|
||||
maybeCarrierData.flatMap(CarrierData::mcc).orElse(null),
|
||||
maybeCarrierData.flatMap(CarrierData::mnc).orElse(null),
|
||||
REGISTRATION_RPC_TIMEOUT).join();
|
||||
} catch (final CancellationException e) {
|
||||
|
||||
@@ -208,9 +229,16 @@ public class VerificationController {
|
||||
throw new ServerErrorException(Response.Status.INTERNAL_SERVER_ERROR, e);
|
||||
}
|
||||
|
||||
VerificationSession verificationSession = new VerificationSession(null, new ArrayList<>(),
|
||||
Collections.emptyList(), null, null, false,
|
||||
clock.millis(), clock.millis(), registrationServiceSession.expiration());
|
||||
VerificationSession verificationSession = new VerificationSession(null,
|
||||
maybeCarrierData.orElse(null),
|
||||
new ArrayList<>(),
|
||||
Collections.emptyList(),
|
||||
null,
|
||||
null,
|
||||
false,
|
||||
clock.millis(),
|
||||
clock.millis(),
|
||||
registrationServiceSession.expiration());
|
||||
|
||||
verificationSession = handlePushToken(pushTokenAndType, verificationSession);
|
||||
// unconditionally request a captcha -- it will either be the only requested information, or a fallback
|
||||
@@ -229,9 +257,9 @@ public class VerificationController {
|
||||
@Operation(
|
||||
summary = "Update a registration verification session",
|
||||
description = """
|
||||
Updates the session with requested information like an answer to a push challenge or captcha.
|
||||
If `requestedInformation` in the response is empty, and `allowedToRequestCode` is `true`, proceed to call
|
||||
`POST /session/{sessionId}/code`. If `requestedInformation` is empty and `allowedToRequestCode` is `false`,
|
||||
Updates the session with requested information like an answer to a push challenge or captcha.
|
||||
If `requestedInformation` in the response is empty, and `allowedToRequestCode` is `true`, proceed to call
|
||||
`POST /session/{sessionId}/code`. If `requestedInformation` is empty and `allowedToRequestCode` is `false`,
|
||||
then the caller must create a new verification session.
|
||||
""")
|
||||
@ApiResponse(responseCode = "200", description = "Session was updated successfully with the information provided", useReturnTypeSchema = true)
|
||||
@@ -326,10 +354,16 @@ public class VerificationController {
|
||||
requestedInformation.add(VerificationSession.Information.PUSH_CHALLENGE);
|
||||
requestedInformation.addAll(verificationSession.requestedInformation());
|
||||
|
||||
verificationSession = new VerificationSession(generatePushChallenge(), requestedInformation,
|
||||
verificationSession.submittedInformation(), verificationSession.smsSenderOverride(),
|
||||
verificationSession.voiceSenderOverride(), verificationSession.allowedToRequestCode(),
|
||||
verificationSession.createdTimestamp(), clock.millis(), verificationSession.remoteExpirationSeconds()
|
||||
verificationSession = new VerificationSession(generatePushChallenge(),
|
||||
verificationSession.carrierData(),
|
||||
requestedInformation,
|
||||
verificationSession.submittedInformation(),
|
||||
verificationSession.smsSenderOverride(),
|
||||
verificationSession.voiceSenderOverride(),
|
||||
verificationSession.allowedToRequestCode(),
|
||||
verificationSession.createdTimestamp(),
|
||||
clock.millis(),
|
||||
verificationSession.remoteExpirationSeconds()
|
||||
);
|
||||
}
|
||||
|
||||
@@ -394,9 +428,15 @@ public class VerificationController {
|
||||
|| requestedInformation.remove(VerificationSession.Information.PUSH_CHALLENGE))
|
||||
&& requestedInformation.isEmpty();
|
||||
|
||||
verificationSession = new VerificationSession(verificationSession.pushChallenge(), requestedInformation,
|
||||
submittedInformation, verificationSession.smsSenderOverride(), verificationSession.voiceSenderOverride(),
|
||||
allowedToRequestCode, verificationSession.createdTimestamp(), clock.millis(),
|
||||
verificationSession = new VerificationSession(verificationSession.pushChallenge(),
|
||||
verificationSession.carrierData(),
|
||||
requestedInformation,
|
||||
submittedInformation,
|
||||
verificationSession.smsSenderOverride(),
|
||||
verificationSession.voiceSenderOverride(),
|
||||
allowedToRequestCode,
|
||||
verificationSession.createdTimestamp(),
|
||||
clock.millis(),
|
||||
verificationSession.remoteExpirationSeconds());
|
||||
|
||||
} else if (pushChallengePresent) {
|
||||
@@ -461,9 +501,15 @@ public class VerificationController {
|
||||
|| requestedInformation.remove(VerificationSession.Information.CAPTCHA))
|
||||
&& requestedInformation.isEmpty();
|
||||
|
||||
verificationSession = new VerificationSession(verificationSession.pushChallenge(), requestedInformation,
|
||||
submittedInformation, verificationSession.smsSenderOverride(), verificationSession.voiceSenderOverride(),
|
||||
allowedToRequestCode, verificationSession.createdTimestamp(), clock.millis(),
|
||||
verificationSession = new VerificationSession(verificationSession.pushChallenge(),
|
||||
verificationSession.carrierData(),
|
||||
requestedInformation,
|
||||
submittedInformation,
|
||||
verificationSession.smsSenderOverride(),
|
||||
verificationSession.voiceSenderOverride(),
|
||||
allowedToRequestCode,
|
||||
verificationSession.createdTimestamp(),
|
||||
clock.millis(),
|
||||
verificationSession.remoteExpirationSeconds());
|
||||
} else {
|
||||
throw new ForbiddenException();
|
||||
@@ -511,9 +557,9 @@ public class VerificationController {
|
||||
content = @Content(schema = @Schema(implementation = VerificationSessionResponse.class)))
|
||||
@ApiResponse(responseCode = "422", description = "Request did not pass validation")
|
||||
@ApiResponse(responseCode = "429", description = """
|
||||
Too may attempts; the caller is not permitted to send a verification code via the requested channel at this time
|
||||
and may need to wait before trying again; if the session metadata does not specify a time at which the caller may
|
||||
try again, then the caller has exhausted their permitted attempts and must either try a different transport or
|
||||
Too may attempts; the caller is not permitted to send a verification code via the requested channel at this time
|
||||
and may need to wait before trying again; if the session metadata does not specify a time at which the caller may
|
||||
try again, then the caller has exhausted their permitted attempts and must either try a different transport or
|
||||
create a new verification session.
|
||||
""",
|
||||
content = @Content(schema = @Schema(implementation = VerificationSessionResponse.class)),
|
||||
@@ -523,10 +569,10 @@ public class VerificationController {
|
||||
schema = @Schema(implementation = Integer.class)
|
||||
))
|
||||
@ApiResponse(responseCode = "440", description = """
|
||||
The attempt to send a verification code failed because an external service (e.g. the SMS provider) refused to
|
||||
deliver the code. This may be a temporary or permanent failure, as indicated in the response body. If temporary,
|
||||
clients may try again after a reasonable delay. If permanent, clients should not retry the request and should
|
||||
communicate the permanent failure to the end user. Permanent failures may result in the server disallowing all
|
||||
The attempt to send a verification code failed because an external service (e.g. the SMS provider) refused to
|
||||
deliver the code. This may be a temporary or permanent failure, as indicated in the response body. If temporary,
|
||||
clients may try again after a reasonable delay. If permanent, clients should not retry the request and should
|
||||
communicate the permanent failure to the end user. Permanent failures may result in the server disallowing all
|
||||
future attempts to request or submit verification codes (since those attempts would be all but guaranteed to fail).
|
||||
""",
|
||||
content = @Content(schema = @Schema(implementation = RegistrationServiceSenderExceptionMapper.SendVerificationCodeFailureResponse.class)))
|
||||
@@ -574,7 +620,7 @@ public class VerificationController {
|
||||
case "ios" -> ClientType.IOS;
|
||||
case "android-2021-03" -> ClientType.ANDROID_WITH_FCM;
|
||||
default -> {
|
||||
if (StringUtils.startsWithIgnoreCase(verificationCodeRequest.client(), "android")) {
|
||||
if (Strings.CI.startsWith(verificationCodeRequest.client(), "android")) {
|
||||
yield ClientType.ANDROID_WITHOUT_FCM;
|
||||
}
|
||||
yield ClientType.UNKNOWN;
|
||||
@@ -598,38 +644,41 @@ public class VerificationController {
|
||||
throw new ServerErrorException("registration service unavailable", Response.Status.SERVICE_UNAVAILABLE);
|
||||
} catch (final CompletionException e) {
|
||||
final Throwable unwrappedException = ExceptionUtils.unwrap(e);
|
||||
if (unwrappedException instanceof RateLimitExceededException rateLimitExceededException) {
|
||||
if (rateLimitExceededException instanceof VerificationSessionRateLimitExceededException ve) {
|
||||
final Response response = buildResponseForRateLimitExceeded(verificationSession, ve.getRegistrationSession(),
|
||||
ve.getRetryDuration());
|
||||
throw new ClientErrorException(response);
|
||||
switch (unwrappedException) {
|
||||
case RateLimitExceededException rateLimitExceededException -> {
|
||||
if (rateLimitExceededException instanceof VerificationSessionRateLimitExceededException ve) {
|
||||
final Response response = buildResponseForRateLimitExceeded(verificationSession,
|
||||
ve.getRegistrationSession(),
|
||||
ve.getRetryDuration());
|
||||
throw new ClientErrorException(response);
|
||||
}
|
||||
|
||||
throw new RateLimitExceededException(rateLimitExceededException.getRetryDuration().orElse(null));
|
||||
}
|
||||
case RegistrationServiceException registrationServiceException ->
|
||||
throw registrationServiceException.getRegistrationSession()
|
||||
.map(s -> buildResponse(s, verificationSession))
|
||||
.map(verificationSessionResponse -> {
|
||||
final Response response = registrationServiceException instanceof TransportNotAllowedException
|
||||
? Response.status(418).entity(verificationSessionResponse).build()
|
||||
: Response.status(Response.Status.CONFLICT).entity(verificationSessionResponse).build();
|
||||
|
||||
throw new RateLimitExceededException(rateLimitExceededException.getRetryDuration().orElse(null));
|
||||
} else if (unwrappedException instanceof RegistrationServiceException registrationServiceException) {
|
||||
|
||||
throw registrationServiceException.getRegistrationSession()
|
||||
.map(s -> buildResponse(s, verificationSession))
|
||||
.map(verificationSessionResponse -> {
|
||||
final Response response = registrationServiceException instanceof TransportNotAllowedException
|
||||
? Response.status(418).entity(verificationSessionResponse).build()
|
||||
: Response.status(Response.Status.CONFLICT).entity(verificationSessionResponse).build();
|
||||
|
||||
return new ClientErrorException(response);
|
||||
})
|
||||
.orElseGet(NotFoundException::new);
|
||||
|
||||
} else if (unwrappedException instanceof RegistrationFraudException) {
|
||||
if (dynamicConfigurationManager.getConfiguration().getRegistrationConfiguration().squashDeclinedAttemptErrors()) {
|
||||
return buildResponse(registrationServiceSession, verificationSession);
|
||||
} else {
|
||||
throw unwrappedException.getCause();
|
||||
return new ClientErrorException(response);
|
||||
})
|
||||
.orElseGet(NotFoundException::new);
|
||||
case RegistrationFraudException _ -> {
|
||||
if (dynamicConfigurationManager.getConfiguration().getRegistrationConfiguration()
|
||||
.squashDeclinedAttemptErrors()) {
|
||||
return buildResponse(registrationServiceSession, verificationSession);
|
||||
} else {
|
||||
throw unwrappedException.getCause();
|
||||
}
|
||||
}
|
||||
case RegistrationServiceSenderException _ -> throw unwrappedException;
|
||||
case null, default -> {
|
||||
logger.error("Registration service failure", unwrappedException);
|
||||
throw new ServerErrorException(Response.Status.INTERNAL_SERVER_ERROR);
|
||||
}
|
||||
} else if (unwrappedException instanceof RegistrationServiceSenderException) {
|
||||
throw unwrappedException;
|
||||
} else {
|
||||
logger.error("Registration service failure", unwrappedException);
|
||||
throw new ServerErrorException(Response.Status.INTERNAL_SERVER_ERROR);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -661,8 +710,8 @@ public class VerificationController {
|
||||
@ApiResponse(responseCode = "409", description = "The session is already verified or no code has been requested yet for this session",
|
||||
content = @Content(schema = @Schema(implementation = VerificationSessionResponse.class)))
|
||||
@ApiResponse(responseCode = "429", description = """
|
||||
Too many attempts; the caller is not permitted to submit a verification code at this time and may need to wait
|
||||
before trying again; if the session metadata does not specify a time at which the caller may try again, then the
|
||||
Too many attempts; the caller is not permitted to submit a verification code at this time and may need to wait
|
||||
before trying again; if the session metadata does not specify a time at which the caller may try again, then the
|
||||
caller has exhausted their permitted attempts and must create a new verification session.
|
||||
""",
|
||||
content = @Content(schema = @Schema(implementation = VerificationSessionResponse.class)),
|
||||
|
||||
+3
-3
@@ -27,8 +27,9 @@ import java.util.Set;
|
||||
import javax.annotation.Nullable;
|
||||
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicRemoteDeprecationConfiguration;
|
||||
import org.whispersystems.textsecuregcm.grpc.GrpcExceptions;
|
||||
import org.whispersystems.textsecuregcm.grpc.RequestAttributesUtil;
|
||||
import org.whispersystems.textsecuregcm.grpc.StatusConstants;
|
||||
import org.whispersystems.textsecuregcm.grpc.ServerInterceptorUtil;
|
||||
import org.whispersystems.textsecuregcm.storage.DynamicConfigurationManager;
|
||||
import org.whispersystems.textsecuregcm.util.ua.ClientPlatform;
|
||||
import org.whispersystems.textsecuregcm.util.ua.UnrecognizedUserAgentException;
|
||||
@@ -91,8 +92,7 @@ public class RemoteDeprecationFilter implements Filter, ServerInterceptor {
|
||||
}).orElse(null);
|
||||
|
||||
if (shouldBlock(userAgent)) {
|
||||
call.close(StatusConstants.UPGRADE_NEEDED_STATUS, new Metadata());
|
||||
return new ServerCall.Listener<>() {};
|
||||
return ServerInterceptorUtil.closeWithStatusException(call, GrpcExceptions.upgradeRequired());
|
||||
} else {
|
||||
return next.startCall(call, headers);
|
||||
}
|
||||
|
||||
+14
-17
@@ -6,7 +6,6 @@
|
||||
package org.whispersystems.textsecuregcm.grpc;
|
||||
|
||||
import com.google.protobuf.ByteString;
|
||||
import io.grpc.Status;
|
||||
import org.signal.chat.account.CheckAccountExistenceRequest;
|
||||
import org.signal.chat.account.CheckAccountExistenceResponse;
|
||||
import org.signal.chat.account.LookupUsernameHashRequest;
|
||||
@@ -14,6 +13,7 @@ import org.signal.chat.account.LookupUsernameHashResponse;
|
||||
import org.signal.chat.account.LookupUsernameLinkRequest;
|
||||
import org.signal.chat.account.LookupUsernameLinkResponse;
|
||||
import org.signal.chat.account.ReactorAccountsAnonymousGrpc;
|
||||
import org.signal.chat.errors.NotFound;
|
||||
import org.whispersystems.textsecuregcm.controllers.AccountController;
|
||||
import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.identity.ServiceIdentifier;
|
||||
@@ -51,18 +51,18 @@ public class AccountsAnonymousGrpcService extends ReactorAccountsAnonymousGrpc.A
|
||||
@Override
|
||||
public Mono<LookupUsernameHashResponse> lookupUsernameHash(final LookupUsernameHashRequest request) {
|
||||
if (request.getUsernameHash().size() != AccountController.USERNAME_HASH_LENGTH) {
|
||||
throw Status.INVALID_ARGUMENT
|
||||
.withDescription(String.format("Illegal username hash length; expected %d bytes, but got %d bytes",
|
||||
AccountController.USERNAME_HASH_LENGTH, request.getUsernameHash().size()))
|
||||
.asRuntimeException();
|
||||
throw GrpcExceptions.fieldViolation("username_hash",
|
||||
String.format("Illegal username hash length; expected %d bytes, but got %d bytes",
|
||||
AccountController.USERNAME_HASH_LENGTH, request.getUsernameHash().size()));
|
||||
}
|
||||
|
||||
return RateLimitUtil.rateLimitByRemoteAddress(rateLimiters.getUsernameLookupLimiter())
|
||||
.then(Mono.fromFuture(() -> accountsManager.getByUsernameHash(request.getUsernameHash().toByteArray())))
|
||||
.map(maybeAccount -> maybeAccount.orElseThrow(Status.NOT_FOUND::asRuntimeException))
|
||||
.map(account -> LookupUsernameHashResponse.newBuilder()
|
||||
.setServiceIdentifier(ServiceIdentifierUtil.toGrpcServiceIdentifier(new AciServiceIdentifier(account.getUuid())))
|
||||
.build());
|
||||
.map(maybeAccount -> maybeAccount
|
||||
.map(account -> LookupUsernameHashResponse.newBuilder()
|
||||
.setServiceIdentifier(ServiceIdentifierUtil.toGrpcServiceIdentifier(new AciServiceIdentifier(account.getUuid())))
|
||||
.build())
|
||||
.orElseGet(() -> LookupUsernameHashResponse.newBuilder().setNotFound(NotFound.getDefaultInstance()).build()));
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -72,19 +72,16 @@ public class AccountsAnonymousGrpcService extends ReactorAccountsAnonymousGrpc.A
|
||||
try {
|
||||
linkHandle = UUIDUtil.fromByteString(request.getUsernameLinkHandle());
|
||||
} catch (final IllegalArgumentException e) {
|
||||
throw Status.INVALID_ARGUMENT
|
||||
.withDescription("Could not interpret link handle as UUID")
|
||||
.withCause(e)
|
||||
.asRuntimeException();
|
||||
throw GrpcExceptions.fieldViolation("username_link_handle", "Could not interpret link handle as UUID");
|
||||
}
|
||||
|
||||
return RateLimitUtil.rateLimitByRemoteAddress(rateLimiters.getUsernameLinkLookupLimiter())
|
||||
.then(Mono.fromFuture(() -> accountsManager.getByUsernameLinkHandle(linkHandle)))
|
||||
.map(maybeAccount -> maybeAccount
|
||||
.flatMap(Account::getEncryptedUsername)
|
||||
.orElseThrow(Status.NOT_FOUND::asRuntimeException))
|
||||
.map(usernameCiphertext -> LookupUsernameLinkResponse.newBuilder()
|
||||
.setUsernameCiphertext(ByteString.copyFrom(usernameCiphertext))
|
||||
.build());
|
||||
.map(usernameCiphertext -> LookupUsernameLinkResponse.newBuilder()
|
||||
.setUsernameCiphertext(ByteString.copyFrom(usernameCiphertext))
|
||||
.build())
|
||||
.orElseGet(() -> LookupUsernameLinkResponse.newBuilder().setNotFound(NotFound.getDefaultInstance()).build()));
|
||||
}
|
||||
}
|
||||
+66
-98
@@ -6,7 +6,6 @@
|
||||
package org.whispersystems.textsecuregcm.grpc;
|
||||
|
||||
import com.google.protobuf.ByteString;
|
||||
import io.grpc.Status;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HexFormat;
|
||||
import java.util.List;
|
||||
@@ -26,8 +25,6 @@ import org.signal.chat.account.DeleteUsernameLinkResponse;
|
||||
import org.signal.chat.account.GetAccountIdentityRequest;
|
||||
import org.signal.chat.account.GetAccountIdentityResponse;
|
||||
import org.signal.chat.account.ReactorAccountsGrpc;
|
||||
import org.signal.chat.account.ReserveUsernameHashError;
|
||||
import org.signal.chat.account.ReserveUsernameHashErrorType;
|
||||
import org.signal.chat.account.ReserveUsernameHashRequest;
|
||||
import org.signal.chat.account.ReserveUsernameHashResponse;
|
||||
import org.signal.chat.account.SetDiscoverableByPhoneNumberRequest;
|
||||
@@ -38,7 +35,9 @@ import org.signal.chat.account.SetRegistrationRecoveryPasswordRequest;
|
||||
import org.signal.chat.account.SetRegistrationRecoveryPasswordResponse;
|
||||
import org.signal.chat.account.SetUsernameLinkRequest;
|
||||
import org.signal.chat.account.SetUsernameLinkResponse;
|
||||
import org.signal.chat.account.UsernameNotAvailable;
|
||||
import org.signal.chat.common.AccountIdentifiers;
|
||||
import org.signal.chat.errors.FailedPrecondition;
|
||||
import org.signal.libsignal.usernames.BaseUsernameException;
|
||||
import org.whispersystems.textsecuregcm.auth.SaltedTokenHash;
|
||||
import org.whispersystems.textsecuregcm.auth.UnidentifiedAccessUtil;
|
||||
@@ -50,6 +49,7 @@ import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.identity.IdentityType;
|
||||
import org.whispersystems.textsecuregcm.identity.PniServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimiters;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.RegistrationRecoveryPasswordsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.UsernameHashNotAvailableException;
|
||||
@@ -78,10 +78,7 @@ public class AccountsGrpcService extends ReactorAccountsGrpc.AccountsImplBase {
|
||||
|
||||
@Override
|
||||
public Mono<GetAccountIdentityResponse> getAccountIdentity(final GetAccountIdentityRequest request) {
|
||||
final AuthenticatedDevice authenticatedDevice = AuthenticationUtil.requireAuthenticatedDevice();
|
||||
|
||||
return Mono.fromFuture(() -> accountsManager.getByAccountIdentifierAsync(authenticatedDevice.accountIdentifier()))
|
||||
.map(maybeAccount -> maybeAccount.orElseThrow(Status.UNAUTHENTICATED::asRuntimeException))
|
||||
return getAccount()
|
||||
.map(account -> {
|
||||
final AccountIdentifiers.Builder accountIdentifiersBuilder = AccountIdentifiers.newBuilder()
|
||||
.addServiceIdentifiers(ServiceIdentifierUtil.toGrpcServiceIdentifier(new AciServiceIdentifier(account.getUuid())))
|
||||
@@ -99,10 +96,7 @@ public class AccountsGrpcService extends ReactorAccountsGrpc.AccountsImplBase {
|
||||
|
||||
@Override
|
||||
public Mono<DeleteAccountResponse> deleteAccount(final DeleteAccountRequest request) {
|
||||
final AuthenticatedDevice authenticatedDevice = AuthenticationUtil.requireAuthenticatedPrimaryDevice();
|
||||
|
||||
return Mono.fromFuture(() -> accountsManager.getByAccountIdentifierAsync(authenticatedDevice.accountIdentifier()))
|
||||
.map(maybeAccount -> maybeAccount.orElseThrow(Status.UNAUTHENTICATED::asRuntimeException))
|
||||
return getAccount(AuthenticationUtil.requireAuthenticatedPrimaryDevice())
|
||||
.flatMap(account -> Mono.fromFuture(() -> accountsManager.delete(account, AccountsManager.DeletionReason.USER_REQUEST)))
|
||||
.thenReturn(DeleteAccountResponse.newBuilder().build());
|
||||
}
|
||||
@@ -112,11 +106,10 @@ public class AccountsGrpcService extends ReactorAccountsGrpc.AccountsImplBase {
|
||||
final AuthenticatedDevice authenticatedDevice = AuthenticationUtil.requireAuthenticatedPrimaryDevice();
|
||||
|
||||
if (request.getRegistrationLock().isEmpty()) {
|
||||
throw Status.INVALID_ARGUMENT.withDescription("Registration lock secret must not be empty").asRuntimeException();
|
||||
throw GrpcExceptions.fieldViolation("registration_lock", "Registration lock secret must not be empty");
|
||||
}
|
||||
|
||||
return Mono.fromFuture(() -> accountsManager.getByAccountIdentifierAsync(authenticatedDevice.accountIdentifier()))
|
||||
.map(maybeAccount -> maybeAccount.orElseThrow(Status.UNAUTHENTICATED::asRuntimeException))
|
||||
return getAccount(authenticatedDevice)
|
||||
.flatMap(account -> {
|
||||
// In the previous REST-based API, clients would send hex strings directly. For backward compatibility, we
|
||||
// convert the registration lock secret to a lowercase hex string before turning it into a salted hash.
|
||||
@@ -131,10 +124,7 @@ public class AccountsGrpcService extends ReactorAccountsGrpc.AccountsImplBase {
|
||||
|
||||
@Override
|
||||
public Mono<ClearRegistrationLockResponse> clearRegistrationLock(final ClearRegistrationLockRequest request) {
|
||||
final AuthenticatedDevice authenticatedDevice = AuthenticationUtil.requireAuthenticatedPrimaryDevice();
|
||||
|
||||
return Mono.fromFuture(() -> accountsManager.getByAccountIdentifierAsync(authenticatedDevice.accountIdentifier()))
|
||||
.map(maybeAccount -> maybeAccount.orElseThrow(Status.UNAUTHENTICATED::asRuntimeException))
|
||||
return getAccount(AuthenticationUtil.requireAuthenticatedPrimaryDevice())
|
||||
.flatMap(account -> Mono.fromFuture(() -> accountsManager.updateAsync(account,
|
||||
a -> a.setRegistrationLock(null, null))))
|
||||
.map(ignored -> ClearRegistrationLockResponse.newBuilder().build());
|
||||
@@ -145,42 +135,34 @@ public class AccountsGrpcService extends ReactorAccountsGrpc.AccountsImplBase {
|
||||
final AuthenticatedDevice authenticatedDevice = AuthenticationUtil.requireAuthenticatedDevice();
|
||||
|
||||
if (request.getUsernameHashesCount() == 0) {
|
||||
throw Status.INVALID_ARGUMENT
|
||||
.withDescription("List of username hashes must not be empty")
|
||||
.asRuntimeException();
|
||||
throw GrpcExceptions.fieldViolation("username_hashes", "List of username hashes must not be empty");
|
||||
}
|
||||
|
||||
if (request.getUsernameHashesCount() > AccountController.MAXIMUM_USERNAME_HASHES_LIST_LENGTH) {
|
||||
throw Status.INVALID_ARGUMENT
|
||||
.withDescription(String.format("List of username hashes may have at most %d elements, but actually had %d",
|
||||
AccountController.MAXIMUM_USERNAME_HASHES_LIST_LENGTH, request.getUsernameHashesCount()))
|
||||
.asRuntimeException();
|
||||
throw GrpcExceptions.fieldViolation("username_hashes",
|
||||
String.format("List of username hashes may have at most %d elements, but actually had %d",
|
||||
AccountController.MAXIMUM_USERNAME_HASHES_LIST_LENGTH, request.getUsernameHashesCount()));
|
||||
}
|
||||
|
||||
final List<byte[]> usernameHashes = new ArrayList<>(request.getUsernameHashesCount());
|
||||
|
||||
for (final ByteString usernameHash : request.getUsernameHashesList()) {
|
||||
if (usernameHash.size() != AccountController.USERNAME_HASH_LENGTH) {
|
||||
throw Status.INVALID_ARGUMENT
|
||||
.withDescription(String.format("Username hash length must be %d bytes, but was actually %d",
|
||||
AccountController.USERNAME_HASH_LENGTH, usernameHash.size()))
|
||||
.asRuntimeException();
|
||||
throw GrpcExceptions.fieldViolation("username_hashes",
|
||||
String.format("Username hash length must be %d bytes, but was actually %d",
|
||||
AccountController.USERNAME_HASH_LENGTH, usernameHash.size()));
|
||||
}
|
||||
|
||||
usernameHashes.add(usernameHash.toByteArray());
|
||||
}
|
||||
|
||||
return rateLimiters.getUsernameReserveLimiter().validateReactive(authenticatedDevice.accountIdentifier())
|
||||
.then(Mono.fromFuture(() -> accountsManager.getByAccountIdentifierAsync(authenticatedDevice.accountIdentifier())))
|
||||
.map(maybeAccount -> maybeAccount.orElseThrow(Status.UNAUTHENTICATED::asRuntimeException))
|
||||
.then(getAccount())
|
||||
.flatMap(account -> Mono.fromFuture(() -> accountsManager.reserveUsernameHash(account, usernameHashes)))
|
||||
.map(reservation -> ReserveUsernameHashResponse.newBuilder()
|
||||
.setUsernameHash(ByteString.copyFrom(reservation.reservedUsernameHash()))
|
||||
.build())
|
||||
.onErrorReturn(UsernameHashNotAvailableException.class, ReserveUsernameHashResponse.newBuilder()
|
||||
.setError(ReserveUsernameHashError.newBuilder()
|
||||
.setErrorType(ReserveUsernameHashErrorType.RESERVE_USERNAME_HASH_ERROR_TYPE_NO_HASHES_AVAILABLE)
|
||||
.build())
|
||||
.setUsernameNotAvailable(UsernameNotAvailable.getDefaultInstance())
|
||||
.build());
|
||||
}
|
||||
|
||||
@@ -189,61 +171,57 @@ public class AccountsGrpcService extends ReactorAccountsGrpc.AccountsImplBase {
|
||||
final AuthenticatedDevice authenticatedDevice = AuthenticationUtil.requireAuthenticatedDevice();
|
||||
|
||||
if (request.getUsernameHash().isEmpty()) {
|
||||
throw Status.INVALID_ARGUMENT
|
||||
.withDescription("Username hash must not be empty")
|
||||
.asRuntimeException();
|
||||
throw GrpcExceptions.fieldViolation("username_hash", "Username hash must not be empty");
|
||||
}
|
||||
|
||||
if (request.getUsernameHash().size() != AccountController.USERNAME_HASH_LENGTH) {
|
||||
throw Status.INVALID_ARGUMENT
|
||||
.withDescription(String.format("Username hash length must be %d bytes, but was actually %d",
|
||||
AccountController.USERNAME_HASH_LENGTH, request.getUsernameHash().size()))
|
||||
.asRuntimeException();
|
||||
throw GrpcExceptions.fieldViolation("username_hash",
|
||||
String.format("Username hash length must be %d bytes, but was actually %d",
|
||||
AccountController.USERNAME_HASH_LENGTH, request.getUsernameHash().size()));
|
||||
}
|
||||
|
||||
if (request.getZkProof().isEmpty()) {
|
||||
throw Status.INVALID_ARGUMENT
|
||||
.withDescription("Zero-knowledge proof must not be empty")
|
||||
.asRuntimeException();
|
||||
throw GrpcExceptions.fieldViolation("zk_proof", "Zero-knowledge proof must not be empty");
|
||||
}
|
||||
|
||||
if (request.getUsernameCiphertext().isEmpty()) {
|
||||
throw Status.INVALID_ARGUMENT
|
||||
.withDescription("Username ciphertext must not be empty")
|
||||
.asRuntimeException();
|
||||
throw GrpcExceptions.fieldViolation("username_ciphertext", "Username ciphertext must not be empty");
|
||||
}
|
||||
|
||||
if (request.getUsernameCiphertext().size() > AccountController.MAXIMUM_USERNAME_CIPHERTEXT_LENGTH) {
|
||||
throw Status.INVALID_ARGUMENT
|
||||
.withDescription(String.format("Username hash length must at most %d bytes, but was actually %d",
|
||||
AccountController.MAXIMUM_USERNAME_CIPHERTEXT_LENGTH, request.getUsernameCiphertext().size()))
|
||||
.asRuntimeException();
|
||||
throw GrpcExceptions.fieldViolation("username_ciphertext",
|
||||
String.format("Username ciphertext length must at most %d bytes, but was actually %d",
|
||||
AccountController.MAXIMUM_USERNAME_CIPHERTEXT_LENGTH, request.getUsernameCiphertext().size()));
|
||||
}
|
||||
|
||||
try {
|
||||
usernameHashZkProofVerifier.verifyProof(request.getZkProof().toByteArray(), request.getUsernameHash().toByteArray());
|
||||
} catch (final BaseUsernameException e) {
|
||||
throw Status.INVALID_ARGUMENT.withDescription("Could not verify proof").asRuntimeException();
|
||||
throw GrpcExceptions.constraintViolation("Could not verify proof");
|
||||
}
|
||||
|
||||
return rateLimiters.getUsernameSetLimiter().validateReactive(authenticatedDevice.accountIdentifier())
|
||||
.then(Mono.fromFuture(() -> accountsManager.getByAccountIdentifierAsync(authenticatedDevice.accountIdentifier())))
|
||||
.map(maybeAccount -> maybeAccount.orElseThrow(Status.UNAUTHENTICATED::asRuntimeException))
|
||||
.then(getAccount())
|
||||
.flatMap(account -> Mono.fromFuture(() -> accountsManager.confirmReservedUsernameHash(account, request.getUsernameHash().toByteArray(), request.getUsernameCiphertext().toByteArray())))
|
||||
.map(updatedAccount -> ConfirmUsernameHashResponse.newBuilder()
|
||||
.setUsernameHash(ByteString.copyFrom(updatedAccount.getUsernameHash().orElseThrow()))
|
||||
.setUsernameLinkHandle(UUIDUtil.toByteString(updatedAccount.getUsernameLinkHandle()))
|
||||
.setConfirmedUsernameHash(ConfirmUsernameHashResponse.ConfirmedUsernameHash.newBuilder()
|
||||
.setUsernameHash(ByteString.copyFrom(updatedAccount.getUsernameHash().orElseThrow()))
|
||||
.setUsernameLinkHandle(UUIDUtil.toByteString(updatedAccount.getUsernameLinkHandle()))
|
||||
.build())
|
||||
.build())
|
||||
.onErrorMap(UsernameReservationNotFoundException.class, throwable -> Status.FAILED_PRECONDITION.asRuntimeException())
|
||||
.onErrorMap(UsernameHashNotAvailableException.class, throwable -> Status.NOT_FOUND.asRuntimeException());
|
||||
.onErrorResume(UsernameReservationNotFoundException.class, _ -> Mono.just(ConfirmUsernameHashResponse
|
||||
.newBuilder()
|
||||
.setReservationNotFound(FailedPrecondition.getDefaultInstance())
|
||||
.build()))
|
||||
.onErrorResume(UsernameHashNotAvailableException.class, _ -> Mono.just(ConfirmUsernameHashResponse
|
||||
.newBuilder()
|
||||
.setUsernameNotAvailable(UsernameNotAvailable.getDefaultInstance())
|
||||
.build()));
|
||||
}
|
||||
|
||||
@Override
|
||||
public Mono<DeleteUsernameHashResponse> deleteUsernameHash(final DeleteUsernameHashRequest request) {
|
||||
final AuthenticatedDevice authenticatedDevice = AuthenticationUtil.requireAuthenticatedDevice();
|
||||
|
||||
return Mono.fromFuture(() -> accountsManager.getByAccountIdentifierAsync(authenticatedDevice.accountIdentifier()))
|
||||
.map(maybeAccount -> maybeAccount.orElseThrow(Status.UNAUTHENTICATED::asRuntimeException))
|
||||
return getAccount()
|
||||
.flatMap(account -> Mono.fromFuture(() -> accountsManager.clearUsernameHash(account)))
|
||||
.thenReturn(DeleteUsernameHashResponse.newBuilder().build());
|
||||
}
|
||||
@@ -253,19 +231,16 @@ public class AccountsGrpcService extends ReactorAccountsGrpc.AccountsImplBase {
|
||||
final AuthenticatedDevice authenticatedDevice = AuthenticationUtil.requireAuthenticatedDevice();
|
||||
|
||||
if (request.getUsernameCiphertext().isEmpty() || request.getUsernameCiphertext().size() > EncryptedUsername.MAX_SIZE) {
|
||||
throw Status.INVALID_ARGUMENT
|
||||
.withDescription(String.format("Username ciphertext must not be empty and must be shorter than %d bytes", EncryptedUsername.MAX_SIZE))
|
||||
.asRuntimeException();
|
||||
throw GrpcExceptions.fieldViolation("username_ciphertext",
|
||||
String.format("Username ciphertext must not be empty and must be shorter than %d bytes", EncryptedUsername.MAX_SIZE));
|
||||
}
|
||||
|
||||
return rateLimiters.getUsernameLinkOperationLimiter().validateReactive(authenticatedDevice.accountIdentifier())
|
||||
.then(Mono.fromFuture(() -> accountsManager.getByAccountIdentifierAsync(authenticatedDevice.accountIdentifier())))
|
||||
.map(maybeAccount -> maybeAccount.orElseThrow(Status.UNAUTHENTICATED::asRuntimeException))
|
||||
.then(getAccount())
|
||||
.flatMap(account -> {
|
||||
final SetUsernameLinkResponse.Builder responseBuilder = SetUsernameLinkResponse.newBuilder();
|
||||
if (account.getUsernameHash().isEmpty()) {
|
||||
return Mono.error(Status.FAILED_PRECONDITION
|
||||
.withDescription("Account does not have a username hash")
|
||||
.asRuntimeException());
|
||||
return Mono.just(responseBuilder.setNoUsernameSet(FailedPrecondition.getDefaultInstance()).build());
|
||||
}
|
||||
|
||||
final UUID linkHandle;
|
||||
@@ -276,37 +251,28 @@ public class AccountsGrpcService extends ReactorAccountsGrpc.AccountsImplBase {
|
||||
}
|
||||
|
||||
return Mono.fromFuture(() -> accountsManager.updateAsync(account, a -> a.setUsernameLinkDetails(linkHandle, request.getUsernameCiphertext().toByteArray())))
|
||||
.thenReturn(linkHandle);
|
||||
})
|
||||
.map(linkHandle -> SetUsernameLinkResponse.newBuilder()
|
||||
.setUsernameLinkHandle(UUIDUtil.toByteString(linkHandle))
|
||||
.build());
|
||||
.thenReturn(responseBuilder.setUsernameLinkHandle(UUIDUtil.toByteString(linkHandle)).build());
|
||||
});
|
||||
}
|
||||
|
||||
@Override
|
||||
public Mono<DeleteUsernameLinkResponse> deleteUsernameLink(final DeleteUsernameLinkRequest request) {
|
||||
final AuthenticatedDevice authenticatedDevice = AuthenticationUtil.requireAuthenticatedDevice();
|
||||
|
||||
return rateLimiters.getUsernameLinkOperationLimiter().validateReactive(authenticatedDevice.accountIdentifier())
|
||||
.then(Mono.fromFuture(() -> accountsManager.getByAccountIdentifierAsync(authenticatedDevice.accountIdentifier())))
|
||||
.map(maybeAccount -> maybeAccount.orElseThrow(Status.UNAUTHENTICATED::asRuntimeException))
|
||||
.then(getAccount())
|
||||
.flatMap(account -> Mono.fromFuture(() -> accountsManager.updateAsync(account, a -> a.setUsernameLinkDetails(null, null))))
|
||||
.thenReturn(DeleteUsernameLinkResponse.newBuilder().build());
|
||||
}
|
||||
|
||||
@Override
|
||||
public Mono<ConfigureUnidentifiedAccessResponse> configureUnidentifiedAccess(final ConfigureUnidentifiedAccessRequest request) {
|
||||
final AuthenticatedDevice authenticatedDevice = AuthenticationUtil.requireAuthenticatedDevice();
|
||||
|
||||
if (!request.getAllowUnrestrictedUnidentifiedAccess() && request.getUnidentifiedAccessKey().size() != UnidentifiedAccessUtil.UNIDENTIFIED_ACCESS_KEY_LENGTH) {
|
||||
throw Status.INVALID_ARGUMENT
|
||||
.withDescription(String.format("Unidentified access key must be %d bytes, but was actually %d",
|
||||
UnidentifiedAccessUtil.UNIDENTIFIED_ACCESS_KEY_LENGTH, request.getUnidentifiedAccessKey().size()))
|
||||
.asRuntimeException();
|
||||
throw GrpcExceptions.fieldViolation("unidentified_access_key",
|
||||
String.format("Unidentified access key must be %d bytes, but was actually %d",
|
||||
UnidentifiedAccessUtil.UNIDENTIFIED_ACCESS_KEY_LENGTH, request.getUnidentifiedAccessKey().size()));
|
||||
}
|
||||
|
||||
return Mono.fromFuture(() -> accountsManager.getByAccountIdentifierAsync(authenticatedDevice.accountIdentifier()))
|
||||
.map(maybeAccount -> maybeAccount.orElseThrow(Status.UNAUTHENTICATED::asRuntimeException))
|
||||
return getAccount()
|
||||
.flatMap(account -> Mono.fromFuture(() -> accountsManager.updateAsync(account, a -> {
|
||||
a.setUnrestrictedUnidentifiedAccess(request.getAllowUnrestrictedUnidentifiedAccess());
|
||||
a.setUnidentifiedAccessKey(request.getAllowUnrestrictedUnidentifiedAccess() ? null : request.getUnidentifiedAccessKey().toByteArray());
|
||||
@@ -316,10 +282,7 @@ public class AccountsGrpcService extends ReactorAccountsGrpc.AccountsImplBase {
|
||||
|
||||
@Override
|
||||
public Mono<SetDiscoverableByPhoneNumberResponse> setDiscoverableByPhoneNumber(final SetDiscoverableByPhoneNumberRequest request) {
|
||||
final AuthenticatedDevice authenticatedDevice = AuthenticationUtil.requireAuthenticatedDevice();
|
||||
|
||||
return Mono.fromFuture(() -> accountsManager.getByAccountIdentifierAsync(authenticatedDevice.accountIdentifier()))
|
||||
.map(maybeAccount -> maybeAccount.orElseThrow(Status.UNAUTHENTICATED::asRuntimeException))
|
||||
return getAccount()
|
||||
.flatMap(account -> Mono.fromFuture(() -> accountsManager.updateAsync(account,
|
||||
a -> a.setDiscoverableByPhoneNumber(request.getDiscoverableByPhoneNumber()))))
|
||||
.thenReturn(SetDiscoverableByPhoneNumberResponse.newBuilder().build());
|
||||
@@ -327,17 +290,22 @@ public class AccountsGrpcService extends ReactorAccountsGrpc.AccountsImplBase {
|
||||
|
||||
@Override
|
||||
public Mono<SetRegistrationRecoveryPasswordResponse> setRegistrationRecoveryPassword(final SetRegistrationRecoveryPasswordRequest request) {
|
||||
final AuthenticatedDevice authenticatedDevice = AuthenticationUtil.requireAuthenticatedDevice();
|
||||
|
||||
if (request.getRegistrationRecoveryPassword().isEmpty()) {
|
||||
throw Status.INVALID_ARGUMENT
|
||||
.withDescription("Registration recovery password must not be empty")
|
||||
.asRuntimeException();
|
||||
throw GrpcExceptions.fieldViolation("registration_recovery_password", "Registration recovery password must not be empty");
|
||||
}
|
||||
|
||||
return Mono.fromFuture(() -> accountsManager.getByAccountIdentifierAsync(authenticatedDevice.accountIdentifier()))
|
||||
.map(maybeAccount -> maybeAccount.orElseThrow(Status.UNAUTHENTICATED::asRuntimeException))
|
||||
return getAccount()
|
||||
.flatMap(account -> Mono.fromFuture(() -> registrationRecoveryPasswordsManager.store(account.getIdentifier(IdentityType.PNI), request.getRegistrationRecoveryPassword().toByteArray())))
|
||||
.thenReturn(SetRegistrationRecoveryPasswordResponse.newBuilder().build());
|
||||
}
|
||||
|
||||
private Mono<Account> getAccount() {
|
||||
return getAccount(AuthenticationUtil.requireAuthenticatedDevice());
|
||||
}
|
||||
|
||||
private Mono<Account> getAccount(AuthenticatedDevice authenticatedDevice) {
|
||||
return Mono.fromFuture(() -> accountsManager.getByAccountIdentifierAsync(authenticatedDevice.accountIdentifier()))
|
||||
.map(maybeAccount -> maybeAccount
|
||||
.orElseThrow(() -> GrpcExceptions.invalidCredentials("invalid credentials")));
|
||||
}
|
||||
}
|
||||
+200
-117
@@ -5,16 +5,13 @@
|
||||
package org.whispersystems.textsecuregcm.grpc;
|
||||
|
||||
import com.google.protobuf.ByteString;
|
||||
import io.grpc.Status;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import io.micrometer.core.instrument.Tag;
|
||||
import io.micrometer.core.instrument.Tags;
|
||||
import java.util.concurrent.Flow;
|
||||
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.DeleteMediaItem;
|
||||
import org.signal.chat.backup.DeleteMediaRequest;
|
||||
import org.signal.chat.backup.DeleteMediaResponse;
|
||||
import org.signal.chat.backup.GetBackupInfoRequest;
|
||||
@@ -27,29 +24,37 @@ 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.chat.backup.SimpleBackupsAnonymousGrpc;
|
||||
import org.signal.chat.errors.FailedPrecondition;
|
||||
import org.signal.chat.errors.FailedZkAuthentication;
|
||||
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.auth.ExternalServiceCredentials;
|
||||
import org.whispersystems.textsecuregcm.backup.BackupFailedZkAuthenticationException;
|
||||
import org.whispersystems.textsecuregcm.backup.BackupInvalidArgumentException;
|
||||
import org.whispersystems.textsecuregcm.backup.BackupManager;
|
||||
import org.whispersystems.textsecuregcm.backup.BackupNotFoundException;
|
||||
import org.whispersystems.textsecuregcm.backup.BackupPermissionException;
|
||||
import org.whispersystems.textsecuregcm.backup.BackupUploadDescriptor;
|
||||
import org.whispersystems.textsecuregcm.backup.BackupWrongCredentialTypeException;
|
||||
import org.whispersystems.textsecuregcm.backup.CopyParameters;
|
||||
import org.whispersystems.textsecuregcm.backup.MediaEncryptionParameters;
|
||||
import org.whispersystems.textsecuregcm.controllers.ArchiveController;
|
||||
import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
|
||||
import org.whispersystems.textsecuregcm.metrics.BackupMetrics;
|
||||
import org.whispersystems.textsecuregcm.metrics.UserAgentTagUtil;
|
||||
import reactor.adapter.JdkFlowAdapter;
|
||||
import reactor.core.publisher.Flux;
|
||||
import reactor.core.publisher.Mono;
|
||||
|
||||
import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
|
||||
|
||||
public class BackupsAnonymousGrpcService extends ReactorBackupsAnonymousGrpc.BackupsAnonymousImplBase {
|
||||
public class BackupsAnonymousGrpcService extends SimpleBackupsAnonymousGrpc.BackupsAnonymousImplBase {
|
||||
|
||||
private final BackupManager backupManager;
|
||||
private final BackupMetrics backupMetrics;
|
||||
@@ -60,94 +65,148 @@ public class BackupsAnonymousGrpcService extends ReactorBackupsAnonymousGrpc.Bac
|
||||
}
|
||||
|
||||
@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());
|
||||
public GetCdnCredentialsResponse getCdnCredentials(final GetCdnCredentialsRequest request)
|
||||
throws BackupInvalidArgumentException, BackupPermissionException {
|
||||
try {
|
||||
final AuthenticatedBackupUser backupUser = authenticateBackupUser(request.getSignedPresentation());
|
||||
return GetCdnCredentialsResponse.newBuilder()
|
||||
.setCdnCredentials(GetCdnCredentialsResponse.CdnCredentials.newBuilder()
|
||||
.putAllHeaders(backupManager.generateReadAuth(backupUser, request.getCdn())))
|
||||
.build();
|
||||
} catch (BackupFailedZkAuthenticationException e) {
|
||||
return GetCdnCredentialsResponse.newBuilder()
|
||||
.setFailedAuthentication(FailedZkAuthentication.newBuilder().setDescription(e.getMessage()).build())
|
||||
.build();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public Mono<GetSvrBCredentialsResponse> getSvrBCredentials(final GetSvrBCredentialsRequest request) {
|
||||
return authenticateBackupUserMono(request.getSignedPresentation())
|
||||
.map(backupManager::generateSvrbAuth)
|
||||
.map(credentials -> GetSvrBCredentialsResponse.newBuilder()
|
||||
.setUsername(credentials.username())
|
||||
.setPassword(credentials.password())
|
||||
.build());
|
||||
public GetSvrBCredentialsResponse getSvrBCredentials(final GetSvrBCredentialsRequest request)
|
||||
throws BackupWrongCredentialTypeException, BackupPermissionException {
|
||||
try {
|
||||
final AuthenticatedBackupUser backupUser = authenticateBackupUser(request.getSignedPresentation());
|
||||
final ExternalServiceCredentials credentials = backupManager.generateSvrbAuth(backupUser);
|
||||
return GetSvrBCredentialsResponse.newBuilder()
|
||||
.setSvrbCredentials(GetSvrBCredentialsResponse.SvrBCredentials.newBuilder()
|
||||
.setUsername(credentials.username())
|
||||
.setPassword(credentials.password()))
|
||||
.build();
|
||||
} catch (BackupFailedZkAuthenticationException e) {
|
||||
return GetSvrBCredentialsResponse.newBuilder()
|
||||
.setFailedAuthentication(FailedZkAuthentication.newBuilder().setDescription(e.getMessage()).build())
|
||||
.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());
|
||||
public GetBackupInfoResponse getBackupInfo(final GetBackupInfoRequest request)
|
||||
throws BackupNotFoundException, BackupPermissionException {
|
||||
try {
|
||||
final AuthenticatedBackupUser backupUser = authenticateBackupUser(request.getSignedPresentation());
|
||||
final BackupManager.BackupInfo info = backupManager.backupInfo(backupUser);
|
||||
return GetBackupInfoResponse.newBuilder().setBackupInfo(GetBackupInfoResponse.BackupInfo.newBuilder()
|
||||
.setBackupName(info.messageBackupKey())
|
||||
.setCdn(info.cdn())
|
||||
.setBackupDir(info.backupSubdir())
|
||||
.setMediaDir(info.mediaSubdir())
|
||||
.setUsedSpace(info.mediaUsedSpace().orElse(0L)))
|
||||
.build();
|
||||
} catch (BackupFailedZkAuthenticationException e) {
|
||||
return GetBackupInfoResponse.newBuilder()
|
||||
.setFailedAuthentication(FailedZkAuthentication.newBuilder().setDescription(e.getMessage()).build())
|
||||
.build();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public Mono<RefreshResponse> refresh(final RefreshRequest request) {
|
||||
return Mono.fromFuture(() -> authenticateBackupUser(request.getSignedPresentation())
|
||||
.thenCompose(backupManager::ttlRefresh))
|
||||
.thenReturn(RefreshResponse.getDefaultInstance());
|
||||
public RefreshResponse refresh(final RefreshRequest request) throws BackupPermissionException {
|
||||
try {
|
||||
final AuthenticatedBackupUser backupUser = authenticateBackupUser(request.getSignedPresentation());
|
||||
backupManager.ttlRefresh(backupUser);
|
||||
return RefreshResponse.getDefaultInstance();
|
||||
} catch (BackupFailedZkAuthenticationException e) {
|
||||
return RefreshResponse.newBuilder()
|
||||
.setFailedAuthentication(FailedZkAuthentication.newBuilder().setDescription(e.getMessage()).build())
|
||||
.build();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public Mono<SetPublicKeyResponse> setPublicKey(final SetPublicKeyRequest request) {
|
||||
public SetPublicKeyResponse setPublicKey(final SetPublicKeyRequest request)
|
||||
throws BackupFailedZkAuthenticationException {
|
||||
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());
|
||||
backupManager.setPublicKey(presentation, signature, publicKey);
|
||||
return SetPublicKeyResponse.getDefaultInstance();
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public Mono<GetUploadFormResponse> getUploadForm(final GetUploadFormRequest request) {
|
||||
return authenticateBackupUserMono(request.getSignedPresentation())
|
||||
.flatMap(backupUser -> switch (request.getUploadTypeCase()) {
|
||||
case MESSAGES -> {
|
||||
final long uploadLength = request.getMessages().getUploadLength();
|
||||
final boolean oversize = uploadLength > BackupManager.MAX_MESSAGE_BACKUP_OBJECT_SIZE;
|
||||
backupMetrics.updateMessageBackupSizeDistribution(backupUser, oversize, Optional.of(uploadLength));
|
||||
if (oversize) {
|
||||
yield Mono.error(Status.FAILED_PRECONDITION
|
||||
.withDescription("Exceeds max upload length")
|
||||
.asRuntimeException());
|
||||
}
|
||||
|
||||
yield 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()
|
||||
public GetUploadFormResponse getUploadForm(final GetUploadFormRequest request)
|
||||
throws RateLimitExceededException, BackupWrongCredentialTypeException, BackupPermissionException {
|
||||
final AuthenticatedBackupUser backupUser;
|
||||
try {
|
||||
backupUser = authenticateBackupUser(request.getSignedPresentation());
|
||||
} catch (BackupFailedZkAuthenticationException e) {
|
||||
return GetUploadFormResponse.newBuilder()
|
||||
.setFailedAuthentication(FailedZkAuthentication.newBuilder().setDescription(e.getMessage()).build())
|
||||
.build();
|
||||
}
|
||||
final GetUploadFormResponse.Builder builder = GetUploadFormResponse.newBuilder();
|
||||
switch (request.getUploadTypeCase()) {
|
||||
case MESSAGES -> {
|
||||
final long uploadLength = request.getMessages().getUploadLength();
|
||||
final boolean oversize = uploadLength > BackupManager.MAX_MESSAGE_BACKUP_OBJECT_SIZE;
|
||||
backupMetrics.updateMessageBackupSizeDistribution(backupUser, oversize, Optional.of(uploadLength));
|
||||
if (oversize) {
|
||||
builder.setExceedsMaxUploadLength(FailedPrecondition.getDefaultInstance());
|
||||
} else {
|
||||
final BackupUploadDescriptor uploadDescriptor = backupManager.createMessageBackupUploadDescriptor(backupUser);
|
||||
builder.setUploadForm(builder.getUploadFormBuilder()
|
||||
.setCdn(uploadDescriptor.cdn())
|
||||
.setKey(uploadDescriptor.key())
|
||||
.setSignedUploadLocation(uploadDescriptor.signedUploadLocation())
|
||||
.putAllHeaders(uploadDescriptor.headers())).build();
|
||||
}
|
||||
}
|
||||
case MEDIA -> {
|
||||
final BackupUploadDescriptor uploadDescriptor = backupManager.createTemporaryAttachmentUploadDescriptor(
|
||||
backupUser);
|
||||
builder.setUploadForm(builder.getUploadFormBuilder()
|
||||
.setCdn(uploadDescriptor.cdn())
|
||||
.setKey(uploadDescriptor.key())
|
||||
.setSignedUploadLocation(uploadDescriptor.signedUploadLocation())
|
||||
.putAllHeaders(uploadDescriptor.headers())
|
||||
.build());
|
||||
.putAllHeaders(uploadDescriptor.headers())).build();
|
||||
}
|
||||
case UPLOADTYPE_NOT_SET -> throw GrpcExceptions.fieldViolation("upload_type", "Must set upload_type");
|
||||
}
|
||||
return builder.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()))
|
||||
public Flow.Publisher<CopyMediaResponse> copyMedia(final CopyMediaRequest request)
|
||||
throws BackupWrongCredentialTypeException, BackupPermissionException, BackupInvalidArgumentException {
|
||||
final BackupManager.CopyQuota copyQuota;
|
||||
try {
|
||||
final AuthenticatedBackupUser backupUser = authenticateBackupUser(request.getSignedPresentation());
|
||||
copyQuota = backupManager.getCopyQuota(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());
|
||||
} catch (BackupFailedZkAuthenticationException e) {
|
||||
return JdkFlowAdapter.publisherToFlowPublisher(Mono.just(CopyMediaResponse
|
||||
.newBuilder()
|
||||
.setFailedAuthentication(FailedZkAuthentication.newBuilder().setDescription(e.getMessage()))
|
||||
.build()));
|
||||
}
|
||||
return JdkFlowAdapter.publisherToFlowPublisher(backupManager.copyToBackup(copyQuota)
|
||||
.doOnNext(result -> backupMetrics.updateCopyCounter(
|
||||
result,
|
||||
UserAgentTagUtil.getPlatformTag(RequestAttributesUtil.getUserAgent().orElse(null))))
|
||||
@@ -166,65 +225,89 @@ public class BackupsAnonymousGrpcService extends ReactorBackupsAnonymousGrpc.Bac
|
||||
.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();
|
||||
});
|
||||
|
||||
public ListMediaResponse listMedia(final ListMediaRequest request) throws BackupPermissionException {
|
||||
try {
|
||||
final AuthenticatedBackupUser backupUser = authenticateBackupUser(request.getSignedPresentation());
|
||||
final BackupManager.ListMediaResult listResult = backupManager.list(
|
||||
backupUser,
|
||||
request.hasCursor() ? Optional.of(request.getCursor()) : Optional.empty(),
|
||||
request.getLimit());
|
||||
final ListMediaResponse.ListResult.Builder builder = ListMediaResponse.ListResult.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 ListMediaResponse.newBuilder().setListResult(builder).build();
|
||||
} catch (BackupFailedZkAuthenticationException e) {
|
||||
return ListMediaResponse.newBuilder()
|
||||
.setFailedAuthentication(FailedZkAuthentication.newBuilder().setDescription(e.getMessage()))
|
||||
.build();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public Mono<DeleteAllResponse> deleteAll(final DeleteAllRequest request) {
|
||||
return Mono.fromFuture(() -> authenticateBackupUser(request.getSignedPresentation())
|
||||
.thenCompose(backupManager::deleteEntireBackup))
|
||||
.thenReturn(DeleteAllResponse.getDefaultInstance());
|
||||
public DeleteAllResponse deleteAll(final DeleteAllRequest request) throws BackupPermissionException {
|
||||
try {
|
||||
final AuthenticatedBackupUser backupUser = authenticateBackupUser(request.getSignedPresentation());
|
||||
backupManager.deleteEntireBackup(backupUser);
|
||||
return DeleteAllResponse.getDefaultInstance();
|
||||
} catch (BackupFailedZkAuthenticationException e) {
|
||||
return DeleteAllResponse.newBuilder()
|
||||
.setFailedAuthentication(FailedZkAuthentication.newBuilder().setDescription(e.getMessage()))
|
||||
.build();
|
||||
}
|
||||
}
|
||||
|
||||
@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()))
|
||||
public Flow.Publisher<DeleteMediaResponse> deleteMedia(final DeleteMediaRequest request)
|
||||
throws BackupWrongCredentialTypeException, BackupPermissionException {
|
||||
final Flux<BackupManager.StorageDescriptor> deleteItems;
|
||||
try {
|
||||
final AuthenticatedBackupUser backupUser = authenticateBackupUser(request.getSignedPresentation());
|
||||
deleteItems = backupManager.deleteMedia(backupUser, request
|
||||
.getItemsList()
|
||||
.stream()
|
||||
.map(item -> new BackupManager.StorageDescriptor(item.getCdn(), item.getMediaId().toByteArray()))
|
||||
.toList());
|
||||
} catch (BackupFailedZkAuthenticationException e) {
|
||||
return JdkFlowAdapter.publisherToFlowPublisher(Mono.just(DeleteMediaResponse
|
||||
.newBuilder()
|
||||
.setFailedAuthentication(FailedZkAuthentication.newBuilder().setDescription(e.getMessage()))
|
||||
.build()));
|
||||
}
|
||||
return JdkFlowAdapter.publisherToFlowPublisher(deleteItems
|
||||
.map(storageDescriptor -> DeleteMediaResponse.newBuilder()
|
||||
.setMediaId(ByteString.copyFrom(storageDescriptor.key()))
|
||||
.setCdn(storageDescriptor.cdn()).build());
|
||||
.setDeletedItem(DeleteMediaItem.newBuilder()
|
||||
.setMediaId(ByteString.copyFrom(storageDescriptor.key()))
|
||||
.setCdn(storageDescriptor.cdn()))
|
||||
.build()));
|
||||
}
|
||||
|
||||
private Mono<AuthenticatedBackupUser> authenticateBackupUserMono(final SignedPresentation signedPresentation) {
|
||||
return Mono.fromFuture(() -> authenticateBackupUser(signedPresentation));
|
||||
@Override
|
||||
public Throwable mapException(final Throwable throwable) {
|
||||
return switch (throwable) {
|
||||
case BackupInvalidArgumentException e -> GrpcExceptions.invalidArguments(e.getMessage());
|
||||
case BackupPermissionException e -> GrpcExceptions.badAuthentication(e.getMessage());
|
||||
case BackupWrongCredentialTypeException e -> GrpcExceptions.badAuthentication(e.getMessage());
|
||||
default -> throwable;
|
||||
};
|
||||
}
|
||||
|
||||
private CompletableFuture<AuthenticatedBackupUser> authenticateBackupUser(
|
||||
final SignedPresentation signedPresentation) {
|
||||
private AuthenticatedBackupUser authenticateBackupUser(final SignedPresentation signedPresentation)
|
||||
throws BackupFailedZkAuthenticationException {
|
||||
if (signedPresentation == null) {
|
||||
throw Status.UNAUTHENTICATED.asRuntimeException();
|
||||
throw GrpcExceptions.badAuthentication("Missing required signedPresentation");
|
||||
}
|
||||
try {
|
||||
return backupManager.authenticateBackupUser(
|
||||
@@ -232,7 +315,7 @@ public class BackupsAnonymousGrpcService extends ReactorBackupsAnonymousGrpc.Bac
|
||||
signedPresentation.getPresentationSignature().toByteArray(),
|
||||
RequestAttributesUtil.getUserAgent().orElse(null));
|
||||
} catch (InvalidInputException e) {
|
||||
throw Status.UNAUTHENTICATED.withDescription("Could not deserialize presentation").asRuntimeException();
|
||||
throw GrpcExceptions.badAuthentication("Could not deserialize presentation");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -242,7 +325,7 @@ public class BackupsAnonymousGrpcService extends ReactorBackupsAnonymousGrpc.Bac
|
||||
*/
|
||||
private static int fromUnsignedExact(final int i) {
|
||||
if (i < 0) {
|
||||
throw Status.INVALID_ARGUMENT.withDescription("Invalid size").asRuntimeException();
|
||||
throw GrpcExceptions.invalidArguments("integer length too large");
|
||||
}
|
||||
return i;
|
||||
}
|
||||
@@ -256,7 +339,7 @@ public class BackupsAnonymousGrpcService extends ReactorBackupsAnonymousGrpc.Bac
|
||||
try {
|
||||
return deserializer.deserialize(bytes);
|
||||
} catch (InvalidInputException | InvalidKeyException e) {
|
||||
throw Status.INVALID_ARGUMENT.withDescription("Invalid serialization").asRuntimeException();
|
||||
throw GrpcExceptions.invalidArguments("invalid serialization");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+64
-38
@@ -5,6 +5,7 @@
|
||||
package org.whispersystems.textsecuregcm.grpc;
|
||||
|
||||
import com.google.protobuf.ByteString;
|
||||
import com.google.protobuf.Empty;
|
||||
import io.grpc.Status;
|
||||
import io.micrometer.core.instrument.Tag;
|
||||
import java.time.Clock;
|
||||
@@ -14,12 +15,13 @@ import java.util.Optional;
|
||||
import java.util.stream.Collectors;
|
||||
import org.signal.chat.backup.GetBackupAuthCredentialsRequest;
|
||||
import org.signal.chat.backup.GetBackupAuthCredentialsResponse;
|
||||
import org.signal.chat.backup.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.backup.SimpleBackupsGrpc;
|
||||
import org.signal.chat.common.ZkCredential;
|
||||
import org.signal.chat.errors.FailedPrecondition;
|
||||
import org.signal.libsignal.zkgroup.InvalidInputException;
|
||||
import org.signal.libsignal.zkgroup.backups.BackupAuthCredentialRequest;
|
||||
import org.signal.libsignal.zkgroup.backups.BackupCredentialType;
|
||||
@@ -28,14 +30,20 @@ import org.whispersystems.textsecuregcm.auth.RedemptionRange;
|
||||
import org.whispersystems.textsecuregcm.auth.grpc.AuthenticatedDevice;
|
||||
import org.whispersystems.textsecuregcm.auth.grpc.AuthenticationUtil;
|
||||
import org.whispersystems.textsecuregcm.backup.BackupAuthManager;
|
||||
import org.whispersystems.textsecuregcm.backup.BackupBadReceiptException;
|
||||
import org.whispersystems.textsecuregcm.backup.BackupInvalidArgumentException;
|
||||
import org.whispersystems.textsecuregcm.backup.BackupMissingIdCommitmentException;
|
||||
import org.whispersystems.textsecuregcm.backup.BackupNotFoundException;
|
||||
import org.whispersystems.textsecuregcm.backup.BackupPermissionException;
|
||||
import org.whispersystems.textsecuregcm.backup.BackupWrongCredentialTypeException;
|
||||
import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
|
||||
import org.whispersystems.textsecuregcm.metrics.BackupMetrics;
|
||||
import org.whispersystems.textsecuregcm.metrics.UserAgentTagUtil;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.Device;
|
||||
import reactor.core.publisher.Mono;
|
||||
|
||||
public class BackupsGrpcService extends ReactorBackupsGrpc.BackupsImplBase {
|
||||
public class BackupsGrpcService extends SimpleBackupsGrpc.BackupsImplBase {
|
||||
|
||||
private final AccountsManager accountManager;
|
||||
private final BackupAuthManager backupAuthManager;
|
||||
@@ -48,7 +56,8 @@ public class BackupsGrpcService extends ReactorBackupsGrpc.BackupsImplBase {
|
||||
}
|
||||
|
||||
@Override
|
||||
public Mono<SetBackupIdResponse> setBackupId(SetBackupIdRequest request) {
|
||||
public SetBackupIdResponse setBackupId(SetBackupIdRequest request)
|
||||
throws RateLimitExceededException, BackupInvalidArgumentException, BackupPermissionException {
|
||||
|
||||
final Optional<BackupAuthCredentialRequest> messagesCredentialRequest = deserializeWithEmptyPresenceCheck(
|
||||
BackupAuthCredentialRequest::new,
|
||||
@@ -59,28 +68,33 @@ public class BackupsGrpcService extends ReactorBackupsGrpc.BackupsImplBase {
|
||||
request.getMediaBackupAuthCredentialRequest());
|
||||
|
||||
final AuthenticatedDevice authenticatedDevice = AuthenticationUtil.requireAuthenticatedDevice();
|
||||
return authenticatedAccount()
|
||||
.flatMap(account -> {
|
||||
final Device device = account
|
||||
.getDevice(authenticatedDevice.deviceId())
|
||||
.orElseThrow(Status.UNAUTHENTICATED::asRuntimeException);
|
||||
return Mono.fromFuture(
|
||||
backupAuthManager.commitBackupId(account, device, messagesCredentialRequest, mediaCredentialRequest));
|
||||
})
|
||||
.thenReturn(SetBackupIdResponse.getDefaultInstance());
|
||||
final Account account = authenticatedAccount();
|
||||
final Device device = account
|
||||
.getDevice(authenticatedDevice.deviceId())
|
||||
.orElseThrow(Status.UNAUTHENTICATED::asRuntimeException);
|
||||
backupAuthManager.commitBackupId(account, device, messagesCredentialRequest, mediaCredentialRequest);
|
||||
return SetBackupIdResponse.getDefaultInstance();
|
||||
}
|
||||
|
||||
public Mono<RedeemReceiptResponse> redeemReceipt(RedeemReceiptRequest request) {
|
||||
public RedeemReceiptResponse redeemReceipt(RedeemReceiptRequest request) throws BackupInvalidArgumentException {
|
||||
final ReceiptCredentialPresentation receiptCredentialPresentation = deserialize(
|
||||
ReceiptCredentialPresentation::new,
|
||||
request.getPresentation().toByteArray());
|
||||
return authenticatedAccount()
|
||||
.flatMap(account -> Mono.fromFuture(backupAuthManager.redeemReceipt(account, receiptCredentialPresentation)))
|
||||
.thenReturn(RedeemReceiptResponse.getDefaultInstance());
|
||||
final Account account = authenticatedAccount();
|
||||
final RedeemReceiptResponse.Builder builder = RedeemReceiptResponse.newBuilder();
|
||||
try {
|
||||
backupAuthManager.redeemReceipt(account, receiptCredentialPresentation);
|
||||
builder.setSuccess(Empty.getDefaultInstance());
|
||||
} catch (BackupBadReceiptException e) {
|
||||
builder.setInvalidReceipt(FailedPrecondition.newBuilder().setDescription(e.getMessage()).build());
|
||||
} catch (BackupMissingIdCommitmentException e) {
|
||||
builder.setAccountMissingCommitment(FailedPrecondition.newBuilder().build());
|
||||
}
|
||||
return builder.build();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Mono<GetBackupAuthCredentialsResponse> getBackupAuthCredentials(GetBackupAuthCredentialsRequest request) {
|
||||
public GetBackupAuthCredentialsResponse getBackupAuthCredentials(GetBackupAuthCredentialsRequest request) {
|
||||
final Tag platformTag = UserAgentTagUtil.getPlatformTag(RequestAttributesUtil.getUserAgent().orElse(null));
|
||||
final RedemptionRange redemptionRange;
|
||||
try {
|
||||
@@ -90,46 +104,58 @@ public class BackupsGrpcService extends ReactorBackupsGrpc.BackupsImplBase {
|
||||
} catch (IllegalArgumentException e) {
|
||||
throw Status.INVALID_ARGUMENT.withDescription(e.getMessage()).asRuntimeException();
|
||||
}
|
||||
return authenticatedAccount().flatMap(account -> {
|
||||
final Mono<List<BackupAuthManager.Credential>> messageCredentials = Mono.fromCompletionStage(() ->
|
||||
final Account account = authenticatedAccount();
|
||||
try {
|
||||
final List<BackupAuthManager.Credential> messageCredentials =
|
||||
backupAuthManager.getBackupAuthCredentials(
|
||||
account,
|
||||
BackupCredentialType.MESSAGES,
|
||||
redemptionRange))
|
||||
.doOnSuccess(credentials ->
|
||||
backupMetrics.updateGetCredentialCounter(platformTag, BackupCredentialType.MESSAGES, credentials.size()));
|
||||
redemptionRange);
|
||||
backupMetrics.updateGetCredentialCounter(platformTag, BackupCredentialType.MESSAGES, messageCredentials.size());
|
||||
|
||||
final Mono<List<BackupAuthManager.Credential>> mediaCredentials = Mono.fromCompletionStage(() ->
|
||||
final List<BackupAuthManager.Credential> mediaCredentials =
|
||||
backupAuthManager.getBackupAuthCredentials(
|
||||
account,
|
||||
BackupCredentialType.MEDIA,
|
||||
redemptionRange))
|
||||
.doOnSuccess(credentials ->
|
||||
backupMetrics.updateGetCredentialCounter(platformTag, BackupCredentialType.MEDIA, credentials.size()));
|
||||
redemptionRange);
|
||||
backupMetrics.updateGetCredentialCounter(platformTag, BackupCredentialType.MEDIA, mediaCredentials.size());
|
||||
|
||||
return messageCredentials.zipWith(mediaCredentials, (messageCreds, mediaCreds) ->
|
||||
GetBackupAuthCredentialsResponse.newBuilder()
|
||||
.putAllMessageCredentials(messageCreds.stream().collect(Collectors.toMap(
|
||||
return GetBackupAuthCredentialsResponse.newBuilder()
|
||||
.setCredentials(GetBackupAuthCredentialsResponse.Credentials.newBuilder()
|
||||
.putAllMessageCredentials(messageCredentials.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(
|
||||
.putAllMediaCredentials(mediaCredentials.stream().collect(Collectors.toMap(
|
||||
c -> c.redemptionTime().getEpochSecond(),
|
||||
c -> ZkCredential.newBuilder()
|
||||
.setCredential(ByteString.copyFrom(c.credential().serialize()))
|
||||
.setRedemptionTime(c.redemptionTime().getEpochSecond())
|
||||
.build())))
|
||||
.build());
|
||||
});
|
||||
.build())
|
||||
.build();
|
||||
} catch (BackupNotFoundException _) {
|
||||
// Return an empty response to indicate that the authenticated account had no associated blinded backup-id
|
||||
return GetBackupAuthCredentialsResponse.getDefaultInstance();
|
||||
}
|
||||
}
|
||||
|
||||
private Mono<Account> authenticatedAccount() {
|
||||
final AuthenticatedDevice authenticatedDevice = AuthenticationUtil.requireAuthenticatedDevice();
|
||||
return Mono
|
||||
.fromFuture(() -> accountManager.getByAccountIdentifierAsync(authenticatedDevice.accountIdentifier()))
|
||||
.map(maybeAccount -> maybeAccount.orElseThrow(Status.UNAUTHENTICATED::asRuntimeException));
|
||||
@Override
|
||||
public Throwable mapException(final Throwable throwable) {
|
||||
return switch (throwable) {
|
||||
case BackupInvalidArgumentException e -> GrpcExceptions.invalidArguments(e.getMessage());
|
||||
case BackupPermissionException e -> GrpcExceptions.badAuthentication(e.getMessage());
|
||||
case BackupWrongCredentialTypeException e -> GrpcExceptions.badAuthentication(e.getMessage());
|
||||
default -> throwable;
|
||||
};
|
||||
}
|
||||
|
||||
private Account authenticatedAccount() {
|
||||
return accountManager
|
||||
.getByAccountIdentifier(AuthenticationUtil.requireAuthenticatedDevice().accountIdentifier())
|
||||
.orElseThrow(Status.UNAUTHENTICATED::asRuntimeException);
|
||||
}
|
||||
|
||||
private interface Deserializer<T> {
|
||||
|
||||
+2
-4
@@ -7,14 +7,12 @@ package org.whispersystems.textsecuregcm.grpc;
|
||||
|
||||
import io.grpc.Metadata;
|
||||
import io.grpc.Status;
|
||||
import io.grpc.StatusRuntimeException;
|
||||
import java.util.Optional;
|
||||
|
||||
/**
|
||||
* Interface to be implemented by our custom exceptions that are consistently mapped to a gRPC status.
|
||||
*/
|
||||
public interface ConvertibleToGrpcStatus {
|
||||
|
||||
Status grpcStatus();
|
||||
|
||||
Optional<Metadata> grpcMetadata();
|
||||
StatusRuntimeException toStatusRuntimeException();
|
||||
}
|
||||
+35
-7
@@ -11,6 +11,12 @@ import io.grpc.ServerCall;
|
||||
import io.grpc.ServerCallHandler;
|
||||
import io.grpc.ServerInterceptor;
|
||||
import io.grpc.Status;
|
||||
import io.grpc.StatusRuntimeException;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.util.ExceptionUtils;
|
||||
import java.io.IOException;
|
||||
import java.io.UncheckedIOException;
|
||||
|
||||
/**
|
||||
* This interceptor observes responses from the service and if the response status is {@link Status#UNKNOWN}
|
||||
@@ -21,6 +27,8 @@ import io.grpc.Status;
|
||||
*/
|
||||
public class ErrorMappingInterceptor implements ServerInterceptor {
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(ErrorMappingInterceptor.class);
|
||||
|
||||
@Override
|
||||
public <ReqT, RespT> ServerCall.Listener<ReqT> interceptCall(
|
||||
final ServerCall<ReqT, RespT> call,
|
||||
@@ -34,15 +42,35 @@ public class ErrorMappingInterceptor implements ServerInterceptor {
|
||||
// I.e. if at this point we see anything but the `UNKNOWN`,
|
||||
// that means that some logic in the service made this decision already
|
||||
// and automatic conversion may conflict with it.
|
||||
if (status.getCode().equals(Status.Code.UNKNOWN)
|
||||
&& status.getCause() instanceof ConvertibleToGrpcStatus convertibleToGrpcStatus) {
|
||||
super.close(
|
||||
convertibleToGrpcStatus.grpcStatus(),
|
||||
convertibleToGrpcStatus.grpcMetadata().orElseGet(Metadata::new)
|
||||
);
|
||||
} else {
|
||||
if (!status.getCode().equals(Status.Code.UNKNOWN)) {
|
||||
super.close(status, trailers);
|
||||
return;
|
||||
}
|
||||
|
||||
final Throwable cause = ExceptionUtils.unwrap(status.getCause());
|
||||
|
||||
final StatusRuntimeException statusException = switch (cause) {
|
||||
case ConvertibleToGrpcStatus e -> e.toStatusRuntimeException();
|
||||
case UncheckedIOException e -> {
|
||||
log.warn("RPC {} encountered UncheckedIOException", call.getMethodDescriptor().getFullMethodName(), e.getCause());
|
||||
yield GrpcExceptions.unavailable(e.getCause().getMessage());
|
||||
}
|
||||
case IOException e -> {
|
||||
log.warn("RPC {} encountered IOException", call.getMethodDescriptor().getFullMethodName(), e);
|
||||
yield GrpcExceptions.unavailable(e.getMessage());
|
||||
}
|
||||
case null -> {
|
||||
log.error("RPC {} finished with status UNKNOWN: {}",
|
||||
call.getMethodDescriptor().getFullMethodName(), status.getDescription());
|
||||
yield GrpcExceptions.unavailable(status.getDescription());
|
||||
}
|
||||
default -> {
|
||||
log.error("RPC {} finished with status UNKNOWN",
|
||||
call.getMethodDescriptor().getFullMethodName(), status.getCause());
|
||||
yield GrpcExceptions.unavailable(status.getCause().getMessage());
|
||||
}
|
||||
};
|
||||
super.close(statusException.getStatus(), statusException.getTrailers());
|
||||
}
|
||||
}, headers);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,178 @@
|
||||
/*
|
||||
* Copyright 2025 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.grpc;
|
||||
|
||||
import com.google.protobuf.Any;
|
||||
import com.google.rpc.BadRequest;
|
||||
import com.google.rpc.ErrorInfo;
|
||||
import com.google.rpc.RetryInfo;
|
||||
import io.grpc.Status;
|
||||
import io.grpc.StatusRuntimeException;
|
||||
import io.grpc.protobuf.StatusProto;
|
||||
import java.time.Duration;
|
||||
import javax.annotation.Nullable;
|
||||
|
||||
public class GrpcExceptions {
|
||||
|
||||
public static final String DOMAIN = "grpc.chat.signal.org";
|
||||
|
||||
private static final Any ERROR_INFO_CONSTRAINT_VIOLATED = Any.pack(ErrorInfo.newBuilder()
|
||||
.setDomain(DOMAIN)
|
||||
.setReason("CONSTRAINT_VIOLATED")
|
||||
.build());
|
||||
|
||||
private static final Any ERROR_INFO_RESOURCE_EXHAUSTED = Any.pack(ErrorInfo.newBuilder()
|
||||
.setDomain(DOMAIN)
|
||||
.setReason("RESOURCE_EXHAUSTED")
|
||||
.build());
|
||||
|
||||
private static final Any ERROR_INFO_INVALID_CREDENTIALS = Any.pack(ErrorInfo.newBuilder()
|
||||
.setDomain(DOMAIN)
|
||||
.setReason("INVALID_CREDENTIALS")
|
||||
.build());
|
||||
|
||||
private static final Any ERROR_INFO_BAD_AUTHENTICATION = Any.pack(ErrorInfo.newBuilder()
|
||||
.setDomain(DOMAIN)
|
||||
.setReason("BAD_AUTHENTICATION")
|
||||
.build());
|
||||
|
||||
private static final com.google.rpc.Status UPGRADE_REQUIRED = com.google.rpc.Status.newBuilder()
|
||||
.setCode(Status.Code.INVALID_ARGUMENT.value())
|
||||
.setMessage("Upgrade required")
|
||||
.addDetails(Any.pack(ErrorInfo.newBuilder()
|
||||
.setDomain(DOMAIN)
|
||||
.setReason("UPGRADE_REQUIRED")
|
||||
.build()))
|
||||
.build();
|
||||
|
||||
|
||||
private GrpcExceptions() {
|
||||
}
|
||||
|
||||
/// The client version provided in the User-Agent is no longer supported. The client must upgrade to use the service.
|
||||
///
|
||||
/// @return A [StatusRuntimeException] encoding the error
|
||||
public static StatusRuntimeException upgradeRequired() {
|
||||
return StatusProto.toStatusRuntimeException(UPGRADE_REQUIRED);
|
||||
}
|
||||
|
||||
/// The RPC argument violated a constraint that was annotated or documented in the service definition. It is always
|
||||
/// possible to check this constraint without communicating with the chat server. This always represents a client bug
|
||||
/// or out of date client. Additional information about the violating field will be included in the metadata.
|
||||
///
|
||||
/// @param fieldName The name of the field that violated a service constraint
|
||||
/// @param message Additional context about the constraint violation
|
||||
/// @return A [StatusRuntimeException] encoding the error
|
||||
public static StatusRuntimeException fieldViolation(final String fieldName, @Nullable final String message) {
|
||||
return StatusProto.toStatusRuntimeException(com.google.rpc.Status.newBuilder()
|
||||
.setCode(Status.Code.INVALID_ARGUMENT.value())
|
||||
.setMessage(messageOrDefault(message, Status.Code.INVALID_ARGUMENT))
|
||||
.addDetails(ERROR_INFO_CONSTRAINT_VIOLATED)
|
||||
.addDetails(Any.pack(BadRequest.newBuilder()
|
||||
.addFieldViolations(BadRequest.FieldViolation.newBuilder()
|
||||
.setField(fieldName)
|
||||
.setDescription(messageOrDefault(message, Status.Code.INVALID_ARGUMENT)))
|
||||
.build()))
|
||||
.build());
|
||||
}
|
||||
|
||||
/// The RPC argument violated a constraint that was annotated or documented in the service definition. It is always
|
||||
/// possible to check this constraint without communicating with the chat server. This always represents a client bug
|
||||
/// or out of date client.
|
||||
///
|
||||
/// @param message Additional context about the constraint violation
|
||||
/// @return A [StatusRuntimeException] encoding the error
|
||||
public static StatusRuntimeException invalidArguments(@Nullable final String message) {
|
||||
return StatusProto.toStatusRuntimeException(com.google.rpc.Status.newBuilder()
|
||||
.setCode(Status.Code.INVALID_ARGUMENT.value())
|
||||
.setMessage(messageOrDefault(message, Status.Code.INVALID_ARGUMENT))
|
||||
.addDetails(ERROR_INFO_CONSTRAINT_VIOLATED)
|
||||
.build());
|
||||
}
|
||||
|
||||
/// The RPC argument violated a constraint that was annotated or documented in the service definition. It is always
|
||||
/// possible to check this constraint without communicating with the chat server. This always represents a client bug
|
||||
/// or out of date client.
|
||||
///
|
||||
/// @param message Additional context about the constraint violation
|
||||
/// @return A [StatusRuntimeException] encoding the error
|
||||
public static StatusRuntimeException constraintViolation(@Nullable final String message) {
|
||||
return StatusProto.toStatusRuntimeException(com.google.rpc.Status.newBuilder()
|
||||
.setCode(Status.Code.INVALID_ARGUMENT.value())
|
||||
.setMessage(messageOrDefault(message, Status.Code.INVALID_ARGUMENT))
|
||||
.addDetails(ERROR_INFO_CONSTRAINT_VIOLATED)
|
||||
.build());
|
||||
}
|
||||
|
||||
/// The request has incorrectly set authentication credentials for the RPC. This represents a client bug where the
|
||||
/// authorization header is not correct for the RPC. For example,
|
||||
///
|
||||
/// - The RPC was for an anonymous service, but included an Authentication header in the RPC metadata
|
||||
/// - The RPC should only be made by the primary device, but the request had linked device credentials
|
||||
///
|
||||
/// @param message indicating why the credentials were set incorrectly
|
||||
/// @return A [StatusRuntimeException] encoding the error
|
||||
public static StatusRuntimeException badAuthentication(@Nullable final String message) {
|
||||
return StatusProto.toStatusRuntimeException(com.google.rpc.Status.newBuilder()
|
||||
.setCode(Status.Code.INVALID_ARGUMENT.value())
|
||||
.setMessage(messageOrDefault(message, Status.Code.INVALID_ARGUMENT))
|
||||
.addDetails(ERROR_INFO_BAD_AUTHENTICATION)
|
||||
.build());
|
||||
}
|
||||
|
||||
/// The account credentials provided in the authorization header are no longer valid.
|
||||
///
|
||||
/// @param message indicating why the credentials were invalid
|
||||
/// @return A [StatusRuntimeException] encoding the error
|
||||
public static StatusRuntimeException invalidCredentials(@Nullable final String message) {
|
||||
return StatusProto.toStatusRuntimeException(com.google.rpc.Status.newBuilder()
|
||||
.setCode(Status.Code.UNAUTHENTICATED.value())
|
||||
.setMessage(messageOrDefault(message, Status.Code.UNAUTHENTICATED))
|
||||
.addDetails(ERROR_INFO_INVALID_CREDENTIALS)
|
||||
.build());
|
||||
}
|
||||
|
||||
/// A server-side resource was exhausted. The details field may include a RetryInfo message that includes the amount
|
||||
/// of time in seconds the client should wait before retrying the request.
|
||||
///
|
||||
/// If a RetryInfo is present, the client must wait the indicated time before retrying the request. If absent, the
|
||||
/// client should retry with an exponential backoff.
|
||||
///
|
||||
/// @param retryDuration If present, the duration the client should wait before retrying the request
|
||||
/// @return A [StatusRuntimeException] encoding the error
|
||||
public static StatusRuntimeException rateLimitExceeded(@Nullable final Duration retryDuration) {
|
||||
final com.google.rpc.Status.Builder builder = com.google.rpc.Status.newBuilder()
|
||||
.setCode(Status.Code.RESOURCE_EXHAUSTED.value())
|
||||
.addDetails(ERROR_INFO_RESOURCE_EXHAUSTED);
|
||||
|
||||
if (retryDuration != null) {
|
||||
builder.addDetails(Any.pack(RetryInfo.newBuilder()
|
||||
.setRetryDelay(com.google.protobuf.Duration.newBuilder()
|
||||
.setSeconds(retryDuration.getSeconds())
|
||||
.setNanos(retryDuration.getNano()))
|
||||
.build()));
|
||||
}
|
||||
return StatusProto.toStatusRuntimeException(builder.build());
|
||||
}
|
||||
|
||||
/// There was an internal error processing the RPC. The client should retry the request with exponential backoff.
|
||||
///
|
||||
/// @return A [StatusRuntimeException] encoding the error
|
||||
public static StatusRuntimeException unavailable(@Nullable final String message) {
|
||||
return StatusProto.toStatusRuntimeException(com.google.rpc.Status.newBuilder()
|
||||
.setCode(Status.Code.UNAVAILABLE.value())
|
||||
.setMessage(messageOrDefault(message, Status.Code.UNAVAILABLE))
|
||||
.addDetails(Any.pack(ErrorInfo.newBuilder()
|
||||
.setDomain(DOMAIN)
|
||||
.setReason("UNAVAILABLE")
|
||||
.build()))
|
||||
.build());
|
||||
}
|
||||
|
||||
private static String messageOrDefault(@Nullable final String message, Status.Code code) {
|
||||
return message == null ? code.toString() : message;
|
||||
}
|
||||
}
|
||||
+88
-6
@@ -6,26 +6,50 @@
|
||||
package org.whispersystems.textsecuregcm.grpc;
|
||||
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import io.grpc.*;
|
||||
import com.google.protobuf.Descriptors;
|
||||
import com.google.protobuf.InvalidProtocolBufferException;
|
||||
import com.google.protobuf.Message;
|
||||
import com.google.rpc.ErrorInfo;
|
||||
import io.grpc.ForwardingServerCall;
|
||||
import io.grpc.ForwardingServerCallListener;
|
||||
import io.grpc.Metadata;
|
||||
import io.grpc.ServerCall;
|
||||
import io.grpc.ServerCallHandler;
|
||||
import io.grpc.ServerInterceptor;
|
||||
import io.grpc.Status;
|
||||
import io.grpc.protobuf.StatusProto;
|
||||
import io.micrometer.core.instrument.Counter;
|
||||
import io.micrometer.core.instrument.MeterRegistry;
|
||||
import io.micrometer.core.instrument.Tag;
|
||||
import io.micrometer.core.instrument.Tags;
|
||||
import io.micrometer.core.instrument.Timer;
|
||||
import java.io.UncheckedIOException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.stream.Stream;
|
||||
import javax.annotation.Nullable;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
|
||||
import org.whispersystems.textsecuregcm.metrics.UserAgentTagUtil;
|
||||
import org.whispersystems.textsecuregcm.storage.ClientReleaseManager;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
public class MetricServerInterceptor implements ServerInterceptor {
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(MetricServerInterceptor.class);
|
||||
|
||||
private static final String TAG_SERVICE_NAME = "grpcService";
|
||||
private static final String TAG_METHOD_NAME = "method";
|
||||
private static final String TAG_METHOD_TYPE = "methodType";
|
||||
private static final String TAG_STATUS_CODE = "statusCode";
|
||||
private static final String TAG_REASON = "reason";
|
||||
|
||||
@VisibleForTesting
|
||||
static final String DEFAULT_SUCCESS_REASON = "success";
|
||||
@VisibleForTesting
|
||||
static final String DEFAULT_ERROR_REASON = "n/a";
|
||||
|
||||
@VisibleForTesting
|
||||
static final String REQUEST_MESSAGE_COUNTER_NAME = MetricsUtil.name(MetricServerInterceptor.class, "requestMessage");
|
||||
@@ -77,6 +101,7 @@ public class MetricServerInterceptor implements ServerInterceptor {
|
||||
|
||||
private final Counter responseMessageCounter;
|
||||
private final Tags tags;
|
||||
private @Nullable String reason = null;
|
||||
|
||||
MetricServerCall(final ServerCall<ReqT, RespT> delegate, final Tags tags) {
|
||||
super(delegate);
|
||||
@@ -86,15 +111,59 @@ public class MetricServerInterceptor implements ServerInterceptor {
|
||||
|
||||
@Override
|
||||
public void close(final Status status, final Metadata responseHeaders) {
|
||||
meterRegistry.counter(RPC_COUNTER_NAME, tags.and(TAG_STATUS_CODE, status.getCode().name())).increment();
|
||||
if (!status.isOk()) {
|
||||
reason = errorInfo(StatusProto.fromStatusAndTrailers(status, responseHeaders))
|
||||
.map(ErrorInfo::getReason)
|
||||
.orElse(DEFAULT_ERROR_REASON);
|
||||
}
|
||||
Tags responseTags = tags.and(Tag.of(TAG_STATUS_CODE, status.getCode().name()));
|
||||
if (reason != null) {
|
||||
responseTags = responseTags.and(TAG_REASON, reason);
|
||||
}
|
||||
meterRegistry.counter(RPC_COUNTER_NAME, responseTags).increment();
|
||||
super.close(status, responseHeaders);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void sendMessage(final RespT responseMessage) {
|
||||
this.responseMessageCounter.increment();
|
||||
// Extract the annotated reason (if any) from the message
|
||||
final String messageReason = MetricServerCall.reason(responseMessage);
|
||||
|
||||
// If there are multiple messages sent on this RPC (server-side streaming), just use the most recent reason
|
||||
this.reason = messageReason == null ? DEFAULT_SUCCESS_REASON : messageReason;
|
||||
|
||||
super.sendMessage(responseMessage);
|
||||
}
|
||||
|
||||
@Nullable
|
||||
private static String reason(final Object obj) {
|
||||
if (!(obj instanceof Message msg)) {
|
||||
return null;
|
||||
}
|
||||
// iterate through all fields on the message
|
||||
for (Map.Entry<Descriptors.FieldDescriptor, Object> field : msg.getAllFields().entrySet()) {
|
||||
// iterate through all options on the field
|
||||
for (Map.Entry<Descriptors.FieldDescriptor, Object> option : field.getKey().getOptions().getAllFields().entrySet()) {
|
||||
if (option.getKey().getFullName().equals("org.signal.chat.tag.reason")) {
|
||||
if (!(option.getValue() instanceof String s)) {
|
||||
log.error("Invalid value for option tag.reason {}", option.getValue());
|
||||
continue;
|
||||
}
|
||||
// return the first tag we see
|
||||
return s;
|
||||
}
|
||||
}
|
||||
|
||||
// No reason on this field. Recursively check subfields of this field for a reason
|
||||
final String subReason = reason(field.getValue());
|
||||
if (subReason != null) {
|
||||
return subReason;
|
||||
}
|
||||
}
|
||||
// No field or subfield contained an annotated reason
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -131,4 +200,17 @@ public class MetricServerInterceptor implements ServerInterceptor {
|
||||
super.onCancel();
|
||||
}
|
||||
}
|
||||
|
||||
private static Optional<ErrorInfo> errorInfo(final com.google.rpc.Status statusProto) {
|
||||
return statusProto.getDetailsList().stream()
|
||||
.filter(any -> any.is(ErrorInfo.class))
|
||||
.map(errorInfo -> {
|
||||
try {
|
||||
return errorInfo.unpack(ErrorInfo.class);
|
||||
} catch (final InvalidProtocolBufferException e) {
|
||||
throw new UncheckedIOException(e);
|
||||
}
|
||||
})
|
||||
.findFirst();
|
||||
}
|
||||
}
|
||||
+20
@@ -8,6 +8,7 @@ package org.whispersystems.textsecuregcm.grpc;
|
||||
import io.grpc.Metadata;
|
||||
import io.grpc.ServerCall;
|
||||
import io.grpc.Status;
|
||||
import io.grpc.StatusRuntimeException;
|
||||
|
||||
public class ServerInterceptorUtil {
|
||||
|
||||
@@ -36,4 +37,23 @@ public class ServerInterceptorUtil {
|
||||
//noinspection unchecked
|
||||
return NO_OP_LISTENER;
|
||||
}
|
||||
|
||||
/**
|
||||
* Closes the given server call with the status and metadata from the provided exception, returning a no-op listener.
|
||||
*
|
||||
* @param call the server call to close
|
||||
* @param exception the {@link StatusRuntimeException} with which to close the call
|
||||
*
|
||||
* @return a no-op server call listener
|
||||
*
|
||||
* @param <ReqT> the type of request object handled by the server call
|
||||
* @param <RespT> the type of response object returned by the server call
|
||||
*/
|
||||
public static <ReqT, RespT> ServerCall.Listener<ReqT> closeWithStatusException(final ServerCall<ReqT, RespT> call, final StatusRuntimeException exception) {
|
||||
call.close(exception.getStatus(), exception.getTrailers());
|
||||
|
||||
//noinspection unchecked
|
||||
return NO_OP_LISTENER;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,12 +0,0 @@
|
||||
/*
|
||||
* Copyright 2023 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.grpc;
|
||||
|
||||
import io.grpc.Status;
|
||||
|
||||
public abstract class StatusConstants {
|
||||
public static final Status UPGRADE_NEEDED_STATUS = Status.INVALID_ARGUMENT.withDescription("signal-upgrade-required");
|
||||
}
|
||||
+32
-14
@@ -9,6 +9,7 @@ import com.google.common.annotations.VisibleForTesting;
|
||||
import io.github.resilience4j.circuitbreaker.CircuitBreaker;
|
||||
import io.github.resilience4j.retry.Retry;
|
||||
import io.github.resilience4j.retry.RetryConfig;
|
||||
import java.io.IOException;
|
||||
import java.net.http.HttpClient;
|
||||
import java.net.http.HttpRequest;
|
||||
import java.net.http.HttpResponse;
|
||||
@@ -18,6 +19,7 @@ import java.time.Duration;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.Callable;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.CompletionStage;
|
||||
import java.util.concurrent.Executor;
|
||||
@@ -29,8 +31,8 @@ import java.util.stream.IntStream;
|
||||
import javax.annotation.Nullable;
|
||||
import org.glassfish.jersey.SslConfigurator;
|
||||
import org.whispersystems.textsecuregcm.util.CertificateUtil;
|
||||
import org.whispersystems.textsecuregcm.util.ResilienceUtil;
|
||||
import org.whispersystems.textsecuregcm.util.ExceptionUtils;
|
||||
import org.whispersystems.textsecuregcm.util.ResilienceUtil;
|
||||
|
||||
public class FaultTolerantHttpClient {
|
||||
|
||||
@@ -65,17 +67,31 @@ public class FaultTolerantHttpClient {
|
||||
return this.httpClients.get(ThreadLocalRandom.current().nextInt(this.httpClients.size()));
|
||||
}
|
||||
|
||||
public <T> CompletableFuture<HttpResponse<T>> sendAsync(HttpRequest request,
|
||||
public <T> HttpResponse<T> send(final HttpRequest request, final HttpResponse.BodyHandler<T> bodyHandler)
|
||||
throws IOException {
|
||||
final Callable<HttpResponse<T>> requestCallable =
|
||||
() -> httpClient().send(requestWithTimeout(request, defaultRequestTimeout), bodyHandler);
|
||||
|
||||
try {
|
||||
return retry != null
|
||||
? breaker.executeCallable(retry.decorateCallable(requestCallable))
|
||||
: breaker.executeCallable(requestCallable);
|
||||
} catch (final IOException e) {
|
||||
throw e;
|
||||
} catch (final Exception e) {
|
||||
if (e instanceof RuntimeException runtimeException) {
|
||||
throw runtimeException;
|
||||
}
|
||||
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
|
||||
public <T> CompletableFuture<HttpResponse<T>> sendAsync(final HttpRequest request,
|
||||
final HttpResponse.BodyHandler<T> bodyHandler) {
|
||||
|
||||
if (request.timeout().isEmpty()) {
|
||||
request = HttpRequest.newBuilder(request, (_, _) -> true)
|
||||
.timeout(defaultRequestTimeout)
|
||||
.build();
|
||||
}
|
||||
|
||||
final Supplier<CompletionStage<HttpResponse<T>>> asyncRequestSupplier =
|
||||
sendAsync(httpClient(), request, bodyHandler);
|
||||
() -> httpClient().sendAsync(requestWithTimeout(request, defaultRequestTimeout), bodyHandler);
|
||||
|
||||
if (retry != null) {
|
||||
assert retryExecutor != null;
|
||||
@@ -87,10 +103,12 @@ public class FaultTolerantHttpClient {
|
||||
}
|
||||
}
|
||||
|
||||
private <T> Supplier<CompletionStage<HttpResponse<T>>> sendAsync(HttpClient client, HttpRequest request,
|
||||
HttpResponse.BodyHandler<T> bodyHandler) {
|
||||
|
||||
return () -> client.sendAsync(request, bodyHandler);
|
||||
private static HttpRequest requestWithTimeout(final HttpRequest request, final Duration defaultRequestTimeout) {
|
||||
return request.timeout().isPresent()
|
||||
? request
|
||||
: HttpRequest.newBuilder(request, (_, _) -> true)
|
||||
.timeout(defaultRequestTimeout)
|
||||
.build();
|
||||
}
|
||||
|
||||
public static class Builder {
|
||||
@@ -102,7 +120,7 @@ public class FaultTolerantHttpClient {
|
||||
private int numClients = 1;
|
||||
|
||||
private final String name;
|
||||
private Executor executor;
|
||||
private final Executor executor;
|
||||
private KeyStore trustStore;
|
||||
private String securityProtocol = SECURITY_PROTOCOL_TLS_1_2;
|
||||
private String retryConfigurationName;
|
||||
|
||||
+45
@@ -0,0 +1,45 @@
|
||||
/*
|
||||
* Copyright 2026 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.mappers;
|
||||
|
||||
import io.dropwizard.jersey.errors.ErrorMessage;
|
||||
import jakarta.ws.rs.WebApplicationException;
|
||||
import jakarta.ws.rs.core.MediaType;
|
||||
import jakarta.ws.rs.core.Response;
|
||||
import jakarta.ws.rs.ext.ExceptionMapper;
|
||||
import org.whispersystems.textsecuregcm.backup.BackupBadReceiptException;
|
||||
import org.whispersystems.textsecuregcm.backup.BackupException;
|
||||
import org.whispersystems.textsecuregcm.backup.BackupFailedZkAuthenticationException;
|
||||
import org.whispersystems.textsecuregcm.backup.BackupInvalidArgumentException;
|
||||
import org.whispersystems.textsecuregcm.backup.BackupMissingIdCommitmentException;
|
||||
import org.whispersystems.textsecuregcm.backup.BackupNotFoundException;
|
||||
import org.whispersystems.textsecuregcm.backup.BackupPermissionException;
|
||||
import org.whispersystems.textsecuregcm.backup.BackupWrongCredentialTypeException;
|
||||
|
||||
public class BackupExceptionMapper implements ExceptionMapper<BackupException> {
|
||||
|
||||
@Override
|
||||
public Response toResponse(final BackupException exception) {
|
||||
final Response.Status status = (switch (exception) {
|
||||
case BackupNotFoundException _ -> Response.Status.NOT_FOUND;
|
||||
case BackupInvalidArgumentException _, BackupBadReceiptException _ -> Response.Status.BAD_REQUEST;
|
||||
case BackupPermissionException _ -> Response.Status.FORBIDDEN;
|
||||
case BackupMissingIdCommitmentException _ -> Response.Status.CONFLICT;
|
||||
case BackupWrongCredentialTypeException _,
|
||||
BackupFailedZkAuthenticationException _ -> Response.Status.UNAUTHORIZED;
|
||||
default -> Response.Status.INTERNAL_SERVER_ERROR;
|
||||
});
|
||||
|
||||
final WebApplicationException wae =
|
||||
new WebApplicationException(exception.getMessage(), exception, Response.status(status).build());
|
||||
|
||||
return Response
|
||||
.fromResponse(wae.getResponse())
|
||||
.type(MediaType.APPLICATION_JSON_TYPE)
|
||||
.entity(new ErrorMessage(wae.getResponse().getStatus(), wae.getLocalizedMessage())).build();
|
||||
|
||||
}
|
||||
}
|
||||
@@ -13,8 +13,10 @@ import io.micrometer.core.instrument.DistributionSummary;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import io.micrometer.core.instrument.Tag;
|
||||
import io.micrometer.core.instrument.Tags;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
@@ -31,6 +33,7 @@ import org.whispersystems.textsecuregcm.identity.IdentityType;
|
||||
import org.whispersystems.textsecuregcm.identity.ServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
|
||||
import org.whispersystems.textsecuregcm.metrics.UserAgentTagUtil;
|
||||
import org.whispersystems.textsecuregcm.spam.MessageDeliveryListener;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.Device;
|
||||
import org.whispersystems.textsecuregcm.storage.MessagesManager;
|
||||
@@ -52,6 +55,8 @@ public class MessageSender {
|
||||
private final MessagesManager messagesManager;
|
||||
private final PushNotificationManager pushNotificationManager;
|
||||
|
||||
private final List<MessageDeliveryListener> messageDeliveryListeners = new ArrayList<>();
|
||||
|
||||
// Note that these names deliberately reference `MessageController` for metric continuity
|
||||
private static final String REJECT_OVERSIZE_MESSAGE_COUNTER_NAME = name(MessageSender.class, "rejectOversizeMessage");
|
||||
private static final String OVERSIZE_MESSAGE_WARNING_COUNTER_NAME = name(MessageSender.class, "oversizeMessageWarning");
|
||||
@@ -80,6 +85,10 @@ public class MessageSender {
|
||||
this.pushNotificationManager = pushNotificationManager;
|
||||
}
|
||||
|
||||
public void addMessageDeliveryListener(final MessageDeliveryListener messageDeliveryListener) {
|
||||
messageDeliveryListeners.add(messageDeliveryListener);
|
||||
}
|
||||
|
||||
/**
|
||||
* Sends messages to devices associated with the given destination account. If a destination device has a valid push
|
||||
* notification token and does not have an active connection to a Signal server, then this method will also send a
|
||||
@@ -136,6 +145,16 @@ public class MessageSender {
|
||||
.and(platformTag);
|
||||
|
||||
Metrics.counter(SEND_COUNTER_NAME, tags).increment();
|
||||
|
||||
messageDeliveryListeners.forEach(messageDeliveryListener ->
|
||||
messageDeliveryListener.handleMessageDelivered(destination,
|
||||
deviceId,
|
||||
message.getEphemeral(),
|
||||
message.getUrgent(),
|
||||
message.getStory(),
|
||||
!message.hasSourceServiceId(),
|
||||
false,
|
||||
syncMessageSenderDeviceId.isPresent()));
|
||||
});
|
||||
}
|
||||
|
||||
@@ -223,6 +242,16 @@ public class MessageSender {
|
||||
.and(platformTag);
|
||||
|
||||
Metrics.counter(SEND_COUNTER_NAME, tags).increment();
|
||||
|
||||
messageDeliveryListeners.forEach(messageDeliveryListener ->
|
||||
messageDeliveryListener.handleMessageDelivered(account,
|
||||
deviceId,
|
||||
isEphemeral,
|
||||
isUrgent,
|
||||
isStory,
|
||||
true,
|
||||
true,
|
||||
false));
|
||||
})))
|
||||
.thenRun(Util.NOOP);
|
||||
}
|
||||
|
||||
+3
-3
@@ -23,10 +23,10 @@ import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.CompletionException;
|
||||
import java.util.concurrent.Executor;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import javax.annotation.Nullable;
|
||||
import javax.crypto.Mac;
|
||||
import javax.crypto.spec.SecretKeySpec;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.checkerframework.checker.nullness.qual.Nullable;
|
||||
import org.signal.registration.rpc.CheckVerificationCodeRequest;
|
||||
import org.signal.registration.rpc.CreateRegistrationSessionRequest;
|
||||
import org.signal.registration.rpc.GetRegistrationSessionMetadataRequest;
|
||||
@@ -97,8 +97,8 @@ public class RegistrationServiceClient implements Managed {
|
||||
final Phonenumber.PhoneNumber phoneNumber,
|
||||
final String sourceHost,
|
||||
final boolean accountExistsWithPhoneNumber,
|
||||
@javax.annotation.Nullable final String clientMcc,
|
||||
@javax.annotation.Nullable final String clientMnc,
|
||||
@Nullable final String clientMcc,
|
||||
@Nullable final String clientMnc,
|
||||
final Duration timeout) {
|
||||
|
||||
final long e164 = Long.parseLong(
|
||||
|
||||
+3
-1
@@ -7,10 +7,10 @@ package org.whispersystems.textsecuregcm.registration;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import java.time.Instant;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import javax.annotation.Nullable;
|
||||
import org.whispersystems.textsecuregcm.storage.SerializedExpireableJsonDynamoStore;
|
||||
import org.whispersystems.textsecuregcm.telephony.CarrierData;
|
||||
|
||||
/**
|
||||
* Server-internal stored session object. Primarily used by
|
||||
@@ -19,6 +19,7 @@ import org.whispersystems.textsecuregcm.storage.SerializedExpireableJsonDynamoSt
|
||||
* {@link org.whispersystems.textsecuregcm.controllers.RegistrationController}.
|
||||
*
|
||||
* @param pushChallenge the value of a push challenge sent to a client, after it submitted a push token
|
||||
* @param carrierData information about the phone number's carrier if available
|
||||
* @param requestedInformation information requested that a client send to the server
|
||||
* @param submittedInformation information that a client has submitted and that the server has verified
|
||||
* @param smsSenderOverride if present, indicates a sender override argument that should be forwarded to the
|
||||
@@ -36,6 +37,7 @@ import org.whispersystems.textsecuregcm.storage.SerializedExpireableJsonDynamoSt
|
||||
*/
|
||||
public record VerificationSession(
|
||||
@Nullable String pushChallenge,
|
||||
@Nullable CarrierData carrierData,
|
||||
List<Information> requestedInformation,
|
||||
List<Information> submittedInformation,
|
||||
@Nullable String smsSenderOverride,
|
||||
|
||||
+20
@@ -0,0 +1,20 @@
|
||||
/*
|
||||
* Copyright 2026 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.spam;
|
||||
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
|
||||
public interface MessageDeliveryListener {
|
||||
|
||||
void handleMessageDelivered(Account destinationAccount,
|
||||
byte destinationDeviceId,
|
||||
boolean ephemeral,
|
||||
boolean urgent,
|
||||
boolean story,
|
||||
boolean sealedSender,
|
||||
boolean multiRecipient,
|
||||
boolean sync);
|
||||
}
|
||||
@@ -46,6 +46,13 @@ public interface SpamFilter extends Managed {
|
||||
*/
|
||||
Collection<ConfiguredCommand<WhisperServerConfiguration>> getCommands();
|
||||
|
||||
/**
|
||||
* Returns a message delivery listener controlled by the spam filter.
|
||||
*
|
||||
* @return a message delivery listener controlled by the spam filter
|
||||
*/
|
||||
MessageDeliveryListener getMessageDeliveryListener();
|
||||
|
||||
/**
|
||||
* Return a reported message listener controlled by the spam filter. Listeners will be registered with the
|
||||
* {@link org.whispersystems.textsecuregcm.storage.ReportMessageManager}.
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
/*
|
||||
* Copyright 2026 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.telephony;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
/// Line type and home network information for a specific phone number.
|
||||
///
|
||||
/// @param carrierName the name of the network operator for the specified phone number
|
||||
/// @param lineType the line type for the specified phone number
|
||||
/// @param mcc the mobile country code (MCC) of the phone number's home network if known; may be empty if the phone
|
||||
/// number is not a mobile number
|
||||
/// @param mnc the mobile network code (MNC) of the phone number's home network if known; may be empty if the phone
|
||||
/// number is not a mobile number
|
||||
public record CarrierData(String carrierName, LineType lineType, Optional<String> mcc, Optional<String> mnc) {
|
||||
|
||||
public enum LineType {
|
||||
MOBILE,
|
||||
LANDLINE,
|
||||
FIXED_VOIP,
|
||||
NON_FIXED_VOIP,
|
||||
OTHER,
|
||||
UNKNOWN
|
||||
}
|
||||
}
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
/*
|
||||
* Copyright 2026 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.telephony;
|
||||
|
||||
/// Indicates that a request for carrier data failed permanently (e.g. it was affirmatively rejected by the provider)
|
||||
/// and should not be retried without modification.
|
||||
public class CarrierDataException extends Exception {
|
||||
|
||||
public CarrierDataException(final String message) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
+30
@@ -0,0 +1,30 @@
|
||||
/*
|
||||
* Copyright 2026 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.telephony;
|
||||
|
||||
import com.google.i18n.phonenumbers.Phonenumber;
|
||||
import java.io.IOException;
|
||||
import java.time.Duration;
|
||||
import java.util.Optional;
|
||||
|
||||
/// A carrier data provider returns line type and home network information about a specific phone number. Carrier data
|
||||
/// providers may cache results and return cached results if they are newer than a given maximum age.
|
||||
public interface CarrierDataProvider {
|
||||
|
||||
/// Retrieves carrier data for a given phone number.
|
||||
///
|
||||
/// @param phoneNumber the phone number for which to retrieve line type and home network information
|
||||
/// @param maxCachedAge the maximum age of a cached response to return; providers must attempt to fetch fresh data if
|
||||
/// cached data is older than the given maximum age, and may choose to fetch fresh data under any circumstances
|
||||
///
|
||||
/// @return line type and home network information for the given phone number if available or empty if this provider
|
||||
/// could not find information for the given phone number
|
||||
///
|
||||
/// @throws IOException if the provider could not be reached due to a network problem of any kind
|
||||
/// @throws CarrierDataException if the request failed and should not be retried without modification
|
||||
Optional<CarrierData> lookupCarrierData(Phonenumber.PhoneNumber phoneNumber, Duration maxCachedAge)
|
||||
throws IOException, CarrierDataException;
|
||||
}
|
||||
+184
@@ -0,0 +1,184 @@
|
||||
/*
|
||||
* Copyright 2026 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.telephony.hlrlookup;
|
||||
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import com.google.i18n.phonenumbers.Phonenumber;
|
||||
import java.io.IOException;
|
||||
import java.net.URI;
|
||||
import java.net.http.HttpRequest;
|
||||
import java.net.http.HttpResponse;
|
||||
import java.time.Duration;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.Executor;
|
||||
import java.util.concurrent.ScheduledExecutorService;
|
||||
import javax.annotation.Nullable;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.whispersystems.textsecuregcm.http.FaultTolerantHttpClient;
|
||||
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
|
||||
import org.whispersystems.textsecuregcm.telephony.CarrierData;
|
||||
import org.whispersystems.textsecuregcm.telephony.CarrierDataException;
|
||||
import org.whispersystems.textsecuregcm.telephony.CarrierDataProvider;
|
||||
import org.whispersystems.textsecuregcm.util.SystemMapper;
|
||||
|
||||
/// A carrier data provider that uses [HLR Lookup](https://www.hlrlookup.com/) as its data source.
|
||||
public class HlrLookupCarrierDataProvider implements CarrierDataProvider {
|
||||
|
||||
private final String apiKey;
|
||||
private final String apiSecret;
|
||||
|
||||
private final FaultTolerantHttpClient httpClient;
|
||||
private final URI lookupUri;
|
||||
|
||||
private static final URI HLR_LOOKUP_URI = URI.create("https://api.hlrlookup.com/apiv2/hlr");
|
||||
|
||||
private static final ObjectMapper OBJECT_MAPPER = SystemMapper.jsonMapper();
|
||||
|
||||
private static final String REQUEST_COUNTER_NAME = MetricsUtil.name(HlrLookupCarrierDataProvider.class, "request");
|
||||
|
||||
public HlrLookupCarrierDataProvider(final String apiKey,
|
||||
final String apiSecret,
|
||||
final Executor httpRequestExecutor,
|
||||
@Nullable final String circuitBreakerConfigurationName,
|
||||
@Nullable final String retryConfigurationName,
|
||||
final ScheduledExecutorService retryExecutor) {
|
||||
|
||||
this(apiKey,
|
||||
apiSecret,
|
||||
FaultTolerantHttpClient.newBuilder("hlr-lookup", httpRequestExecutor)
|
||||
.withCircuitBreaker(circuitBreakerConfigurationName)
|
||||
.withRetry(retryConfigurationName, retryExecutor)
|
||||
.build(),
|
||||
HLR_LOOKUP_URI);
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
HlrLookupCarrierDataProvider(final String apiKey,
|
||||
final String apiSecret,
|
||||
final FaultTolerantHttpClient httpClient,
|
||||
final URI lookupUri) {
|
||||
|
||||
this.apiKey = apiKey;
|
||||
this.apiSecret = apiSecret;
|
||||
this.httpClient = httpClient;
|
||||
this.lookupUri = lookupUri;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Optional<CarrierData> lookupCarrierData(final Phonenumber.PhoneNumber phoneNumber,
|
||||
final Duration maxCachedAge) throws IOException, CarrierDataException {
|
||||
|
||||
final HlrLookupResponse response;
|
||||
|
||||
try {
|
||||
final String requestJson = OBJECT_MAPPER.writeValueAsString(
|
||||
new HlrLookupRequest(apiKey, apiSecret,
|
||||
List.of(TelephoneNumberRequest.forPhoneNumber(phoneNumber, maxCachedAge))));
|
||||
|
||||
final HttpRequest request = HttpRequest
|
||||
.newBuilder(lookupUri)
|
||||
.POST(HttpRequest.BodyPublishers.ofString(requestJson))
|
||||
.header("Content-Type", "application/json")
|
||||
.build();
|
||||
|
||||
final HttpResponse<String> httpResponse = httpClient.send(request, HttpResponse.BodyHandlers.ofString());
|
||||
|
||||
if (httpResponse.statusCode() != 200) {
|
||||
// We may or may not have helpful data in the response body
|
||||
try {
|
||||
final HlrLookupResponse hlrLookupResponse = parseResponse(httpResponse.body());
|
||||
|
||||
if (StringUtils.isNotBlank(hlrLookupResponse.error()) || StringUtils.isNotBlank(
|
||||
hlrLookupResponse.message())) {
|
||||
throw new CarrierDataException(
|
||||
"Received a non-success status code (%d): error = %s; message = %s".formatted(
|
||||
httpResponse.statusCode(), hlrLookupResponse.error(), hlrLookupResponse.message()));
|
||||
}
|
||||
} catch (final JsonProcessingException _) {
|
||||
// We couldn't parse the body, so just move on with the default error message
|
||||
}
|
||||
|
||||
throw new CarrierDataException("Received a non-success status code (%d)".formatted(httpResponse.statusCode()));
|
||||
}
|
||||
|
||||
response = parseResponse(httpResponse.body());
|
||||
|
||||
Metrics.counter(REQUEST_COUNTER_NAME, "status", String.valueOf(httpResponse.statusCode()))
|
||||
.increment();
|
||||
} catch (final IOException | CarrierDataException e) {
|
||||
Metrics.counter(REQUEST_COUNTER_NAME, "exception", e.getClass().getSimpleName())
|
||||
.increment();
|
||||
|
||||
throw e;
|
||||
}
|
||||
|
||||
if (response.results() == null || response.results().isEmpty()) {
|
||||
throw new CarrierDataException("No error reported, but no results provided");
|
||||
}
|
||||
|
||||
final HlrLookupResult result = response.results().getFirst();
|
||||
|
||||
if (!result.error().equals("NONE")) {
|
||||
throw new CarrierDataException("Received a per-number error: " + result.error());
|
||||
}
|
||||
|
||||
return getNetworkDetails(result)
|
||||
.map(networkDetails -> new CarrierData(
|
||||
networkDetails.name(),
|
||||
lineType(result.telephoneNumberType()),
|
||||
mccFromMccMnc(networkDetails.mccmnc()),
|
||||
mncFromMccMnc(networkDetails.mccmnc())));
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
static Optional<String> mccFromMccMnc(@Nullable final String mccMnc) {
|
||||
// MCCs are always 3 digits
|
||||
return Optional.ofNullable(StringUtils.stripToNull(mccMnc))
|
||||
.map(trimmedMccMnc -> trimmedMccMnc.substring(0, 3));
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
static Optional<String> mncFromMccMnc(@Nullable final String mccMnc) {
|
||||
// MNCs may be 2 or 3 digits, but always come after a 3-digit MCC
|
||||
return Optional.ofNullable(StringUtils.stripToNull(mccMnc))
|
||||
.map(trimmedMccMnc -> trimmedMccMnc.substring(3));
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
static CarrierData.LineType lineType(@Nullable final String telephoneNumberType) {
|
||||
if (telephoneNumberType == null) {
|
||||
return CarrierData.LineType.UNKNOWN;
|
||||
}
|
||||
|
||||
return switch (telephoneNumberType) {
|
||||
case "MOBILE" -> CarrierData.LineType.MOBILE;
|
||||
case "LANDLINE", "MOBILE_OR_LANDLINE" -> CarrierData.LineType.LANDLINE;
|
||||
case "VOIP" -> CarrierData.LineType.NON_FIXED_VOIP;
|
||||
case "UNKNOWN" -> CarrierData.LineType.UNKNOWN;
|
||||
default -> CarrierData.LineType.OTHER;
|
||||
};
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
static Optional<NetworkDetails> getNetworkDetails(final HlrLookupResult hlrLookupResult) {
|
||||
if (hlrLookupResult.currentNetwork().equals("AVAILABLE")) {
|
||||
return Optional.of(hlrLookupResult.currentNetworkDetails());
|
||||
} else if (hlrLookupResult.originalNetwork().equals("AVAILABLE")) {
|
||||
return Optional.of(hlrLookupResult.originalNetworkDetails());
|
||||
}
|
||||
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
static HlrLookupResponse parseResponse(final String responseJson) throws JsonProcessingException {
|
||||
return OBJECT_MAPPER.readValue(responseJson, HlrLookupResponse.class);
|
||||
}
|
||||
}
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
/*
|
||||
* Copyright 2026 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.telephony.hlrlookup;
|
||||
|
||||
import com.fasterxml.jackson.databind.PropertyNamingStrategies;
|
||||
import com.fasterxml.jackson.databind.annotation.JsonNaming;
|
||||
import java.util.List;
|
||||
|
||||
@JsonNaming(PropertyNamingStrategies.SnakeCaseStrategy.class)
|
||||
record HlrLookupRequest(String apiKey, String apiSecret, List<TelephoneNumberRequest> requests) {
|
||||
}
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
/*
|
||||
* Copyright 2026 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.telephony.hlrlookup;
|
||||
|
||||
import javax.annotation.Nullable;
|
||||
import java.util.List;
|
||||
|
||||
record HlrLookupResponse(@Nullable List<HlrLookupResult> results,
|
||||
@Nullable String error,
|
||||
@Nullable String message) {
|
||||
}
|
||||
+18
@@ -0,0 +1,18 @@
|
||||
/*
|
||||
* Copyright 2026 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.telephony.hlrlookup;
|
||||
|
||||
import com.fasterxml.jackson.databind.PropertyNamingStrategies;
|
||||
import com.fasterxml.jackson.databind.annotation.JsonNaming;
|
||||
|
||||
@JsonNaming(PropertyNamingStrategies.SnakeCaseStrategy.class)
|
||||
record HlrLookupResult(String error,
|
||||
String originalNetwork,
|
||||
NetworkDetails originalNetworkDetails,
|
||||
String currentNetwork,
|
||||
NetworkDetails currentNetworkDetails,
|
||||
String telephoneNumberType) {
|
||||
}
|
||||
+18
@@ -0,0 +1,18 @@
|
||||
/*
|
||||
* Copyright 2026 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.telephony.hlrlookup;
|
||||
|
||||
import com.fasterxml.jackson.databind.PropertyNamingStrategies;
|
||||
import com.fasterxml.jackson.databind.annotation.JsonNaming;
|
||||
|
||||
@JsonNaming(PropertyNamingStrategies.SnakeCaseStrategy.class)
|
||||
record NetworkDetails(String name,
|
||||
String mccmnc,
|
||||
String countryName,
|
||||
String countryIso3,
|
||||
String area,
|
||||
String countryPrefix) {
|
||||
}
|
||||
+31
@@ -0,0 +1,31 @@
|
||||
/*
|
||||
* Copyright 2026 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.telephony.hlrlookup;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import com.fasterxml.jackson.databind.PropertyNamingStrategies;
|
||||
import com.fasterxml.jackson.databind.annotation.JsonNaming;
|
||||
import com.google.i18n.phonenumbers.PhoneNumberUtil;
|
||||
import com.google.i18n.phonenumbers.Phonenumber;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import javax.annotation.Nullable;
|
||||
import java.time.Duration;
|
||||
|
||||
@JsonNaming(PropertyNamingStrategies.SnakeCaseStrategy.class)
|
||||
record TelephoneNumberRequest(String telephoneNumber,
|
||||
@Nullable Integer cacheDaysGlobal,
|
||||
@Nullable Integer cacheDaysPrivate,
|
||||
@JsonProperty("save_to_cache") String saveToGlobalCache) {
|
||||
|
||||
static TelephoneNumberRequest forPhoneNumber(final Phonenumber.PhoneNumber phoneNumber, final Duration maxCachedAge) {
|
||||
|
||||
return new TelephoneNumberRequest(
|
||||
StringUtils.stripStart(PhoneNumberUtil.getInstance().format(phoneNumber, PhoneNumberUtil.PhoneNumberFormat.E164), "+"),
|
||||
(int) maxCachedAge.toDays(),
|
||||
(int) maxCachedAge.toDays(),
|
||||
"NO");
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,7 @@ package org.whispersystems.textsecuregcm.util;
|
||||
|
||||
import java.util.concurrent.CompletionException;
|
||||
import java.util.function.Function;
|
||||
import java.util.function.Supplier;
|
||||
|
||||
public final class ExceptionUtils {
|
||||
|
||||
@@ -81,4 +82,49 @@ public final class ExceptionUtils {
|
||||
throw wrap(fn.apply(e));
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Runs the supplier, throwing a checked exception if the supplier throws an exception that unwraps to the provided type
|
||||
*
|
||||
* @param exType The exception type to check for
|
||||
* @param supplier A supplier that produces a T
|
||||
* @return The result of the supplier
|
||||
* @param <T> The supplier type
|
||||
* @param <E> The checked exception type
|
||||
* @throws E If the supplier throws E or a type that {@link #unwrap}s to E
|
||||
*/
|
||||
public static <T, E extends Throwable> T unwrapSupply(Class<E> exType, Supplier<T> supplier) throws E {
|
||||
try {
|
||||
return supplier.get();
|
||||
} catch (RuntimeException e) {
|
||||
final Throwable ex = unwrap(e);
|
||||
if (exType.isInstance(ex)) {
|
||||
throw exType.cast(ex);
|
||||
}
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Runs the supplier, throwing a checked exception if the supplier throws an exception that unwraps to the provided type
|
||||
*
|
||||
* @param exType The exception type to check for
|
||||
* @param supplier A supplier that produces a T
|
||||
* @param marshal A function that maps from the thrown type to another exception type
|
||||
* @return The result of the supplier
|
||||
* @param <T> The supplier type
|
||||
* @param <E> The checked exception type that may be thrown from supplier
|
||||
* @throws F If the supplier throws E or a type that {@link #unwrap}s to E
|
||||
*/
|
||||
public static <T, E extends Throwable, F extends Throwable> T unwrapSupply(Class<E> exType, Supplier<T> supplier, Function<E, F> marshal) throws F {
|
||||
try {
|
||||
return supplier.get();
|
||||
} catch (RuntimeException e) {
|
||||
final Throwable ex = unwrap(e);
|
||||
if (exType.isInstance(ex)) {
|
||||
throw marshal.apply(exType.cast(ex));
|
||||
}
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -47,12 +47,12 @@ message CreateRegistrationSessionRequest {
|
||||
string rate_limit_collation_key = 3;
|
||||
|
||||
/**
|
||||
* The MCC for the given `e164` as reported by the client.
|
||||
* The MCC for the given `e164` as reported by a number lookup service.
|
||||
*/
|
||||
string mcc = 4;
|
||||
|
||||
/**
|
||||
* The MNC for the given `e164` as reported by the client.
|
||||
* The MNC for the given `e164` as reported by a number lookup service.
|
||||
*/
|
||||
string mnc = 5;
|
||||
}
|
||||
|
||||
@@ -58,12 +58,18 @@ message ServerCertificate {
|
||||
|
||||
message SenderCertificate {
|
||||
message Certificate {
|
||||
optional string sender = 1;
|
||||
optional string sender_uuid = 6;
|
||||
reserved 6;
|
||||
|
||||
optional string sender_e164 = 1;
|
||||
optional bytes sender_uuid_= 7;
|
||||
optional uint32 sender_device = 2;
|
||||
optional fixed64 expires = 3;
|
||||
optional bytes identity_key = 4;
|
||||
optional ServerCertificate signer = 5;
|
||||
oneof signer {
|
||||
ServerCertificate signer_certificate = 5;
|
||||
uint32 signer_id = 8;
|
||||
}
|
||||
// next: 9
|
||||
}
|
||||
|
||||
optional bytes certificate = 1;
|
||||
|
||||
@@ -5,125 +5,71 @@ option java_multiple_files = true;
|
||||
package org.signal.chat.account;
|
||||
|
||||
import "org/signal/chat/common.proto";
|
||||
import "org/signal/chat/errors.proto";
|
||||
|
||||
/**
|
||||
* Provides methods for working with Signal accounts.
|
||||
*/
|
||||
// Provides methods for working with Signal accounts.
|
||||
service Accounts {
|
||||
/**
|
||||
* Returns basic identifiers for the authenticated account.
|
||||
*/
|
||||
// Returns basic identifiers for the authenticated account.
|
||||
rpc GetAccountIdentity(GetAccountIdentityRequest) returns (GetAccountIdentityResponse) {}
|
||||
|
||||
/**
|
||||
* Deletes the authenticated account, purging all associated data in the
|
||||
* process.
|
||||
*/
|
||||
// Deletes the authenticated account, purging all associated data in the
|
||||
// process.
|
||||
rpc DeleteAccount(DeleteAccountRequest) returns (DeleteAccountResponse) {}
|
||||
|
||||
/**
|
||||
* Sets the registration lock secret for the authenticated account. To remove
|
||||
* a registration lock, please use `ClearRegistrationLock`.
|
||||
*/
|
||||
// Sets the registration lock secret for the authenticated account. To remove
|
||||
// a registration lock, please use `ClearRegistrationLock`.
|
||||
rpc SetRegistrationLock(SetRegistrationLockRequest) returns (SetRegistrationLockResponse) {}
|
||||
|
||||
/**
|
||||
* Removes any registration lock credentials from the authenticated account.
|
||||
*/
|
||||
// Removes any registration lock credentials from the authenticated account.
|
||||
rpc ClearRegistrationLock(ClearRegistrationLockRequest) returns (ClearRegistrationLockResponse) {}
|
||||
|
||||
/**
|
||||
* Attempts to reserve one of multiple given username hashes. Reserved
|
||||
* usernames may be claimed later via `ConfirmUsernameHash`. This RPC may
|
||||
* fail with a `RESOURCE_EXHAUSTED` status if a rate limit for modifying
|
||||
* usernames has been exceeded, in which case a `retry-after` header
|
||||
* containing an ISO 8601 duration string will be present in the response
|
||||
* trailers.
|
||||
*/
|
||||
// Attempts to reserve one of multiple given username hashes. Reserved
|
||||
// usernames may be claimed later via `ConfirmUsernameHash`.
|
||||
rpc ReserveUsernameHash(ReserveUsernameHashRequest) returns (ReserveUsernameHashResponse) {}
|
||||
|
||||
/**
|
||||
* Sets the username hash/encrypted username to a previously-reserved value
|
||||
* (see `ReserveUsernameHash`). This RPC may fail with a status of
|
||||
* `FAILED_PRECONDITION` if no reserved username hash was found for the given
|
||||
* account or `NOT_FOUND` if the reservation has lapsed and been claimed by
|
||||
* another caller. It may also fail with a `RESOURCE_EXHAUSTED` if a rate
|
||||
* limit for modifying usernames has been exceeded, in which case a
|
||||
* `retry-after` header containing an ISO 8601 duration string will be present
|
||||
* in the response trailers.
|
||||
*/
|
||||
// Sets the username hash/encrypted username to a previously-reserved value
|
||||
// (see `ReserveUsernameHash`).
|
||||
rpc ConfirmUsernameHash(ConfirmUsernameHashRequest) returns (ConfirmUsernameHashResponse) {}
|
||||
|
||||
/**
|
||||
* Clears the current username hash, ciphertext, and link for the
|
||||
* authenticated user.
|
||||
*/
|
||||
// Clears the current username hash, ciphertext, and link for the
|
||||
// authenticated user.
|
||||
rpc DeleteUsernameHash(DeleteUsernameHashRequest) returns (DeleteUsernameHashResponse) {}
|
||||
|
||||
/**
|
||||
* Associates the given username ciphertext with the account, replacing any
|
||||
* previously stored ciphertext. A new link handle will optionally be created,
|
||||
* and the link handle to use will be returned in any event.
|
||||
*
|
||||
* This RPC may fail with a status of `FAILED_PRECONDITION` if the
|
||||
* authenticated account does not have a username. It may also fail with
|
||||
* `RESOURCE_EXHAUSTED` if a rate limit for modifying username links has been
|
||||
* exceeded, in which case a `retry-after` header containing an ISO 8601
|
||||
* duration string will be present in the response trailers.
|
||||
*/
|
||||
// Associates the given username ciphertext with the account, replacing any
|
||||
// previously stored ciphertext. A new link handle will optionally be created,
|
||||
// and the link handle to use will be returned in any event.
|
||||
rpc SetUsernameLink(SetUsernameLinkRequest) returns (SetUsernameLinkResponse) {}
|
||||
|
||||
/**
|
||||
* Clears any username link associated with the authenticated account. This
|
||||
* RPC may fail with `RESOURCE_EXHAUSTED` if a rate limit for modifying
|
||||
* username links has been exceeded, in which case a `retry-after` header
|
||||
* containing an ISO 8601 duration string will be present in the response
|
||||
* trailers.
|
||||
*/
|
||||
// Clears any username link associated with the authenticated account.
|
||||
rpc DeleteUsernameLink(DeleteUsernameLinkRequest) returns (DeleteUsernameLinkResponse) {}
|
||||
|
||||
/**
|
||||
* Configures "unidentified access" keys and preferences for the authenticated
|
||||
* account. Other users permitted to interact with this account anonymously
|
||||
* may take actions like fetching pre-keys and profiles for this account or
|
||||
* sending sealed-sender messages without providing identifying credentials.
|
||||
*/
|
||||
// Configures "unidentified access" keys and preferences for the authenticated
|
||||
// account. Other users permitted to interact with this account anonymously
|
||||
// may take actions like fetching pre-keys and profiles for this account or
|
||||
// sending sealed-sender messages without providing identifying credentials.
|
||||
rpc ConfigureUnidentifiedAccess(ConfigureUnidentifiedAccessRequest) returns (ConfigureUnidentifiedAccessResponse) {}
|
||||
|
||||
/**
|
||||
* Sets whether the authenticated account may be discovered by phone number
|
||||
* via the Contact Discovery Service (CDS).
|
||||
*/
|
||||
// Sets whether the authenticated account may be discovered by phone number
|
||||
// via the Contact Discovery Service (CDS).
|
||||
rpc SetDiscoverableByPhoneNumber(SetDiscoverableByPhoneNumberRequest) returns (SetDiscoverableByPhoneNumberResponse) {}
|
||||
|
||||
/**
|
||||
* Sets the registration recovery password for the authenticated account.
|
||||
*/
|
||||
// Sets the registration recovery password for the authenticated account.
|
||||
rpc SetRegistrationRecoveryPassword(SetRegistrationRecoveryPasswordRequest) returns (SetRegistrationRecoveryPasswordResponse) {}
|
||||
}
|
||||
|
||||
/**
|
||||
* Provides methods for looking up Signal accounts. Callers must not provide
|
||||
* identifying credentials when calling methods in this service.
|
||||
*/
|
||||
// Provides methods for looking up Signal accounts. Callers must not provide
|
||||
// identifying credentials when calling methods in this service.
|
||||
service AccountsAnonymous {
|
||||
/**
|
||||
* Checks whether an account with the given service identifier exists.
|
||||
*/
|
||||
// Checks whether an account with the given service identifier exists.
|
||||
rpc CheckAccountExistence(CheckAccountExistenceRequest) returns (CheckAccountExistenceResponse) {}
|
||||
|
||||
/**
|
||||
* Finds the service identifier of the account associated with the given
|
||||
* username hash. This method will return a `NOT_FOUND` status if no account
|
||||
* was found for the given username hash.
|
||||
*/
|
||||
// Finds the service identifier of the account associated with the given
|
||||
// username hash.
|
||||
rpc LookupUsernameHash(LookupUsernameHashRequest) returns (LookupUsernameHashResponse) {}
|
||||
|
||||
/**
|
||||
* Finds the encrypted username identified by a given username link handle.
|
||||
* This method will return a `NOT_FOUND` status if no username was found for
|
||||
* the given link handle.
|
||||
*/
|
||||
// Finds the encrypted username identified by a given username link handle.
|
||||
// This method will return a `NOT_FOUND` status if no username was found for
|
||||
// the given link handle.
|
||||
rpc LookupUsernameLink(LookupUsernameLinkRequest) returns (LookupUsernameLinkResponse) {}
|
||||
}
|
||||
|
||||
@@ -131,9 +77,7 @@ message GetAccountIdentityRequest {
|
||||
}
|
||||
|
||||
message GetAccountIdentityResponse {
|
||||
/**
|
||||
* A set of account identifiers for the authenticated account.
|
||||
*/
|
||||
// A set of account identifiers for the authenticated account.
|
||||
common.AccountIdentifiers account_identifiers = 1;
|
||||
}
|
||||
|
||||
@@ -144,9 +88,7 @@ message DeleteAccountResponse {
|
||||
}
|
||||
|
||||
message SetRegistrationLockRequest {
|
||||
/**
|
||||
* The new registration lock secret for the authenticated account.
|
||||
*/
|
||||
// The new registration lock secret for the authenticated account.
|
||||
bytes registration_lock = 1;
|
||||
}
|
||||
|
||||
@@ -160,69 +102,56 @@ message ClearRegistrationLockResponse {
|
||||
}
|
||||
|
||||
message ReserveUsernameHashRequest {
|
||||
/**
|
||||
* A prioritized list of username hashes to attempt to reserve.
|
||||
*/
|
||||
// A prioritized list of username hashes to attempt to reserve.
|
||||
repeated bytes username_hashes = 1;
|
||||
}
|
||||
|
||||
message UsernameNotAvailable {}
|
||||
|
||||
message ReserveUsernameHashResponse {
|
||||
oneof response {
|
||||
/**
|
||||
* The first username hash that was available (and actually reserved).
|
||||
*/
|
||||
// The first username hash that was available (and actually reserved).
|
||||
bytes username_hash = 1;
|
||||
|
||||
/**
|
||||
* An error indicating why a username hash could not be reserved.
|
||||
*/
|
||||
ReserveUsernameHashError error = 2;
|
||||
// Indicates that, of all of the candidate hashes provided, none were
|
||||
// available. Callers may generate a new set of hashes and and retry.
|
||||
UsernameNotAvailable username_not_available = 2;
|
||||
}
|
||||
}
|
||||
|
||||
message ReserveUsernameHashError {
|
||||
ReserveUsernameHashErrorType error_type = 1;
|
||||
}
|
||||
|
||||
enum ReserveUsernameHashErrorType {
|
||||
RESERVE_USERNAME_HASH_ERROR_TYPE_UNSPECIFIED = 0;
|
||||
|
||||
/**
|
||||
* Indicates that, of all of the candidate hashes provided, none were
|
||||
* available. Callers may generate a new set of hashes and and retry.
|
||||
*/
|
||||
RESERVE_USERNAME_HASH_ERROR_TYPE_NO_HASHES_AVAILABLE = 1;
|
||||
}
|
||||
|
||||
message ConfirmUsernameHashRequest {
|
||||
/**
|
||||
* The username hash to claim for the authenticated account.
|
||||
*/
|
||||
// The username hash to claim for the authenticated account.
|
||||
bytes username_hash = 1;
|
||||
|
||||
/**
|
||||
* A zero-knowledge proof that the given username hash was generated by the
|
||||
* Signal username algorithm.
|
||||
*/
|
||||
// A zero-knowledge proof that the given username hash was generated by the
|
||||
// Signal username algorithm.
|
||||
bytes zk_proof = 2;
|
||||
|
||||
/**
|
||||
* The ciphertext of the chosen username for use in public-facing contexts
|
||||
* (e.g. links and QR codes).
|
||||
*/
|
||||
// The ciphertext of the chosen username for use in public-facing contexts
|
||||
// (e.g. links and QR codes).
|
||||
bytes username_ciphertext = 3;
|
||||
}
|
||||
|
||||
message ConfirmUsernameHashResponse {
|
||||
/**
|
||||
* The newly-confirmed username hash.
|
||||
*/
|
||||
bytes username_hash = 1;
|
||||
message ConfirmedUsernameHash {
|
||||
// The newly-confirmed username hash.
|
||||
bytes username_hash = 1;
|
||||
|
||||
/**
|
||||
* The server-generated username link handle for the newly-confirmed username.
|
||||
*/
|
||||
bytes username_link_handle = 2;
|
||||
// The server-generated username link handle for the newly-confirmed username.
|
||||
bytes username_link_handle = 2;
|
||||
}
|
||||
|
||||
oneof response {
|
||||
// The details of the successfully confirmed username.
|
||||
ConfirmedUsernameHash confirmed_username_hash = 1;
|
||||
|
||||
// The provided hash was not reserved for the account.
|
||||
errors.FailedPrecondition reservation_not_found = 2;
|
||||
|
||||
// The reservation has lapsed and the requested username has been claimed by
|
||||
// another caller.
|
||||
UsernameNotAvailable username_not_available = 3;
|
||||
}
|
||||
}
|
||||
|
||||
message DeleteUsernameHashRequest {
|
||||
@@ -232,24 +161,25 @@ message DeleteUsernameHashResponse {
|
||||
}
|
||||
|
||||
message SetUsernameLinkRequest {
|
||||
/**
|
||||
* The username ciphertext for which to generate a new link handle.
|
||||
*/
|
||||
// The username ciphertext for which to generate a new link handle.
|
||||
bytes username_ciphertext = 1;
|
||||
|
||||
/**
|
||||
* If true and the account already had an encrypted username stored, the
|
||||
* existing link handle will be reused. Otherwise a new link handle will be
|
||||
* created.
|
||||
*/
|
||||
// If true and the account already had an encrypted username stored, the
|
||||
// existing link handle will be reused. Otherwise a new link handle will be
|
||||
// created.
|
||||
bool keep_link_handle = 2;
|
||||
}
|
||||
|
||||
|
||||
message SetUsernameLinkResponse {
|
||||
/**
|
||||
* A new link handle for the given username ciphertext.
|
||||
*/
|
||||
bytes username_link_handle = 1;
|
||||
oneof response {
|
||||
// A new link handle for the given username ciphertext.
|
||||
bytes username_link_handle = 1;
|
||||
|
||||
// The authenticated account did not have a username set.
|
||||
errors.FailedPrecondition no_username_set = 2;
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
message DeleteUsernameLinkRequest {
|
||||
@@ -259,19 +189,15 @@ message DeleteUsernameLinkResponse {
|
||||
}
|
||||
|
||||
message ConfigureUnidentifiedAccessRequest {
|
||||
/**
|
||||
* The key that other users must provide to interact with this account
|
||||
* anonymously (i.e. to retrieve keys or profiles or to send messages) unless
|
||||
* unrestricted unidentified access is permitted. Must be present if
|
||||
* unrestricted unidentified access is not allowed.
|
||||
*/
|
||||
// The key that other users must provide to interact with this account
|
||||
// anonymously (i.e. to retrieve keys or profiles or to send messages) unless
|
||||
// unrestricted unidentified access is permitted. Must be present if
|
||||
// unrestricted unidentified access is not allowed.
|
||||
bytes unidentified_access_key = 1;
|
||||
|
||||
/**
|
||||
* If `true`, any user may interact with this account anonymously without
|
||||
* providing an unidentified access key. Otherwise, users must provide the
|
||||
* given unidentified access key to interact with this account anonymously.
|
||||
*/
|
||||
// If `true`, any user may interact with this account anonymously without
|
||||
// providing an unidentified access key. Otherwise, users must provide the
|
||||
// given unidentified access key to interact with this account anonymously.
|
||||
bool allow_unrestricted_unidentified_access = 2;
|
||||
}
|
||||
|
||||
@@ -279,11 +205,9 @@ message ConfigureUnidentifiedAccessResponse {
|
||||
}
|
||||
|
||||
message SetDiscoverableByPhoneNumberRequest {
|
||||
/**
|
||||
* If true, the authenticated account may be discovered by phone number via
|
||||
* the Contact Discovery Service (CDS). Otherwise, other users must discover
|
||||
* this account by other means (i.e. by username).
|
||||
*/
|
||||
// If true, the authenticated account may be discovered by phone number via
|
||||
// the Contact Discovery Service (CDS). Otherwise, other users must discover
|
||||
// this account by other means (i.e. by username).
|
||||
bool discoverable_by_phone_number = 1;
|
||||
}
|
||||
|
||||
@@ -291,9 +215,7 @@ message SetDiscoverableByPhoneNumberResponse {
|
||||
}
|
||||
|
||||
message SetRegistrationRecoveryPasswordRequest {
|
||||
/**
|
||||
* The new registration recovery password for the authenticated account.
|
||||
*/
|
||||
// The new registration recovery password for the authenticated account.
|
||||
bytes registration_recovery_password = 1;
|
||||
}
|
||||
|
||||
@@ -301,45 +223,44 @@ message SetRegistrationRecoveryPasswordResponse {
|
||||
}
|
||||
|
||||
message CheckAccountExistenceRequest {
|
||||
/**
|
||||
* The service identifier of an account that may or may not exist.
|
||||
*/
|
||||
// The service identifier of an account that may or may not exist.
|
||||
common.ServiceIdentifier service_identifier = 1;
|
||||
}
|
||||
|
||||
message CheckAccountExistenceResponse {
|
||||
/**
|
||||
* True if an account exists with the given service identifier or false if no
|
||||
* account was found.
|
||||
*/
|
||||
// True if an account exists with the given service identifier or false if no
|
||||
// account was found.
|
||||
bool account_exists = 1;
|
||||
}
|
||||
|
||||
message LookupUsernameHashRequest {
|
||||
/**
|
||||
* A 32-byte username hash for which to find an account.
|
||||
*/
|
||||
// A 32-byte username hash for which to find an account.
|
||||
bytes username_hash = 1;
|
||||
}
|
||||
|
||||
message LookupUsernameHashResponse {
|
||||
/**
|
||||
* The service identifier associated with a given username hash.
|
||||
*/
|
||||
common.ServiceIdentifier service_identifier = 1;
|
||||
oneof response {
|
||||
// The service identifier associated with the provided username hash.
|
||||
common.ServiceIdentifier service_identifier = 1;
|
||||
|
||||
// No account was found for the provided username hash.
|
||||
errors.NotFound not_found = 2;
|
||||
}
|
||||
}
|
||||
|
||||
message LookupUsernameLinkRequest {
|
||||
/**
|
||||
* The link handle for which to find an encrypted username. Link handles are
|
||||
* 16-byte representations of UUIDs.
|
||||
*/
|
||||
// The link handle for which to find an encrypted username. Link handles are
|
||||
// 16-byte representations of UUIDs.
|
||||
bytes username_link_handle = 1;
|
||||
}
|
||||
|
||||
message LookupUsernameLinkResponse {
|
||||
/**
|
||||
* The ciphertext of the username identified by the given link handle.
|
||||
*/
|
||||
bytes username_ciphertext = 1;
|
||||
oneof response {
|
||||
// The ciphertext of the username identified by the provided link handle.
|
||||
bytes username_ciphertext = 1;
|
||||
|
||||
|
||||
// No username was found for the provided link handle.
|
||||
errors.NotFound not_found = 2;
|
||||
}
|
||||
}
|
||||
@@ -11,350 +11,312 @@ package org.signal.chat.backup;
|
||||
|
||||
import "google/protobuf/empty.proto";
|
||||
import "org/signal/chat/common.proto";
|
||||
import "org/signal/chat/errors.proto";
|
||||
import "org/signal/chat/require.proto";
|
||||
import "org/signal/chat/tag.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 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.
|
||||
service Backups {
|
||||
option (require.auth) = AUTH_ONLY_AUTHENTICATED;
|
||||
|
||||
/**
|
||||
* Set (blinded) backup-id(s) for the account.
|
||||
*
|
||||
* Each account may have a single active backup-id for each credential type
|
||||
* 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.
|
||||
*
|
||||
* At least one of the credential types must be set on the request.
|
||||
*
|
||||
* errors:
|
||||
* PERMISSION_DENIED: This account is not currently eligible for backups
|
||||
*/
|
||||
// Set (blinded) backup-id(s) for the account.
|
||||
//
|
||||
// Each account may have a single active backup-id for each credential type
|
||||
// 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.
|
||||
//
|
||||
// At least one of the credential types must be set on the request.
|
||||
// Only the primary device can set a blinded backup-id.
|
||||
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.
|
||||
*
|
||||
* errors:
|
||||
* ABORTED: The target account does not have a backup-id commitment
|
||||
*/
|
||||
// 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.
|
||||
*/
|
||||
// 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.
|
||||
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. If absent, the message credential request will not be updated.
|
||||
*/
|
||||
// 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. If absent, the message credential request will not be updated.
|
||||
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. If absent,
|
||||
* the media credential request will not be updated.
|
||||
*/
|
||||
// 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. If absent,
|
||||
// the media credential request will not be updated.
|
||||
bytes media_backup_auth_credential_request = 2;
|
||||
}
|
||||
|
||||
message SetBackupIdResponse {}
|
||||
|
||||
|
||||
message RedeemReceiptRequest {
|
||||
/**
|
||||
* Presentation for a previously acquired receipt, serialized with libsignal
|
||||
*/
|
||||
// Presentation for a previously acquired receipt, serialized with libsignal
|
||||
bytes presentation = 1;
|
||||
}
|
||||
message RedeemReceiptResponse {}
|
||||
|
||||
message RedeemReceiptResponse {
|
||||
oneof outcome {
|
||||
// The receipt was successfully redeemed
|
||||
google.protobuf.Empty success = 1;
|
||||
|
||||
// The target account does not have a backup-id commitment
|
||||
errors.FailedPrecondition account_missing_commitment = 2 [(tag.reason) = "account_missing_commitment"];
|
||||
|
||||
// The provided receipt presentation was malformed or expired
|
||||
errors.FailedPrecondition invalid_receipt = 3 [(tag.reason) = "invalid_receipt"];
|
||||
}
|
||||
}
|
||||
|
||||
message GetBackupAuthCredentialsRequest {
|
||||
/**
|
||||
* The redemption time for the first credential. This must be a day-aligned
|
||||
* seconds since epoch in UTC.
|
||||
*/
|
||||
// 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.
|
||||
*/
|
||||
// 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;
|
||||
message Credentials {
|
||||
// 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 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;
|
||||
// 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 redemption_end.
|
||||
map<int64, common.ZkCredential> media_credentials = 2;
|
||||
}
|
||||
|
||||
// The requested credentials. If absent, there was no existing blinded
|
||||
// backup id associated with the provided account.
|
||||
Credentials credentials = 1;
|
||||
}
|
||||
|
||||
/**
|
||||
* 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 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.
|
||||
service BackupsAnonymous {
|
||||
option (require.auth) = AUTH_ONLY_ANONYMOUS;
|
||||
|
||||
/**
|
||||
* Retrieve credentials used to read objects stored on the backup cdn
|
||||
*/
|
||||
// Retrieve credentials used to read objects stored on the backup cdn
|
||||
rpc GetCdnCredentials(GetCdnCredentialsRequest) returns (GetCdnCredentialsResponse) {}
|
||||
|
||||
/**
|
||||
* Retrieve credentials used to interact with the SecureValueRecoveryB service
|
||||
*/
|
||||
// Retrieve credentials used to interact with the SecureValueRecoveryB service
|
||||
rpc GetSvrBCredentials(GetSvrBCredentialsRequest) returns (GetSvrBCredentialsResponse) {}
|
||||
|
||||
/**
|
||||
* Retrieve information about the currently stored backup
|
||||
*/
|
||||
// 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.
|
||||
*/
|
||||
// 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.
|
||||
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
|
||||
*/
|
||||
// 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
|
||||
*
|
||||
* Trying to request an upload form larger than the maximum supported upload
|
||||
* size will return a PRECONDITION_FAILED error. The maximum upload size is
|
||||
* subject to change.
|
||||
*/
|
||||
// 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.
|
||||
*/
|
||||
// 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.
|
||||
*/
|
||||
// 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.
|
||||
*/
|
||||
// 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.
|
||||
*/
|
||||
// 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
|
||||
*/
|
||||
// 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
|
||||
*/
|
||||
// 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.
|
||||
*/
|
||||
// The public key, serialized in libsignal's elliptic-curve public key format.
|
||||
bytes public_key = 2;
|
||||
}
|
||||
message SetPublicKeyResponse {}
|
||||
message SetPublicKeyResponse {
|
||||
// The provided backup auth credential presentation could not be
|
||||
// authenticated. Either, the presentation could not be verified, or
|
||||
// the public key signature was invalid, or there is no backup associated
|
||||
// with the backup-id in the presentation.
|
||||
//
|
||||
// This may also be returned if there was an existing public key and the
|
||||
// provided public key did not match.
|
||||
errors.FailedZkAuthentication failed_authentication = 1 [(tag.reason) = "failed_authentication"];
|
||||
}
|
||||
|
||||
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 CdnCredentials {
|
||||
map<string, string> headers = 1;
|
||||
}
|
||||
oneof outcome {
|
||||
// Headers to include with requests to the read from the backup CDN. Includes
|
||||
// time limited read-only credentials.
|
||||
CdnCredentials cdn_credentials = 1;
|
||||
|
||||
// The provided backup auth credential presentation could not be
|
||||
// authenticated. Either, the presentation could not be verified, or
|
||||
// the public key signature was invalid, or there is no backup associated
|
||||
// with the backup-id in the presentation.
|
||||
errors.FailedZkAuthentication failed_authentication = 2 [(tag.reason) = "failed_authentication"];
|
||||
}
|
||||
}
|
||||
|
||||
message GetSvrBCredentialsRequest {
|
||||
SignedPresentation signed_presentation = 1;
|
||||
}
|
||||
message GetSvrBCredentialsResponse {
|
||||
/**
|
||||
* A username that can be presented to authenticate with SVRB
|
||||
*/
|
||||
string username = 1;
|
||||
|
||||
/**
|
||||
* A password that can be presented to authenticate with SVRB
|
||||
*/
|
||||
string password = 2;
|
||||
message GetSvrBCredentialsResponse {
|
||||
message SvrBCredentials {
|
||||
// A username that can be presented to authenticate with SVRB
|
||||
string username = 1;
|
||||
|
||||
// A password that can be presented to authenticate with SVRB
|
||||
string password = 2;
|
||||
}
|
||||
|
||||
oneof outcome {
|
||||
SvrBCredentials svrb_credentials = 1;
|
||||
|
||||
// The provided backup auth credential presentation could not be
|
||||
// authenticated. Either, the presentation could not be verified, or
|
||||
// the public key signature was invalid, or there is no backup associated
|
||||
// with the backup-id in the presentation.
|
||||
errors.FailedZkAuthentication failed_authentication = 2 [(tag.reason) = "failed_authentication"];
|
||||
}
|
||||
}
|
||||
|
||||
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;
|
||||
message BackupInfo {
|
||||
// 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 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 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 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;
|
||||
// The amount of space used to store media
|
||||
uint64 used_space = 5;
|
||||
}
|
||||
|
||||
oneof outcome {
|
||||
BackupInfo backup_info = 1;
|
||||
|
||||
// The provided backup auth credential presentation could not be
|
||||
// authenticated. Either, the presentation could not be verified, or
|
||||
// the public key signature was invalid, or there is no backup associated
|
||||
// with the backup-id in the presentation.
|
||||
errors.FailedZkAuthentication failed_authentication = 2 [(tag.reason) = "failed_authentication"];
|
||||
}
|
||||
}
|
||||
|
||||
message RefreshRequest {
|
||||
SignedPresentation signed_presentation = 1;
|
||||
}
|
||||
message RefreshResponse {
|
||||
SignedPresentation signed_presentation = 1;
|
||||
oneof outcome {
|
||||
// The provided backup auth credential presentation could not be
|
||||
// authenticated. Either, the presentation could not be verified, or
|
||||
// the public key signature was invalid, or there is no backup associated
|
||||
// with the backup-id in the presentation.
|
||||
errors.FailedZkAuthentication failed_authentication = 1 [(tag.reason) = "failed_authentication"];
|
||||
}
|
||||
}
|
||||
|
||||
message GetUploadFormRequest {
|
||||
@@ -365,84 +327,74 @@ message GetUploadFormRequest {
|
||||
}
|
||||
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.
|
||||
*/
|
||||
// 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.
|
||||
*/
|
||||
// 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;
|
||||
message UploadForm {
|
||||
// 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;
|
||||
// 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;
|
||||
// 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;
|
||||
// The URL to upload to with the appropriate protocol
|
||||
string signed_upload_location = 4;
|
||||
}
|
||||
|
||||
oneof outcome {
|
||||
UploadForm upload_form = 1;
|
||||
|
||||
// The provided backup auth credential presentation could not be
|
||||
// authenticated. Either, the presentation could not be verified, or
|
||||
// the public key signature was invalid, or there is no backup associated
|
||||
// with the backup-id in the presentation.
|
||||
errors.FailedZkAuthentication failed_authentication = 2 [(tag.reason) = "failed_authentication"];
|
||||
|
||||
// The request size was larger than the maximum supported upload size. The
|
||||
// maximum upload size is subject to change.
|
||||
errors.FailedPrecondition exceeds_max_upload_length = 3 [(tag.reason) = "oversize_upload"];
|
||||
}
|
||||
}
|
||||
|
||||
message CopyMediaItem {
|
||||
/**
|
||||
* The attachment cdn of the object to copy into the backup
|
||||
*/
|
||||
// The attachment cdn of the object to copy into the backup
|
||||
int32 source_attachment_cdn = 1 [(require.range).min = 1, (require.range).max = 3];
|
||||
|
||||
/**
|
||||
* The attachment key of the object to copy into the backup
|
||||
*/
|
||||
// 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
|
||||
*/
|
||||
// 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
|
||||
*/
|
||||
// media_id to copy on to the backup CDN
|
||||
bytes media_id = 4 [(require.exactlySize) = 15];
|
||||
|
||||
/**
|
||||
* A 32-byte key for the MAC
|
||||
*/
|
||||
// A 32-byte key for the MAC
|
||||
bytes hmac_key = 5 [(require.exactlySize) = 32];
|
||||
|
||||
/**
|
||||
* A 32-byte encryption key for AES
|
||||
*/
|
||||
// A 32-byte encryption key for AES
|
||||
bytes encryption_key = 6 [(require.exactlySize) = 32];
|
||||
}
|
||||
|
||||
message CopyMediaRequest {
|
||||
SignedPresentation signed_presentation = 1;
|
||||
|
||||
/**
|
||||
* Items to copy
|
||||
*/
|
||||
// Items to copy
|
||||
repeated CopyMediaItem items = 2;
|
||||
}
|
||||
|
||||
@@ -451,109 +403,102 @@ message CopyMediaResponse {
|
||||
message WrongSourceLength {}
|
||||
message OutOfSpace {}
|
||||
message CopySuccess {
|
||||
/**
|
||||
* The backup cdn where this media object is stored
|
||||
*/
|
||||
// The backup cdn where this media object is stored
|
||||
int32 cdn = 1;
|
||||
}
|
||||
|
||||
/**
|
||||
* The 15-byte media_id from the corresponding CopyMediaItem in the request
|
||||
*/
|
||||
// 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
|
||||
*/
|
||||
// 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 backup auth credential presentation could not be
|
||||
// authenticated. Either, the presentation could not be verified, or
|
||||
// the public key signature was invalid, or there is no backup associated
|
||||
// with the backup-id in the presentation.
|
||||
errors.FailedZkAuthentication failed_authentication = 3 [(tag.reason) = "failed_authentication"];
|
||||
|
||||
/**
|
||||
* The provided object length was incorrect
|
||||
*/
|
||||
WrongSourceLength wrong_source_length = 4;
|
||||
// The source object was not found
|
||||
SourceNotFound source_not_found = 4;
|
||||
|
||||
/**
|
||||
* All media capacity has been consumed. Free some space to continue.
|
||||
*/
|
||||
OutOfSpace out_of_space = 5;
|
||||
// The provided object length was incorrect
|
||||
WrongSourceLength wrong_source_length = 5;
|
||||
|
||||
// All media capacity has been consumed. Free some space to continue.
|
||||
OutOfSpace out_of_space = 6;
|
||||
}
|
||||
}
|
||||
|
||||
message ListMediaRequest {
|
||||
SignedPresentation signed_presentation = 1;
|
||||
|
||||
/**
|
||||
* A cursor returned by a previous call to ListMedia, absent on the first call
|
||||
*/
|
||||
// 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
|
||||
*/
|
||||
// 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
|
||||
*/
|
||||
// The backup cdn where this media object is stored
|
||||
int32 cdn = 1;
|
||||
/**
|
||||
* The media_id of the object
|
||||
*/
|
||||
// The media_id of the object
|
||||
bytes media_id = 2;
|
||||
/**
|
||||
* The length of the object in bytes
|
||||
*/
|
||||
// The length of the object in bytes
|
||||
uint64 length = 3;
|
||||
}
|
||||
|
||||
/**
|
||||
* A page of media objects stored for this backup ID
|
||||
*/
|
||||
repeated ListEntry page = 1;
|
||||
message ListResult {
|
||||
|
||||
/**
|
||||
* 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;
|
||||
// A page of media objects stored for this backup ID
|
||||
repeated ListEntry page = 1;
|
||||
|
||||
/**
|
||||
* 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;
|
||||
// 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;
|
||||
|
||||
/**
|
||||
* 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;
|
||||
// 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;
|
||||
}
|
||||
|
||||
oneof outcome {
|
||||
ListResult list_result = 1;
|
||||
|
||||
// The provided backup auth credential presentation could not be
|
||||
// authenticated. Either, the presentation could not be verified, or
|
||||
// the public key signature was invalid, or there is no backup associated
|
||||
// with the backup-id in the presentation.
|
||||
errors.FailedZkAuthentication failed_authentication = 2 [(tag.reason) = "failed_authentication"];
|
||||
}
|
||||
}
|
||||
|
||||
message DeleteAllRequest {
|
||||
SignedPresentation signed_presentation = 1;
|
||||
}
|
||||
message DeleteAllResponse {}
|
||||
message DeleteAllResponse {
|
||||
oneof outcome {
|
||||
// The provided backup auth credential presentation could not be
|
||||
// authenticated. Either, the presentation could not be verified, or
|
||||
// the public key signature was invalid, or there is no backup associated
|
||||
// with the backup-id in the presentation.
|
||||
errors.FailedZkAuthentication failed_authentication = 1 [(tag.reason) = "failed_authentication"];
|
||||
}
|
||||
}
|
||||
|
||||
message DeleteMediaItem {
|
||||
/**
|
||||
* The backup cdn where this media object is stored
|
||||
*/
|
||||
// The backup cdn where this media object is stored
|
||||
int32 cdn = 1;
|
||||
|
||||
/**
|
||||
* The media_id of the object to delete
|
||||
*/
|
||||
// The media_id of the object to delete
|
||||
bytes media_id = 2;
|
||||
}
|
||||
|
||||
@@ -564,13 +509,13 @@ message DeleteMediaRequest {
|
||||
}
|
||||
|
||||
message DeleteMediaResponse {
|
||||
/**
|
||||
* The backup cdn where the media object was stored
|
||||
*/
|
||||
int32 cdn = 1;
|
||||
oneof outcome {
|
||||
DeleteMediaItem deleted_item = 1;
|
||||
|
||||
/**
|
||||
* The media_id of the object that was successfully deleted
|
||||
*/
|
||||
bytes media_id = 3;
|
||||
// The provided backup auth credential presentation could not be
|
||||
// authenticated. Either, the presentation could not be verified, or
|
||||
// the public key signature was invalid, or there is no backup associated
|
||||
// with the backup-id in the presentation.
|
||||
errors.FailedZkAuthentication failed_authentication = 2 [(tag.reason) = "failed_authentication"];
|
||||
}
|
||||
}
|
||||
@@ -9,38 +9,28 @@ option java_multiple_files = true;
|
||||
|
||||
package org.signal.chat.calling;
|
||||
|
||||
/**
|
||||
* Provides methods for getting credentials for one-on-one and group calls.
|
||||
*/
|
||||
// Provides methods for getting credentials for one-on-one and group calls.
|
||||
service Calling {
|
||||
|
||||
/**
|
||||
* Generates and returns TURN credentials for the caller.
|
||||
*
|
||||
* This RPC may fail with a `RESOURCE_EXHAUSTED` status if a rate limit for
|
||||
* generating TURN credentials has been exceeded, in which case a
|
||||
* `retry-after` header containing an ISO 8601 duration string will be present
|
||||
* in the response trailers.
|
||||
*/
|
||||
// Generates and returns TURN credentials for the caller.
|
||||
//
|
||||
// This RPC may fail with a `RESOURCE_EXHAUSTED` status if a rate limit for
|
||||
// generating TURN credentials has been exceeded, in which case a
|
||||
// `retry-after` header containing an ISO 8601 duration string will be present
|
||||
// in the response trailers.
|
||||
rpc GetTurnCredentials(GetTurnCredentialsRequest) returns (GetTurnCredentialsResponse) {}
|
||||
}
|
||||
|
||||
message GetTurnCredentialsRequest {}
|
||||
|
||||
message GetTurnCredentialsResponse {
|
||||
/**
|
||||
* A username that can be presented to authenticate with a TURN server.
|
||||
*/
|
||||
// A username that can be presented to authenticate with a TURN server.
|
||||
string username = 1;
|
||||
|
||||
/**
|
||||
* A password that can be presented to authenticate with a TURN server.
|
||||
*/
|
||||
// A password that can be presented to authenticate with a TURN server.
|
||||
string password = 2;
|
||||
|
||||
/**
|
||||
* A list of TURN (or TURNS or STUN) servers where the provided credentials
|
||||
* may be used.
|
||||
*/
|
||||
// A list of TURN (or TURNS or STUN) servers where the provided credentials
|
||||
// may be used.
|
||||
repeated string urls = 3;
|
||||
}
|
||||
@@ -16,80 +16,54 @@ enum IdentityType {
|
||||
}
|
||||
|
||||
message ServiceIdentifier {
|
||||
/**
|
||||
* The type of identity represented by this service identifier.
|
||||
*/
|
||||
// The type of identity represented by this service identifier.
|
||||
IdentityType identity_type = 1;
|
||||
|
||||
/**
|
||||
* The UUID of the identity represented by this service identifier.
|
||||
*/
|
||||
// The UUID of the identity represented by this service identifier.
|
||||
bytes uuid = 2;
|
||||
}
|
||||
|
||||
message AccountIdentifiers {
|
||||
/**
|
||||
* A list of service identifiers for the identified account.
|
||||
*/
|
||||
// A list of service identifiers for the identified account.
|
||||
repeated ServiceIdentifier service_identifiers = 1;
|
||||
|
||||
/**
|
||||
* The phone number associated with the identified account.
|
||||
*/
|
||||
// The phone number associated with the identified account.
|
||||
string e164 = 2;
|
||||
|
||||
/**
|
||||
* The username hash (if any) associated with the identified account. May be
|
||||
* empty if no username is associated with the identified account.
|
||||
*/
|
||||
// The username hash (if any) associated with the identified account. May be
|
||||
// empty if no username is associated with the identified account.
|
||||
bytes username_hash = 3;
|
||||
}
|
||||
|
||||
message EcPreKey {
|
||||
/**
|
||||
* A locally-unique identifier for this key.
|
||||
*/
|
||||
// A locally-unique identifier for this key.
|
||||
uint64 key_id = 1;
|
||||
|
||||
/**
|
||||
* The serialized form of the public key.
|
||||
*/
|
||||
// The serialized form of the public key.
|
||||
bytes public_key = 2;
|
||||
}
|
||||
|
||||
message EcSignedPreKey {
|
||||
/**
|
||||
* A locally-unique identifier for this key.
|
||||
*/
|
||||
// A locally-unique identifier for this key.
|
||||
uint64 key_id = 1;
|
||||
|
||||
/**
|
||||
* The serialized form of the public key.
|
||||
*/
|
||||
// The serialized form of the public key.
|
||||
bytes public_key = 2;
|
||||
|
||||
/**
|
||||
* A signature of the public key, verifiable with the identity key for the
|
||||
* account/identity associated with this pre-key.
|
||||
*/
|
||||
// A signature of the public key, verifiable with the identity key for the
|
||||
// account/identity associated with this pre-key.
|
||||
bytes signature = 3;
|
||||
}
|
||||
|
||||
message KemSignedPreKey {
|
||||
/**
|
||||
* A locally-unique identifier for this key.
|
||||
*/
|
||||
// A locally-unique identifier for this key.
|
||||
uint64 key_id = 1;
|
||||
|
||||
/**
|
||||
* The serialized form of the public key.
|
||||
*/
|
||||
// The serialized form of the public key.
|
||||
bytes public_key = 2;
|
||||
|
||||
/**
|
||||
* A signature of the public key, verifiable with the identity key for the
|
||||
* account/identity associated with this pre-key.
|
||||
*/
|
||||
// A signature of the public key, verifiable with the identity key for the
|
||||
// account/identity associated with this pre-key.
|
||||
bytes signature = 3;
|
||||
}
|
||||
|
||||
@@ -115,3 +89,4 @@ message ZkCredential {
|
||||
*/
|
||||
bytes credential = 2;
|
||||
}
|
||||
|
||||
@@ -9,40 +9,34 @@ option java_multiple_files = true;
|
||||
|
||||
package org.signal.chat.credentials;
|
||||
|
||||
/**
|
||||
* Provides methods for obtaining and verifying credentials for "external" services
|
||||
* (i.e. services that are not a part of the chat server deployment).
|
||||
* All methods of this service require authentication.
|
||||
*/
|
||||
// Provides methods for obtaining and verifying credentials for "external" services
|
||||
// (i.e. services that are not a part of the chat server deployment).
|
||||
// All methods of this service require authentication.
|
||||
service ExternalServiceCredentials {
|
||||
|
||||
/**
|
||||
* Generates and returns an external service credentials for the caller.
|
||||
*
|
||||
* `UNAUTHENTICATED` status is returned if the call is made on unauthenticated channel.
|
||||
*
|
||||
* `INVALID_ARGUMENT` status is returned if service is not configured for the service type
|
||||
* found in the request OR if `externalService` is not specified in the request.
|
||||
*
|
||||
* `RESOURCE_EXHAUSTED` status is returned if a rate limit for
|
||||
* generating credentials has been exceeded, in which case a
|
||||
* `retry-after` header containing an ISO 8601 duration string will be present
|
||||
* in the response trailers.
|
||||
*/
|
||||
// Generates and returns an external service credentials for the caller.
|
||||
//
|
||||
// `UNAUTHENTICATED` status is returned if the call is made on unauthenticated channel.
|
||||
//
|
||||
// `INVALID_ARGUMENT` status is returned if service is not configured for the service type
|
||||
// found in the request OR if `externalService` is not specified in the request.
|
||||
//
|
||||
// `RESOURCE_EXHAUSTED` status is returned if a rate limit for
|
||||
// generating credentials has been exceeded, in which case a
|
||||
// `retry-after` header containing an ISO 8601 duration string will be present
|
||||
// in the response trailers.
|
||||
rpc GetExternalServiceCredentials(GetExternalServiceCredentialsRequest)
|
||||
returns (GetExternalServiceCredentialsResponse) {}
|
||||
}
|
||||
|
||||
service ExternalServiceCredentialsAnonymous {
|
||||
/**
|
||||
* Given a list of secure value recovery (SVR) service credentials and a phone number,
|
||||
* checks, which of the provided credentials were generated by the user with the given phone number
|
||||
* and have not yet expired.
|
||||
*
|
||||
* `UNAUTHENTICATED` status is returned if the call is made on unauthenticated channel.
|
||||
*
|
||||
* `INVALID_ARGUMENT` status is returned if request contains more than 10 passwords to be checked.
|
||||
*/
|
||||
// Given a list of secure value recovery (SVR) service credentials and a phone number,
|
||||
// checks, which of the provided credentials were generated by the user with the given phone number
|
||||
// and have not yet expired.
|
||||
//
|
||||
// `UNAUTHENTICATED` status is returned if the call is made on unauthenticated channel.
|
||||
//
|
||||
// `INVALID_ARGUMENT` status is returned if request contains more than 10 passwords to be checked.
|
||||
rpc CheckSvrCredentials(CheckSvrCredentialsRequest)
|
||||
returns (CheckSvrCredentialsResponse) {}
|
||||
}
|
||||
@@ -56,60 +50,42 @@ enum ExternalServiceType {
|
||||
}
|
||||
|
||||
message GetExternalServiceCredentialsRequest {
|
||||
/**
|
||||
* A service to request credentials for.
|
||||
*/
|
||||
// A service to request credentials for.
|
||||
ExternalServiceType externalService = 1;
|
||||
}
|
||||
|
||||
message GetExternalServiceCredentialsResponse {
|
||||
/**
|
||||
* A username that can be presented to authenticate with the external service.
|
||||
*/
|
||||
// A username that can be presented to authenticate with the external service.
|
||||
string username = 1;
|
||||
|
||||
/**
|
||||
* A password that can be presented to authenticate with the external service.
|
||||
*/
|
||||
// A password that can be presented to authenticate with the external service.
|
||||
string password = 2;
|
||||
}
|
||||
|
||||
enum AuthCheckResult {
|
||||
AUTH_CHECK_RESULT_UNSPECIFIED = 0;
|
||||
/**
|
||||
* The credentials could be used to make a call to SVR service by the user
|
||||
* associated with the `CheckSvrCredentialsRequest.number` phone number.
|
||||
*/
|
||||
// The credentials could be used to make a call to SVR service by the user
|
||||
// associated with the `CheckSvrCredentialsRequest.number` phone number.
|
||||
AUTH_CHECK_RESULT_MATCH = 1;
|
||||
/**
|
||||
* The credentials were generated by a different user.
|
||||
*/
|
||||
// The credentials were generated by a different user.
|
||||
AUTH_CHECK_RESULT_NO_MATCH = 2;
|
||||
/**
|
||||
* This status indicates that the corresponding credentials token should no longer be used.
|
||||
* This may be because it has expired or invalid, but it can also mean that there is a more
|
||||
* recent token in the request which should be used instead.
|
||||
*/
|
||||
// This status indicates that the corresponding credentials token should no longer be used.
|
||||
// This may be because it has expired or invalid, but it can also mean that there is a more
|
||||
// recent token in the request which should be used instead.
|
||||
AUTH_CHECK_RESULT_INVALID = 3;
|
||||
}
|
||||
|
||||
message CheckSvrCredentialsRequest {
|
||||
/**
|
||||
* A phone number in the E164 format to check the passwords against.
|
||||
* Only passwords generated for the user associated with the given number will be marked as `AUTH_CHECK_RESULT_MATCH`.
|
||||
*/
|
||||
// A phone number in the E164 format to check the passwords against.
|
||||
// Only passwords generated for the user associated with the given number will be marked as `AUTH_CHECK_RESULT_MATCH`.
|
||||
string number = 1;
|
||||
|
||||
/**
|
||||
* A list of credentials from previously made calls to `ExternalServiceCredentials.GetExternalServiceCredentials()`
|
||||
* for `EXTERNAL_SERVICE_TYPE_SVR`. This list may contain credentials generated by different users.
|
||||
*/
|
||||
// A list of credentials from previously made calls to `ExternalServiceCredentials.GetExternalServiceCredentials()`
|
||||
// for `EXTERNAL_SERVICE_TYPE_SVR`. This list may contain credentials generated by different users.
|
||||
repeated string passwords = 2;
|
||||
}
|
||||
|
||||
/**
|
||||
* For each of the credentials tokens in the `CheckSvrCredentialsRequest` contains the result of the check.
|
||||
*/
|
||||
// For each of the credentials tokens in the `CheckSvrCredentialsRequest` contains the result of the check.
|
||||
message CheckSvrCredentialsResponse {
|
||||
|
||||
map<string, AuthCheckResult> matches = 1;
|
||||
|
||||
@@ -12,50 +12,36 @@ package org.signal.chat.device;
|
||||
import "org/signal/chat/common.proto";
|
||||
import "org/signal/chat/require.proto";
|
||||
|
||||
/**
|
||||
* Provides methods for working with devices attached to a Signal account.
|
||||
*/
|
||||
// Provides methods for working with devices attached to a Signal account.
|
||||
service Devices {
|
||||
/**
|
||||
* Returns a list of devices associated with the caller's account.
|
||||
*/
|
||||
// Returns a list of devices associated with the caller's account.
|
||||
rpc GetDevices(GetDevicesRequest) returns (GetDevicesResponse) {}
|
||||
|
||||
/**
|
||||
* Removes a linked device from the caller's account. This call will fail with
|
||||
* a status of `PERMISSION_DENIED` if not called from the primary device
|
||||
* associated with an account. It will also fail with a status of
|
||||
* `INVALID_ARGUMENT` if the targeted device is the primary device associated
|
||||
* with the account.
|
||||
*/
|
||||
// Removes a linked device from the caller's account. This call will fail with
|
||||
// a status of `PERMISSION_DENIED` if not called from the primary device
|
||||
// associated with an account. It will also fail with a status of
|
||||
// `INVALID_ARGUMENT` if the targeted device is the primary device associated
|
||||
// with the account.
|
||||
rpc RemoveDevice(RemoveDeviceRequest) returns (RemoveDeviceResponse) {}
|
||||
|
||||
/**
|
||||
* Sets the encrypted human-readable name for a specific devices. Primary
|
||||
* devices may change the name of any device associated with their account,
|
||||
* but linked devices may only change their own name. This call will fail with
|
||||
* a status of `NOT_FOUND` if no device was found with the given identifier.
|
||||
* It will also fail with a status of `PERMISSION_DENIED` if a linked device
|
||||
* tries to change the name of any device other than itself.
|
||||
*/
|
||||
// Sets the encrypted human-readable name for a specific devices. Primary
|
||||
// devices may change the name of any device associated with their account,
|
||||
// but linked devices may only change their own name. This call will fail with
|
||||
// a status of `NOT_FOUND` if no device was found with the given identifier.
|
||||
// It will also fail with a status of `PERMISSION_DENIED` if a linked device
|
||||
// tries to change the name of any device other than itself.
|
||||
rpc SetDeviceName(SetDeviceNameRequest) returns (SetDeviceNameResponse) {}
|
||||
|
||||
/**
|
||||
* Sets the token(s) the server should use to send new message notifications
|
||||
* to the authenticated device.
|
||||
*/
|
||||
// Sets the token(s) the server should use to send new message notifications
|
||||
// to the authenticated device.
|
||||
rpc SetPushToken(SetPushTokenRequest) returns (SetPushTokenResponse) {}
|
||||
|
||||
/**
|
||||
* Removes any push tokens associated with the authenticated device. After
|
||||
* calling this method, the server will assume that the authenticated device
|
||||
* will periodically poll for new messages.
|
||||
*/
|
||||
// Removes any push tokens associated with the authenticated device. After
|
||||
// calling this method, the server will assume that the authenticated device
|
||||
// will periodically poll for new messages.
|
||||
rpc ClearPushToken(ClearPushTokenRequest) returns (ClearPushTokenResponse) {}
|
||||
|
||||
/**
|
||||
* Declares that the authenticated device supports certain features.
|
||||
*/
|
||||
// Declares that the authenticated device supports certain features.
|
||||
rpc SetCapabilities(SetCapabilitiesRequest) returns (SetCapabilitiesResponse) {}
|
||||
}
|
||||
|
||||
@@ -63,65 +49,45 @@ message GetDevicesRequest {}
|
||||
|
||||
message GetDevicesResponse {
|
||||
message LinkedDevice {
|
||||
/**
|
||||
* The identifier for the device within an account.
|
||||
*/
|
||||
// The identifier for the device within an account.
|
||||
uint32 id = 1;
|
||||
|
||||
/**
|
||||
* A sequence of bytes that encodes an encrypted human-readable name for
|
||||
* this device.
|
||||
*/
|
||||
// A sequence of bytes that encodes an encrypted human-readable name for
|
||||
// this device.
|
||||
bytes name = 2;
|
||||
|
||||
/**
|
||||
* The time, in milliseconds since the epoch, at which this device was
|
||||
* attached to its parent account.
|
||||
*/
|
||||
// The time, in milliseconds since the epoch, at which this device was
|
||||
// attached to its parent account.
|
||||
uint64 created = 3;
|
||||
|
||||
/**
|
||||
* The approximate time, in milliseconds since the epoch, at which this
|
||||
* device last connected to the server.
|
||||
*/
|
||||
// The approximate time, in milliseconds since the epoch, at which this
|
||||
// device last connected to the server.
|
||||
uint64 last_seen = 4;
|
||||
|
||||
/**
|
||||
* The registration ID of the given device.
|
||||
*/
|
||||
// The registration ID of the given device.
|
||||
uint32 registration_id = 5 [(require.range).max = 0x3fff];
|
||||
|
||||
/**
|
||||
* A sequence of bytes that encodes the time,
|
||||
* in milliseconds since the epoch, at which this device was
|
||||
* attached to its parent account.
|
||||
*/
|
||||
// A sequence of bytes that encodes the time,
|
||||
// in milliseconds since the epoch, at which this device was
|
||||
// attached to its parent account.
|
||||
bytes created_at_ciphertext = 6;
|
||||
}
|
||||
|
||||
/**
|
||||
* A list of devices linked to the authenticated account.
|
||||
*/
|
||||
// A list of devices linked to the authenticated account.
|
||||
repeated LinkedDevice devices = 1;
|
||||
}
|
||||
|
||||
message RemoveDeviceRequest {
|
||||
/**
|
||||
* The identifier for the device to remove from the authenticated account.
|
||||
*/
|
||||
// The identifier for the device to remove from the authenticated account.
|
||||
uint32 id = 1;
|
||||
}
|
||||
|
||||
message SetDeviceNameRequest {
|
||||
/**
|
||||
* A sequence of bytes that encodes an encrypted human-readable name for this
|
||||
* device.
|
||||
*/
|
||||
// A sequence of bytes that encodes an encrypted human-readable name for this
|
||||
// device.
|
||||
bytes name = 1;
|
||||
|
||||
/**
|
||||
* The identifier for the device for which to set a name.
|
||||
*/
|
||||
// The identifier for the device for which to set a name.
|
||||
uint32 id = 2;
|
||||
}
|
||||
|
||||
@@ -131,30 +97,22 @@ message RemoveDeviceResponse {}
|
||||
|
||||
message SetPushTokenRequest {
|
||||
message ApnsTokenRequest {
|
||||
/**
|
||||
* A "standard" APNs device token.
|
||||
*/
|
||||
// A "standard" APNs device token.
|
||||
string apns_token = 1;
|
||||
}
|
||||
|
||||
message FcmTokenRequest {
|
||||
/**
|
||||
* An FCM push token.
|
||||
*/
|
||||
// An FCM push token.
|
||||
string fcm_token = 1;
|
||||
}
|
||||
|
||||
oneof token_request {
|
||||
/**
|
||||
* If present, specifies the APNs device token(s) the server will use to
|
||||
* send new message notifications to the authenticated device.
|
||||
*/
|
||||
// If present, specifies the APNs device token(s) the server will use to
|
||||
// send new message notifications to the authenticated device.
|
||||
ApnsTokenRequest apns_token_request = 1;
|
||||
|
||||
/**
|
||||
* If present, specifies the FCM push token the server will use to send new
|
||||
* message notifications to the authenticated device.
|
||||
*/
|
||||
// If present, specifies the FCM push token the server will use to send new
|
||||
// message notifications to the authenticated device.
|
||||
FcmTokenRequest fcm_token_request = 2;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
/*
|
||||
* Copyright 2025 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
syntax = "proto3";
|
||||
|
||||
option java_multiple_files = true;
|
||||
|
||||
package org.signal.chat.errors;
|
||||
|
||||
// Response message that indicates a particular resource was not found.
|
||||
message NotFound {}
|
||||
|
||||
// Response message that indicates that some precondition of the request was not
|
||||
// met. For example, if there was a request to update foo, but foo had not been
|
||||
// set, this would be an appropriate error.
|
||||
message FailedPrecondition {
|
||||
// An optional description indicating what precondition failed.
|
||||
string description = 1;
|
||||
}
|
||||
|
||||
// Response message that authentication via an anonymous credential failed.
|
||||
message FailedZkAuthentication {
|
||||
// An optional description with additional information about the failure.
|
||||
string description = 1;
|
||||
}
|
||||
@@ -11,106 +11,86 @@ package org.signal.chat.keys;
|
||||
|
||||
import "org/signal/chat/common.proto";
|
||||
|
||||
/**
|
||||
* Provides methods for working with pre-keys.
|
||||
*/
|
||||
// Provides methods for working with pre-keys.
|
||||
service Keys {
|
||||
|
||||
/**
|
||||
* Retrieves an approximate count of the number of the various kinds of
|
||||
* pre-keys stored for the authenticated device.
|
||||
*/
|
||||
// Retrieves an approximate count of the number of the various kinds of
|
||||
// pre-keys stored for the authenticated device.
|
||||
rpc GetPreKeyCount (GetPreKeyCountRequest) returns (GetPreKeyCountResponse) {}
|
||||
|
||||
/**
|
||||
* Retrieves a set of pre-keys for establishing a session with the targeted
|
||||
* device or devices. Note that callers with an unidentified access key for
|
||||
* the targeted account should use the version of this method in
|
||||
* `KeysAnonymous` instead.
|
||||
*
|
||||
* This RPC may fail with a `NOT_FOUND` status if the target account was not
|
||||
* found, if no active device with the given ID (if specified) was found on
|
||||
* the target account, or if the account has no active devices. It may also
|
||||
* fail with a `RESOURCE_EXHAUSTED` if a rate limit for fetching keys has been
|
||||
* exceeded, in which case a `retry-after` header containing an ISO 8601
|
||||
* duration string will be present in the response trailers.
|
||||
*/
|
||||
// Retrieves a set of pre-keys for establishing a session with the targeted
|
||||
// device or devices. Note that callers with an unidentified access key for
|
||||
// the targeted account should use the version of this method in
|
||||
// `KeysAnonymous` instead.
|
||||
//
|
||||
// This RPC may fail with a `NOT_FOUND` status if the target account was not
|
||||
// found, if no active device with the given ID (if specified) was found on
|
||||
// the target account, or if the account has no active devices. It may also
|
||||
// fail with a `RESOURCE_EXHAUSTED` if a rate limit for fetching keys has been
|
||||
// exceeded, in which case a `retry-after` header containing an ISO 8601
|
||||
// duration string will be present in the response trailers.
|
||||
rpc GetPreKeys(GetPreKeysRequest) returns (GetPreKeysResponse) {}
|
||||
|
||||
/**
|
||||
* Uploads a new set of one-time EC pre-keys for the authenticated device,
|
||||
* clearing any previously-stored pre-keys. Note that all keys submitted via
|
||||
* a single call to this method _must_ have the same identity type (i.e. if
|
||||
* the first key has an ACI identity type, then all other keys in the same
|
||||
* stream must also have an ACI identity type).
|
||||
*
|
||||
* This RPC may fail with an `INVALID_ARGUMENT` status if one or more of the
|
||||
* given pre-keys was structurally invalid or if the list of pre-keys was
|
||||
* empty.
|
||||
*/
|
||||
// Uploads a new set of one-time EC pre-keys for the authenticated device,
|
||||
// clearing any previously-stored pre-keys. Note that all keys submitted via
|
||||
// a single call to this method _must_ have the same identity type (i.e. if
|
||||
// the first key has an ACI identity type, then all other keys in the same
|
||||
// stream must also have an ACI identity type).
|
||||
//
|
||||
// This RPC may fail with an `INVALID_ARGUMENT` status if one or more of the
|
||||
// given pre-keys was structurally invalid or if the list of pre-keys was
|
||||
// empty.
|
||||
rpc SetOneTimeEcPreKeys (SetOneTimeEcPreKeysRequest) returns (SetPreKeyResponse) {}
|
||||
|
||||
/**
|
||||
* Uploads a new set of one-time KEM pre-keys for the authenticated device,
|
||||
* clearing any previously-stored pre-keys. Note that all keys submitted via
|
||||
* a single call to this method _must_ have the same identity type (i.e. if
|
||||
* the first key has an ACI identity type, then all other keys in the same
|
||||
* stream must also have an ACI identity type).
|
||||
*
|
||||
* This RPC may fail with an `INVALID_ARGUMENT` status if one or more of the
|
||||
* given pre-keys was structurally invalid, had an invalid signature, or if
|
||||
* the list of pre-keys was empty.
|
||||
*/
|
||||
// Uploads a new set of one-time KEM pre-keys for the authenticated device,
|
||||
// clearing any previously-stored pre-keys. Note that all keys submitted via
|
||||
// a single call to this method _must_ have the same identity type (i.e. if
|
||||
// the first key has an ACI identity type, then all other keys in the same
|
||||
// stream must also have an ACI identity type).
|
||||
//
|
||||
// This RPC may fail with an `INVALID_ARGUMENT` status if one or more of the
|
||||
// given pre-keys was structurally invalid, had an invalid signature, or if
|
||||
// the list of pre-keys was empty.
|
||||
rpc SetOneTimeKemSignedPreKeys (SetOneTimeKemSignedPreKeysRequest) returns (SetPreKeyResponse) {}
|
||||
|
||||
/**
|
||||
* Sets the signed EC pre-key for one identity (i.e. ACI or PNI) associated
|
||||
* with the authenticated device.
|
||||
*
|
||||
* This RPC may fail with an `INVALID_ARGUMENT` status if the given pre-key
|
||||
* was structurally invalid, had a bad signature, or was missing entirely.
|
||||
*/
|
||||
// Sets the signed EC pre-key for one identity (i.e. ACI or PNI) associated
|
||||
// with the authenticated device.
|
||||
//
|
||||
// This RPC may fail with an `INVALID_ARGUMENT` status if the given pre-key
|
||||
// was structurally invalid, had a bad signature, or was missing entirely.
|
||||
rpc SetEcSignedPreKey (SetEcSignedPreKeyRequest) returns (SetPreKeyResponse) {}
|
||||
|
||||
/**
|
||||
* Sets the last-resort KEM pre-key for one identity (i.e. ACI or PNI)
|
||||
* associated with the authenticated device.
|
||||
*
|
||||
* This RPC may fail with an `INVALID_ARGUMENT` status if the given pre-key
|
||||
* was structurally invalid, had a bad signature, or was missing entirely.
|
||||
*/
|
||||
// Sets the last-resort KEM pre-key for one identity (i.e. ACI or PNI)
|
||||
// associated with the authenticated device.
|
||||
//
|
||||
// This RPC may fail with an `INVALID_ARGUMENT` status if the given pre-key
|
||||
// was structurally invalid, had a bad signature, or was missing entirely.
|
||||
rpc SetKemLastResortPreKey (SetKemLastResortPreKeyRequest) returns (SetPreKeyResponse) {}
|
||||
}
|
||||
|
||||
/**
|
||||
* Provides methods for working with pre-keys using "unidentified access"
|
||||
* credentials.
|
||||
*/
|
||||
// Provides methods for working with pre-keys using "unidentified access"
|
||||
// credentials.
|
||||
service KeysAnonymous {
|
||||
|
||||
/**
|
||||
* Retrieves a set of pre-keys for establishing a session with the targeted
|
||||
* device or devices. Callers must not submit any self-identifying credentials
|
||||
* when calling this method and must instead present the targeted account's
|
||||
* unidentified access key as an anonymous authentication mechanism. Callers
|
||||
* without an unidentified access key should use the equivalent, authenticated
|
||||
* method in `Keys` instead.
|
||||
*
|
||||
* This RPC may fail with an `UNAUTHENTICATED` status if the given
|
||||
* unidentified access key did not match the target account's unidentified
|
||||
* access key or if the target account was not found. It may also fail with a
|
||||
* `NOT_FOUND` status if no active device with the given ID (if specified) was
|
||||
* found on the target account, or if the target account has no active
|
||||
* devices.
|
||||
*/
|
||||
// Retrieves a set of pre-keys for establishing a session with the targeted
|
||||
// device or devices. Callers must not submit any self-identifying credentials
|
||||
// when calling this method and must instead present the targeted account's
|
||||
// unidentified access key as an anonymous authentication mechanism. Callers
|
||||
// without an unidentified access key should use the equivalent, authenticated
|
||||
// method in `Keys` instead.
|
||||
//
|
||||
// This RPC may fail with an `UNAUTHENTICATED` status if the given
|
||||
// unidentified access key did not match the target account's unidentified
|
||||
// access key or if the target account was not found. It may also fail with a
|
||||
// `NOT_FOUND` status if no active device with the given ID (if specified) was
|
||||
// found on the target account, or if the target account has no active
|
||||
// devices.
|
||||
rpc GetPreKeys(GetPreKeysAnonymousRequest) returns (GetPreKeysResponse) {}
|
||||
|
||||
/**
|
||||
* Checks identity key fingerprints of the target accounts.
|
||||
*
|
||||
* Returns a stream of elements, each one representing an account that had a mismatched
|
||||
* identity key fingerprint with the server and the corresponding identity key stored by the server.
|
||||
*/
|
||||
// Checks identity key fingerprints of the target accounts.
|
||||
//
|
||||
// Returns a stream of elements, each one representing an account that had a mismatched
|
||||
// identity key fingerprint with the server and the corresponding identity key stored by the server.
|
||||
rpc CheckIdentityKeys(stream CheckIdentityKeyRequest) returns (stream CheckIdentityKeyResponse) {}
|
||||
}
|
||||
|
||||
@@ -118,151 +98,103 @@ message GetPreKeyCountRequest {
|
||||
}
|
||||
|
||||
message GetPreKeyCountResponse {
|
||||
/**
|
||||
* The approximate number of one-time EC pre-keys stored for the
|
||||
* authenticated device and associated with the caller's ACI.
|
||||
*/
|
||||
// The approximate number of one-time EC pre-keys stored for the
|
||||
// authenticated device and associated with the caller's ACI.
|
||||
uint32 aci_ec_pre_key_count = 1;
|
||||
|
||||
/**
|
||||
* The approximate number of one-time Kyber pre-keys stored for the
|
||||
* authenticated device and associated with the caller's ACI.
|
||||
*/
|
||||
// The approximate number of one-time Kyber pre-keys stored for the
|
||||
// authenticated device and associated with the caller's ACI.
|
||||
uint32 aci_kem_pre_key_count = 2;
|
||||
|
||||
/**
|
||||
* The approximate number of one-time EC pre-keys stored for the
|
||||
* authenticated device and associated with the caller's PNI.
|
||||
*/
|
||||
// The approximate number of one-time EC pre-keys stored for the
|
||||
// authenticated device and associated with the caller's PNI.
|
||||
uint32 pni_ec_pre_key_count = 3;
|
||||
|
||||
/**
|
||||
* The approximate number of one-time KEM pre-keys stored for the
|
||||
* authenticated device and associated with the caller's PNI.
|
||||
*/
|
||||
// The approximate number of one-time KEM pre-keys stored for the
|
||||
// authenticated device and associated with the caller's PNI.
|
||||
uint32 pni_kem_pre_key_count = 4;
|
||||
}
|
||||
|
||||
message GetPreKeysRequest {
|
||||
/**
|
||||
* The service identifier of the account for which to retrieve pre-keys.
|
||||
*/
|
||||
// The service identifier of the account for which to retrieve pre-keys.
|
||||
common.ServiceIdentifier target_identifier = 1;
|
||||
|
||||
/**
|
||||
* The ID of the device associated with the targeted account for which to
|
||||
* retrieve pre-keys. If not set, pre-keys are returned for all devices
|
||||
* associated with the targeted account.
|
||||
*/
|
||||
// The ID of the device associated with the targeted account for which to
|
||||
// retrieve pre-keys. If not set, pre-keys are returned for all devices
|
||||
// associated with the targeted account.
|
||||
optional uint32 device_id = 2;
|
||||
}
|
||||
|
||||
message GetPreKeysAnonymousRequest {
|
||||
/**
|
||||
* The request to retrieve pre-keys for a specific account/device(s).
|
||||
*/
|
||||
// The request to retrieve pre-keys for a specific account/device(s).
|
||||
GetPreKeysRequest request = 1;
|
||||
|
||||
/**
|
||||
* A means to authorize the request.
|
||||
*/
|
||||
// A means to authorize the request.
|
||||
oneof authorization {
|
||||
/**
|
||||
* The unidentified access key (UAK) for the targeted account.
|
||||
*/
|
||||
// The unidentified access key (UAK) for the targeted account.
|
||||
bytes unidentified_access_key = 2;
|
||||
|
||||
/**
|
||||
* A group send endorsement token for the targeted account.
|
||||
*/
|
||||
// A group send endorsement token for the targeted account.
|
||||
bytes group_send_token = 3;
|
||||
}
|
||||
}
|
||||
|
||||
message GetPreKeysResponse {
|
||||
message PreKeyBundle {
|
||||
/**
|
||||
* The EC signed pre-key associated with the targeted
|
||||
* account/device/identity.
|
||||
*/
|
||||
// The EC signed pre-key associated with the targeted
|
||||
// account/device/identity.
|
||||
common.EcSignedPreKey ec_signed_pre_key = 1;
|
||||
|
||||
/**
|
||||
* A one-time EC pre-key for the targeted account/device/identity. May not
|
||||
* be set if no one-time EC pre-keys are available.
|
||||
*/
|
||||
// A one-time EC pre-key for the targeted account/device/identity. May not
|
||||
// be set if no one-time EC pre-keys are available.
|
||||
common.EcPreKey ec_one_time_pre_key = 2;
|
||||
|
||||
/**
|
||||
* A one-time KEM pre-key (or a last-resort KEM pre-key) for the targeted
|
||||
* account/device/identity.
|
||||
*/
|
||||
// A one-time KEM pre-key (or a last-resort KEM pre-key) for the targeted
|
||||
// account/device/identity.
|
||||
common.KemSignedPreKey kem_one_time_pre_key = 3;
|
||||
|
||||
/**
|
||||
* The registration ID for the targeted account/device/identity.
|
||||
*/
|
||||
// The registration ID for the targeted account/device/identity.
|
||||
uint32 registration_id = 4;
|
||||
}
|
||||
|
||||
/**
|
||||
* The identity key associated with the targeted account/identity.
|
||||
*/
|
||||
// The identity key associated with the targeted account/identity.
|
||||
bytes identity_key = 1;
|
||||
|
||||
/**
|
||||
* A map of device IDs to pre-key "bundles" for the targeted account.
|
||||
*/
|
||||
// A map of device IDs to pre-key "bundles" for the targeted account.
|
||||
map<uint32, PreKeyBundle> pre_keys = 2;
|
||||
}
|
||||
|
||||
message SetOneTimeEcPreKeysRequest {
|
||||
/**
|
||||
* The identity type (i.e. ACI/PNI) with which the keys in this request are
|
||||
* associated.
|
||||
*/
|
||||
// The identity type (i.e. ACI/PNI) with which the keys in this request are
|
||||
// associated.
|
||||
common.IdentityType identity_type = 1;
|
||||
|
||||
/**
|
||||
* The unsigned EC pre-keys to be stored.
|
||||
*/
|
||||
// The unsigned EC pre-keys to be stored.
|
||||
repeated common.EcPreKey pre_keys = 2;
|
||||
}
|
||||
|
||||
message SetOneTimeKemSignedPreKeysRequest {
|
||||
/**
|
||||
* The identity type (i.e. ACI/PNI) with which the keys in this request are
|
||||
* associated.
|
||||
*/
|
||||
// The identity type (i.e. ACI/PNI) with which the keys in this request are
|
||||
// associated.
|
||||
common.IdentityType identity_type = 1;
|
||||
|
||||
/**
|
||||
* The KEM pre-keys to be stored.
|
||||
*/
|
||||
// The KEM pre-keys to be stored.
|
||||
repeated common.KemSignedPreKey pre_keys = 2;
|
||||
}
|
||||
|
||||
message SetEcSignedPreKeyRequest {
|
||||
/**
|
||||
* The identity type (i.e. ACI/PNI) with which this key is associated.
|
||||
*/
|
||||
// The identity type (i.e. ACI/PNI) with which this key is associated.
|
||||
common.IdentityType identity_type = 1;
|
||||
|
||||
/**
|
||||
* The signed EC pre-key itself.
|
||||
*/
|
||||
// The signed EC pre-key itself.
|
||||
common.EcSignedPreKey signed_pre_key = 2;
|
||||
}
|
||||
|
||||
message SetKemLastResortPreKeyRequest {
|
||||
/**
|
||||
* The identity type (i.e. ACI/PNI) with which this key is associated.
|
||||
*/
|
||||
// The identity type (i.e. ACI/PNI) with which this key is associated.
|
||||
common.IdentityType identity_type = 1;
|
||||
|
||||
/**
|
||||
* The signed KEM pre-key itself.
|
||||
*/
|
||||
// The signed KEM pre-key itself.
|
||||
common.KemSignedPreKey signed_pre_key = 2;
|
||||
}
|
||||
|
||||
@@ -270,23 +202,15 @@ message SetPreKeyResponse {
|
||||
}
|
||||
|
||||
message CheckIdentityKeyRequest {
|
||||
/**
|
||||
* The service identifier of the account for which we want to check the associated identity key fingerprint.
|
||||
*/
|
||||
// The service identifier of the account for which we want to check the associated identity key fingerprint.
|
||||
common.ServiceIdentifier target_identifier = 1;
|
||||
/**
|
||||
* The most significant 4 bytes of the SHA-256 hash of the identity key associated with the target account/identity type.
|
||||
*/
|
||||
// The most significant 4 bytes of the SHA-256 hash of the identity key associated with the target account/identity type.
|
||||
bytes fingerprint = 2;
|
||||
}
|
||||
|
||||
message CheckIdentityKeyResponse {
|
||||
/**
|
||||
* The service identifier of the account for which there is a mismatch between the client and server identity key fingerprints.
|
||||
*/
|
||||
// The service identifier of the account for which there is a mismatch between the client and server identity key fingerprints.
|
||||
common.ServiceIdentifier target_identifier = 1;
|
||||
/**
|
||||
* The identity key that is stored by the server for the target account/identity type.
|
||||
*/
|
||||
// The identity key that is stored by the server for the target account/identity type.
|
||||
bytes identity_key = 2;
|
||||
}
|
||||
@@ -12,454 +12,346 @@ package org.signal.chat.messages;
|
||||
import "org/signal/chat/common.proto";
|
||||
import "org/signal/chat/require.proto";
|
||||
|
||||
/**
|
||||
* Provides methods for sending "unsealed sender" messages.
|
||||
*/
|
||||
// Provides methods for sending "unsealed sender" messages.
|
||||
service Messages {
|
||||
|
||||
option (require.auth) = AUTH_ONLY_AUTHENTICATED;
|
||||
|
||||
/**
|
||||
* Sends an "unsealed sender" message to all devices linked to a single
|
||||
* destination account.
|
||||
*
|
||||
* This RPC may fail with a `NOT_FOUND` status if the destination account was
|
||||
* not found. It may also fail with an `INVALID_ARGUMENT` status if the
|
||||
* destination account is the same as the authenticated caller (callers should
|
||||
* use `SendSyncMessage` to send messages to themselves). It may also fail
|
||||
* with a `RESOURCE_EXHAUSTED` status if a rate limit for sending messages has
|
||||
* been exceeded, in which case a `retry-after` header containing an ISO 8601
|
||||
* duration string may be present in the response trailers.
|
||||
*
|
||||
* Note that message delivery may not succeed even if this RPC returns an `OK`
|
||||
* status; callers must check the response object to verify that the message
|
||||
* was actually accepted and sent.
|
||||
*/
|
||||
// Sends an "unsealed sender" message to all devices linked to a single
|
||||
// destination account.
|
||||
//
|
||||
// This RPC may fail with a `NOT_FOUND` status if the destination account was
|
||||
// not found. It may also fail with an `INVALID_ARGUMENT` status if the
|
||||
// destination account is the same as the authenticated caller (callers should
|
||||
// use `SendSyncMessage` to send messages to themselves). It may also fail
|
||||
// with a `RESOURCE_EXHAUSTED` status if a rate limit for sending messages has
|
||||
// been exceeded, in which case a `retry-after` header containing an ISO 8601
|
||||
// duration string may be present in the response trailers.
|
||||
//
|
||||
// Note that message delivery may not succeed even if this RPC returns an `OK`
|
||||
// status; callers must check the response object to verify that the message
|
||||
// was actually accepted and sent.
|
||||
rpc SendMessage(SendAuthenticatedSenderMessageRequest) returns (SendMessageResponse) {}
|
||||
|
||||
/**
|
||||
* Sends a "sync" message to all other devices linked to the authenticated
|
||||
* sender's account. This RPC may fail with a `RESOURCE_EXHAUSTED` status if a
|
||||
* rate limit for sending messages has been exceeded, in which case a
|
||||
* `retry-after` header containing an ISO 8601 duration string may be present
|
||||
* in the response trailers.
|
||||
*
|
||||
* Note that message delivery may not succeed even if this RPC returns an `OK`
|
||||
* status; callers must check the response object to verify that the message
|
||||
* was actually accepted and sent.
|
||||
*/
|
||||
// Sends a "sync" message to all other devices linked to the authenticated
|
||||
// sender's account. This RPC may fail with a `RESOURCE_EXHAUSTED` status if a
|
||||
// rate limit for sending messages has been exceeded, in which case a
|
||||
// `retry-after` header containing an ISO 8601 duration string may be present
|
||||
// in the response trailers.
|
||||
//
|
||||
// Note that message delivery may not succeed even if this RPC returns an `OK`
|
||||
// status; callers must check the response object to verify that the message
|
||||
// was actually accepted and sent.
|
||||
rpc SendSyncMessage(SendSyncMessageRequest) returns (SendMessageResponse) {}
|
||||
}
|
||||
|
||||
/**
|
||||
* Provides methods for sending "sealed sender" messages.
|
||||
*/
|
||||
// Provides methods for sending "sealed sender" messages.
|
||||
service MessagesAnonymous {
|
||||
|
||||
option (require.auth) = AUTH_ONLY_ANONYMOUS;
|
||||
|
||||
/**
|
||||
* Sends a "sealed sender" message to all devices linked to a single
|
||||
* destination account.
|
||||
*
|
||||
* This RPC may fail with an `UNAUTHENTICATED` status if the given credentials
|
||||
* were not accepted for any reason or if the destination account was not
|
||||
* found while using an unidentified access key (UAK) for authorization. It
|
||||
* may also fail with a `NOT_FOUND` status if the destination account was not
|
||||
* found while using a group send token for authorization. It may also fail
|
||||
* with a `RESOURCE_EXHAUSTED` status if a rate limit for sending messages has
|
||||
* been exceeded, in which case a `retry-after` header containing an ISO 8601
|
||||
* duration string may be present in the response trailers.
|
||||
*
|
||||
* Note that message delivery may not succeed even if this RPC returns an `OK`
|
||||
* status; callers must check the response object to verify that the message
|
||||
* was actually accepted and sent.
|
||||
*/
|
||||
// Sends a "sealed sender" message to all devices linked to a single
|
||||
// destination account.
|
||||
//
|
||||
// This RPC may fail with an `UNAUTHENTICATED` status if the given credentials
|
||||
// were not accepted for any reason or if the destination account was not
|
||||
// found while using an unidentified access key (UAK) for authorization. It
|
||||
// may also fail with a `NOT_FOUND` status if the destination account was not
|
||||
// found while using a group send token for authorization. It may also fail
|
||||
// with a `RESOURCE_EXHAUSTED` status if a rate limit for sending messages has
|
||||
// been exceeded, in which case a `retry-after` header containing an ISO 8601
|
||||
// duration string may be present in the response trailers.
|
||||
//
|
||||
// Note that message delivery may not succeed even if this RPC returns an `OK`
|
||||
// status; callers must check the response object to verify that the message
|
||||
// was actually accepted and sent.
|
||||
rpc SendSingleRecipientMessage(SendSealedSenderMessageRequest) returns (SendMessageResponse) {}
|
||||
|
||||
/**
|
||||
* Sends a "sealed sender" message with a common payload to all devices linked
|
||||
* to multiple destination accounts.
|
||||
*
|
||||
* This RPC may fail with a `NOT_FOUND` status if one or more destination
|
||||
* accounts were not found. It may also fail with an `UNAUTHENTICATED` status
|
||||
* if the given credentials were not accepted for any reason. It may also fail
|
||||
* with a `RESOURCE_EXHAUSTED` status if a rate limit for sending messages has
|
||||
* been exceeded, in which case a `retry-after` header containing an ISO 8601
|
||||
* duration string may be present in the response trailers.
|
||||
*
|
||||
* Note that message delivery may not succeed even if this RPC returns an `OK`
|
||||
* status; callers must check the response object to verify that the message
|
||||
* was actually accepted and sent.
|
||||
*/
|
||||
// Sends a "sealed sender" message with a common payload to all devices linked
|
||||
// to multiple destination accounts.
|
||||
//
|
||||
// This RPC may fail with a `NOT_FOUND` status if one or more destination
|
||||
// accounts were not found. It may also fail with an `UNAUTHENTICATED` status
|
||||
// if the given credentials were not accepted for any reason. It may also fail
|
||||
// with a `RESOURCE_EXHAUSTED` status if a rate limit for sending messages has
|
||||
// been exceeded, in which case a `retry-after` header containing an ISO 8601
|
||||
// duration string may be present in the response trailers.
|
||||
//
|
||||
// Note that message delivery may not succeed even if this RPC returns an `OK`
|
||||
// status; callers must check the response object to verify that the message
|
||||
// was actually accepted and sent.
|
||||
rpc SendMultiRecipientMessage(SendMultiRecipientMessageRequest) returns (SendMultiRecipientMessageResponse) {}
|
||||
|
||||
/**
|
||||
* Sends a story message to devices linked to a single destination account.
|
||||
*
|
||||
* This RPC may fail with a `RESOURCE_EXHAUSTED` status if a rate limit for
|
||||
* sending stories has been exceeded, in which case a `retry-after` header
|
||||
* containing an ISO 8601 duration string may be present in the response
|
||||
* trailers.
|
||||
*
|
||||
* Note that message delivery may not succeed even if this RPC returns an `OK`
|
||||
* status; callers must check the response object to verify that the message
|
||||
* was actually accepted and sent.
|
||||
*/
|
||||
// Sends a story message to devices linked to a single destination account.
|
||||
//
|
||||
// This RPC may fail with a `RESOURCE_EXHAUSTED` status if a rate limit for
|
||||
// sending stories has been exceeded, in which case a `retry-after` header
|
||||
// containing an ISO 8601 duration string may be present in the response
|
||||
// trailers.
|
||||
//
|
||||
// Note that message delivery may not succeed even if this RPC returns an `OK`
|
||||
// status; callers must check the response object to verify that the message
|
||||
// was actually accepted and sent.
|
||||
rpc SendStory(SendStoryMessageRequest) returns (SendMessageResponse) {}
|
||||
|
||||
/**
|
||||
* Sends a story message with a common payload to devices linked to devices
|
||||
* linked to multiple destination accounts.
|
||||
*
|
||||
* This RPC may fail with a `RESOURCE_EXHAUSTED` status if a rate limit for
|
||||
* sending stories has been exceeded, in which case a `retry-after` header
|
||||
* containing an ISO 8601 duration string may be present in the response
|
||||
* trailers.
|
||||
*
|
||||
* Note that message delivery may not succeed even if this RPC returns an `OK`
|
||||
* status; callers must check the response object to verify that the message
|
||||
* was actually accepted and sent.
|
||||
*/
|
||||
// Sends a story message with a common payload to devices linked to devices
|
||||
// linked to multiple destination accounts.
|
||||
//
|
||||
// This RPC may fail with a `RESOURCE_EXHAUSTED` status if a rate limit for
|
||||
// sending stories has been exceeded, in which case a `retry-after` header
|
||||
// containing an ISO 8601 duration string may be present in the response
|
||||
// trailers.
|
||||
//
|
||||
// Note that message delivery may not succeed even if this RPC returns an `OK`
|
||||
// status; callers must check the response object to verify that the message
|
||||
// was actually accepted and sent.
|
||||
rpc SendMultiRecipientStory(SendMultiRecipientStoryRequest) returns (SendMultiRecipientMessageResponse) {}
|
||||
}
|
||||
|
||||
message IndividualRecipientMessageBundle {
|
||||
|
||||
/**
|
||||
* A message for an individual device linked to a destination account.
|
||||
*/
|
||||
// A message for an individual device linked to a destination account.
|
||||
message Message {
|
||||
|
||||
/**
|
||||
* The registration ID for the destination device.
|
||||
*/
|
||||
// The registration ID for the destination device.
|
||||
uint32 registration_id = 1 [(require.range).max = 0x3fff];
|
||||
|
||||
/**
|
||||
* The content of the message to deliver to the destination device.
|
||||
*/
|
||||
// The content of the message to deliver to the destination device.
|
||||
bytes payload = 2 [(require.size).max = 262144]; // 256 KiB
|
||||
}
|
||||
|
||||
/**
|
||||
* The time, in milliseconds since the epoch, at which this message was
|
||||
* originally sent from the perspective of the sender. Note that the maximum
|
||||
* allowable timestamp for JavaScript clients is less than Long.MAX_VALUE; see
|
||||
* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date#the_epoch_timestamps_and_invalid_date
|
||||
* for additional details and discussion.
|
||||
*/
|
||||
// The time, in milliseconds since the epoch, at which this message was
|
||||
// originally sent from the perspective of the sender. Note that the maximum
|
||||
// allowable timestamp for JavaScript clients is less than Long.MAX_VALUE; see
|
||||
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date#the_epoch_timestamps_and_invalid_date
|
||||
// for additional details and discussion.
|
||||
uint64 timestamp = 1 [(require.range).min = 1, (require.range).max = 8640000000000000];
|
||||
|
||||
/**
|
||||
* A map of device IDs to individual messages. Generally, callers must include
|
||||
* one message for each device linked to the destination account. In cases of
|
||||
* "sync messages" where a sender is distributing information to other devices
|
||||
* linked to the sender's account, senders may omit a message for the sending
|
||||
* device.
|
||||
*/
|
||||
// A map of device IDs to individual messages. Generally, callers must include
|
||||
// one message for each device linked to the destination account. In cases of
|
||||
// "sync messages" where a sender is distributing information to other devices
|
||||
// linked to the sender's account, senders may omit a message for the sending
|
||||
// device.
|
||||
map<uint32, Message> messages = 2 [(require.nonEmpty) = true];
|
||||
}
|
||||
|
||||
enum AuthenticatedSenderMessageType {
|
||||
UNSPECIFIED = 0;
|
||||
|
||||
/**
|
||||
* A double-ratchet message represents a "normal," "unsealed-sender" message
|
||||
* encrypted using the Double Ratchet within an established Signal session.
|
||||
*/
|
||||
// A double-ratchet message represents a "normal," "unsealed-sender" message
|
||||
// encrypted using the Double Ratchet within an established Signal session.
|
||||
DOUBLE_RATCHET = 1;
|
||||
|
||||
/**
|
||||
* A prekey message begins a new Signal session. The `content` of a prekey
|
||||
* message is a superset of a double-ratchet message's `content` and
|
||||
* contains the sender's identity public key and information identifying the
|
||||
* pre-keys used in the message's ciphertext.
|
||||
*/
|
||||
// A prekey message begins a new Signal session. The `content` of a prekey
|
||||
// message is a superset of a double-ratchet message's `content` and
|
||||
// contains the sender's identity public key and information identifying the
|
||||
// pre-keys used in the message's ciphertext.
|
||||
PREKEY_MESSAGE = 2;
|
||||
|
||||
/**
|
||||
* A plaintext message is used solely to convey encryption error receipts
|
||||
* and never contains encrypted message content. Encryption error receipts
|
||||
* must be delivered in plaintext because, encryption/decryption of a prior
|
||||
* message failed and there is no reason to believe that
|
||||
* encryption/decryption of subsequent messages with the same key material
|
||||
* would succeed.
|
||||
*
|
||||
* Critically, plaintext messages never have "real" message content
|
||||
* generated by users. Plaintext messages include sender information.
|
||||
*/
|
||||
// A plaintext message is used solely to convey encryption error receipts
|
||||
// and never contains encrypted message content. Encryption error receipts
|
||||
// must be delivered in plaintext because, encryption/decryption of a prior
|
||||
// message failed and there is no reason to believe that
|
||||
// encryption/decryption of subsequent messages with the same key material
|
||||
// would succeed.
|
||||
//
|
||||
// Critically, plaintext messages never have "real" message content
|
||||
// generated by users. Plaintext messages include sender information.
|
||||
PLAINTEXT_CONTENT = 3;
|
||||
}
|
||||
|
||||
message SendAuthenticatedSenderMessageRequest {
|
||||
|
||||
/**
|
||||
* The service identifier of the account to which to deliver the message.
|
||||
*/
|
||||
// The service identifier of the account to which to deliver the message.
|
||||
common.ServiceIdentifier destination = 1;
|
||||
|
||||
/**
|
||||
* The type identifier for this message.
|
||||
*/
|
||||
// The type identifier for this message.
|
||||
AuthenticatedSenderMessageType type = 2 [(require.specified) = true];
|
||||
|
||||
/**
|
||||
* If true, this message will only be delivered to destination devices that
|
||||
* have an active message delivery channel with a Signal server.
|
||||
*/
|
||||
// If true, this message will only be delivered to destination devices that
|
||||
// have an active message delivery channel with a Signal server.
|
||||
bool ephemeral = 3;
|
||||
|
||||
/**
|
||||
* Indicates whether this message is urgent and should trigger a high-priority
|
||||
* notification if the destination device does not have an active message
|
||||
* delivery channel with a Signal server
|
||||
*/
|
||||
// Indicates whether this message is urgent and should trigger a high-priority
|
||||
// notification if the destination device does not have an active message
|
||||
// delivery channel with a Signal server
|
||||
bool urgent = 4;
|
||||
|
||||
/**
|
||||
* The messages to send to the destination account.
|
||||
*/
|
||||
// The messages to send to the destination account.
|
||||
IndividualRecipientMessageBundle messages = 5;
|
||||
}
|
||||
|
||||
message SendSyncMessageRequest {
|
||||
|
||||
/**
|
||||
* The type identifier for this message.
|
||||
*/
|
||||
// The type identifier for this message.
|
||||
AuthenticatedSenderMessageType type = 1 [(require.specified) = true];
|
||||
|
||||
/**
|
||||
* Indicates whether this message is urgent and should trigger a high-priority
|
||||
* notification if the destination device does not have an active message
|
||||
* delivery channel with a Signal server
|
||||
*/
|
||||
// Indicates whether this message is urgent and should trigger a high-priority
|
||||
// notification if the destination device does not have an active message
|
||||
// delivery channel with a Signal server
|
||||
bool urgent = 2;
|
||||
|
||||
/**
|
||||
* The messages to send to the destination account.
|
||||
*/
|
||||
// The messages to send to the destination account.
|
||||
IndividualRecipientMessageBundle messages = 3;
|
||||
}
|
||||
|
||||
message SendSealedSenderMessageRequest {
|
||||
|
||||
/**
|
||||
* The service identifier of the account to which to deliver the message.
|
||||
*/
|
||||
// The service identifier of the account to which to deliver the message.
|
||||
common.ServiceIdentifier destination = 1;
|
||||
|
||||
/**
|
||||
* If true, this message will only be delivered to destination devices that
|
||||
* have an active message delivery channel with a Signal server.
|
||||
*/
|
||||
// If true, this message will only be delivered to destination devices that
|
||||
// have an active message delivery channel with a Signal server.
|
||||
bool ephemeral = 2;
|
||||
|
||||
/**
|
||||
* Indicates whether this message is urgent and should trigger a high-priority
|
||||
* notification if the destination device does not have an active message
|
||||
* delivery channel with a Signal server
|
||||
*/
|
||||
// Indicates whether this message is urgent and should trigger a high-priority
|
||||
// notification if the destination device does not have an active message
|
||||
// delivery channel with a Signal server
|
||||
bool urgent = 3;
|
||||
|
||||
/**
|
||||
* The messages to send to the destination account.
|
||||
*/
|
||||
// The messages to send to the destination account.
|
||||
IndividualRecipientMessageBundle messages = 4;
|
||||
|
||||
/**
|
||||
* A means to authorize the request.
|
||||
*/
|
||||
// A means to authorize the request.
|
||||
oneof authorization {
|
||||
|
||||
/**
|
||||
* The unidentified access key (UAK) for the destination account.
|
||||
*/
|
||||
// The unidentified access key (UAK) for the destination account.
|
||||
bytes unidentified_access_key = 5;
|
||||
|
||||
/**
|
||||
* A group send endorsement token for the destination account.
|
||||
*/
|
||||
// A group send endorsement token for the destination account.
|
||||
bytes group_send_token = 6;
|
||||
}
|
||||
}
|
||||
|
||||
message SendStoryMessageRequest {
|
||||
|
||||
/**
|
||||
* The service identifier of the account to which to deliver the message.
|
||||
*/
|
||||
// The service identifier of the account to which to deliver the message.
|
||||
common.ServiceIdentifier destination = 1;
|
||||
|
||||
/**
|
||||
* Indicates whether this message is urgent and should trigger a high-priority
|
||||
* notification if the destination device does not have an active message
|
||||
* delivery channel with a Signal server
|
||||
*/
|
||||
// Indicates whether this message is urgent and should trigger a high-priority
|
||||
// notification if the destination device does not have an active message
|
||||
// delivery channel with a Signal server
|
||||
bool urgent = 2;
|
||||
|
||||
/**
|
||||
* The messages to send to the destination account.
|
||||
*/
|
||||
// The messages to send to the destination account.
|
||||
IndividualRecipientMessageBundle messages = 3;
|
||||
}
|
||||
|
||||
message SendMessageResponse {
|
||||
|
||||
/**
|
||||
* An error preventing message delivery. If not set, then the message(s) in
|
||||
* the original request were sent to all destination devices.
|
||||
*/
|
||||
// An error preventing message delivery. If not set, then the message(s) in
|
||||
// the original request were sent to all destination devices.
|
||||
oneof error {
|
||||
|
||||
/**
|
||||
* A list of discrepancies between the destination devices identified in a
|
||||
* request to send a message and the devices that are actually linked to an
|
||||
* account.
|
||||
*/
|
||||
// A list of discrepancies between the destination devices identified in a
|
||||
// request to send a message and the devices that are actually linked to an
|
||||
// account.
|
||||
MismatchedDevices mismatched_devices = 1;
|
||||
|
||||
/**
|
||||
* A description of a challenge callers must complete before sending
|
||||
* additional messages.
|
||||
*/
|
||||
// A description of a challenge callers must complete before sending
|
||||
// additional messages.
|
||||
ChallengeRequired challenge_required = 2;
|
||||
}
|
||||
}
|
||||
|
||||
message MultiRecipientMessage {
|
||||
|
||||
/**
|
||||
* The time, in milliseconds since the epoch, at which this message was
|
||||
* originally sent from the perspective of the sender. Note that the maximum
|
||||
* allowable timestamp for JavaScript clients is less than Long.MAX_VALUE; see
|
||||
* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date#the_epoch_timestamps_and_invalid_date
|
||||
* for additional details and discussion.
|
||||
*/
|
||||
// The time, in milliseconds since the epoch, at which this message was
|
||||
// originally sent from the perspective of the sender. Note that the maximum
|
||||
// allowable timestamp for JavaScript clients is less than Long.MAX_VALUE; see
|
||||
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date#the_epoch_timestamps_and_invalid_date
|
||||
// for additional details and discussion.
|
||||
uint64 timestamp = 1 [(require.range).min = 1, (require.range).max = 8640000000000000];
|
||||
|
||||
/**
|
||||
* The serialized multi-recipient message payload.
|
||||
*/
|
||||
// The serialized multi-recipient message payload.
|
||||
bytes payload = 2 [(require.size).max = 762144]; // 256 KiB payload + (5000 * 100) of overhead
|
||||
}
|
||||
|
||||
message SendMultiRecipientMessageRequest {
|
||||
|
||||
/**
|
||||
* If true, this message will only be delivered to destination devices that
|
||||
* have an active message delivery channel with a Signal server.
|
||||
*/
|
||||
// If true, this message will only be delivered to destination devices that
|
||||
// have an active message delivery channel with a Signal server.
|
||||
bool ephemeral = 1;
|
||||
|
||||
/**
|
||||
* Indicates whether this message is urgent and should trigger a high-priority
|
||||
* notification if the destination device does not have an active message
|
||||
* delivery channel with a Signal server
|
||||
*/
|
||||
// Indicates whether this message is urgent and should trigger a high-priority
|
||||
// notification if the destination device does not have an active message
|
||||
// delivery channel with a Signal server
|
||||
bool urgent = 2;
|
||||
|
||||
/**
|
||||
* The multi-recipient message to send to all destination accounts and
|
||||
* devices.
|
||||
*/
|
||||
// The multi-recipient message to send to all destination accounts and
|
||||
// devices.
|
||||
MultiRecipientMessage message = 3;
|
||||
|
||||
/**
|
||||
* A group send endorsement token for the destination account.
|
||||
*/
|
||||
// A group send endorsement token for the destination account.
|
||||
bytes group_send_token = 4;
|
||||
}
|
||||
|
||||
message SendMultiRecipientStoryRequest {
|
||||
|
||||
/**
|
||||
* Indicates whether this message is urgent and should trigger a high-priority
|
||||
* notification if the destination device does not have an active message
|
||||
* delivery channel with a Signal server
|
||||
*/
|
||||
// Indicates whether this message is urgent and should trigger a high-priority
|
||||
// notification if the destination device does not have an active message
|
||||
// delivery channel with a Signal server
|
||||
bool urgent = 1;
|
||||
|
||||
/**
|
||||
* The multi-recipient story message to send to all destination accounts and
|
||||
* devices.
|
||||
*/
|
||||
// The multi-recipient story message to send to all destination accounts and
|
||||
// devices.
|
||||
MultiRecipientMessage message = 2;
|
||||
}
|
||||
|
||||
message SendMultiRecipientMessageResponse {
|
||||
|
||||
/**
|
||||
* A list of destination service identifiers that could not be resolved to
|
||||
* registered Signal accounts. If `mismatched_devices` is empty, then the
|
||||
* message in the original request was sent to all service identifiers/devices
|
||||
* in the original request except for the destination devices associated with
|
||||
* the service identifiers in this list.
|
||||
*/
|
||||
// A list of destination service identifiers that could not be resolved to
|
||||
// registered Signal accounts. If `mismatched_devices` is empty, then the
|
||||
// message in the original request was sent to all service identifiers/devices
|
||||
// in the original request except for the destination devices associated with
|
||||
// the service identifiers in this list.
|
||||
repeated common.ServiceIdentifier unresolved_recipients = 1;
|
||||
|
||||
/**
|
||||
* An error preventing message delivery. If not set, then the message was sent
|
||||
* to some or all destination accounts/devices identified in the original
|
||||
* request.
|
||||
*/
|
||||
// An error preventing message delivery. If not set, then the message was sent
|
||||
// to some or all destination accounts/devices identified in the original
|
||||
// request.
|
||||
oneof error {
|
||||
|
||||
/**
|
||||
* A list of sets of discrepancies between the destination devices
|
||||
* identified in a request to send a message and the devices that are
|
||||
* actually linked to a destination account.
|
||||
*/
|
||||
// A list of sets of discrepancies between the destination devices
|
||||
// identified in a request to send a message and the devices that are
|
||||
// actually linked to a destination account.
|
||||
MultiRecipientMismatchedDevices mismatched_devices = 2;
|
||||
|
||||
/**
|
||||
* A description of a challenge callers must complete before sending
|
||||
* additional messages.
|
||||
*/
|
||||
// A description of a challenge callers must complete before sending
|
||||
// additional messages.
|
||||
ChallengeRequired challenge_required = 3;
|
||||
}
|
||||
}
|
||||
|
||||
message MismatchedDevices {
|
||||
|
||||
/**
|
||||
* The service identifier to which the devices named in this object are
|
||||
* linked.
|
||||
*/
|
||||
// The service identifier to which the devices named in this object are
|
||||
// linked.
|
||||
common.ServiceIdentifier service_identifier = 1;
|
||||
|
||||
/**
|
||||
* A list of device IDs that are linked to the destination account, but were
|
||||
* not included in the collection of messages bound for the destination
|
||||
* account.
|
||||
*/
|
||||
// A list of device IDs that are linked to the destination account, but were
|
||||
// not included in the collection of messages bound for the destination
|
||||
// account.
|
||||
repeated uint32 missing_devices = 2 [(require.range).max = 0x7f];
|
||||
|
||||
/**
|
||||
* A list of device IDs that were included in the collection of messages bound
|
||||
* for the destination account, but are not currently linked to the
|
||||
* destination account.
|
||||
*/
|
||||
// A list of device IDs that were included in the collection of messages bound
|
||||
// for the destination account, but are not currently linked to the
|
||||
// destination account.
|
||||
repeated uint32 extra_devices = 3 [(require.range).max = 0x7f];
|
||||
|
||||
/**
|
||||
* A list of device IDs that present in the collection of messages bound for
|
||||
* the destination account and are linked to the destination account, but have
|
||||
* a different registration ID than the registration ID presented by the
|
||||
* sender (indicating that the destination device has likely been replaced by
|
||||
* another device).
|
||||
*/
|
||||
// A list of device IDs that present in the collection of messages bound for
|
||||
// the destination account and are linked to the destination account, but have
|
||||
// a different registration ID than the registration ID presented by the
|
||||
// sender (indicating that the destination device has likely been replaced by
|
||||
// another device).
|
||||
repeated uint32 stale_devices = 4 [(require.range).max = 0x7f];
|
||||
}
|
||||
|
||||
message MultiRecipientMismatchedDevices {
|
||||
|
||||
/**
|
||||
* A list of sets of discrepancies between the destination devices identified
|
||||
* in a request to send a message and the devices that are actually linked to
|
||||
* a destination account.
|
||||
*/
|
||||
// A list of sets of discrepancies between the destination devices identified
|
||||
// in a request to send a message and the devices that are actually linked to
|
||||
// a destination account.
|
||||
repeated MismatchedDevices mismatched_devices = 1;
|
||||
}
|
||||
|
||||
@@ -468,35 +360,25 @@ message ChallengeRequired {
|
||||
enum ChallengeType {
|
||||
UNSPECIFIED = 0;
|
||||
|
||||
/**
|
||||
* A challenge that callers can fulfill by completing a captcha.
|
||||
*/
|
||||
// A challenge that callers can fulfill by completing a captcha.
|
||||
CAPTCHA = 1;
|
||||
|
||||
/**
|
||||
* A challenge that callers can fulfill by supplying a token delivered via
|
||||
* push notification.
|
||||
*/
|
||||
// A challenge that callers can fulfill by supplying a token delivered via
|
||||
// push notification.
|
||||
PUSH_CHALLENGE = 2;
|
||||
};
|
||||
|
||||
/**
|
||||
* An opaque token identifying this challenge request. Clients must generally
|
||||
* submit this token when submitting a challenge response.
|
||||
*/
|
||||
// An opaque token identifying this challenge request. Clients must generally
|
||||
// submit this token when submitting a challenge response.
|
||||
bytes token = 1;
|
||||
|
||||
/**
|
||||
* A list of challenge types callers may choose to complete to resolve the
|
||||
* challenge requirement. May be empty, in which case callers cannot resolve
|
||||
* the challenge by any means other than waiting.
|
||||
*/
|
||||
// A list of challenge types callers may choose to complete to resolve the
|
||||
// challenge requirement. May be empty, in which case callers cannot resolve
|
||||
// the challenge by any means other than waiting.
|
||||
repeated ChallengeType challenge_options = 2;
|
||||
|
||||
/**
|
||||
* A duration (in seconds) after which the challenge requirement may be
|
||||
* resolved by simply waiting. May not be set if the challenge cannot be
|
||||
* resolved by waiting.
|
||||
*/
|
||||
// A duration (in seconds) after which the challenge requirement may be
|
||||
// resolved by simply waiting. May not be set if the challenge cannot be
|
||||
// resolved by waiting.
|
||||
optional uint64 retry_after_seconds = 3;
|
||||
}
|
||||
@@ -9,12 +9,9 @@ option java_multiple_files = true;
|
||||
|
||||
package org.signal.chat.payments;
|
||||
|
||||
/**
|
||||
* Provides methods for working with payments.
|
||||
*/
|
||||
// Provides methods for working with payments.
|
||||
service Payments {
|
||||
/**
|
||||
*/
|
||||
|
||||
rpc GetCurrencyConversions(GetCurrencyConversionsRequest) returns (GetCurrencyConversionsResponse) {}
|
||||
}
|
||||
|
||||
|
||||
@@ -11,90 +11,72 @@ package org.signal.chat.profile;
|
||||
|
||||
import "org/signal/chat/common.proto";
|
||||
|
||||
/**
|
||||
* Provides methods for working with profiles and profile-related data.
|
||||
*/
|
||||
// Provides methods for working with profiles and profile-related data.
|
||||
service Profile {
|
||||
/**
|
||||
* Sets profile data and if needed, returns S3 credentials used by clients to upload an avatar.
|
||||
*
|
||||
* This RPC may fail with `PERMISSION_DENIED` if it attempts to set the MobileCoin wallet ID
|
||||
* on an account whose profile does not currently have a MobileCoin wallet ID and
|
||||
* whose phone number contains a disallowed country prefix.
|
||||
*/
|
||||
// Sets profile data and if needed, returns S3 credentials used by clients to upload an avatar.
|
||||
//
|
||||
// This RPC may fail with `PERMISSION_DENIED` if it attempts to set the MobileCoin wallet ID
|
||||
// on an account whose profile does not currently have a MobileCoin wallet ID and
|
||||
// whose phone number contains a disallowed country prefix.
|
||||
rpc SetProfile(SetProfileRequest) returns (SetProfileResponse) {}
|
||||
|
||||
/**
|
||||
* Retrieves versioned profile data. Callers with an unidentified access key for the account
|
||||
* should use the version of this method in `ProfileAnonymous` instead.
|
||||
*
|
||||
* This RPC may fail with a `NOT_FOUND` status if the target account was not
|
||||
* found. It may fail with a `RESOURCE_EXHAUSTED` if a rate limit for fetching profiles has been
|
||||
* exceeded, in which case a `retry-after` header containing an ISO 8601
|
||||
* duration string will be present in the response trailers.
|
||||
*/
|
||||
// Retrieves versioned profile data. Callers with an unidentified access key for the account
|
||||
// should use the version of this method in `ProfileAnonymous` instead.
|
||||
//
|
||||
// This RPC may fail with a `NOT_FOUND` status if the target account was not
|
||||
// found. It may fail with a `RESOURCE_EXHAUSTED` if a rate limit for fetching profiles has been
|
||||
// exceeded, in which case a `retry-after` header containing an ISO 8601
|
||||
// duration string will be present in the response trailers.
|
||||
rpc GetVersionedProfile(GetVersionedProfileRequest) returns (GetVersionedProfileResponse) {}
|
||||
|
||||
/**
|
||||
* Retrieves unversioned profile data. Callers with an unidentified access key for the account
|
||||
* should use the version of this method in `ProfileAnonymous` instead.
|
||||
*
|
||||
* This RPC may fail with a `NOT_FOUND` status if the target account was not
|
||||
* found. It may fail with a `RESOURCE_EXHAUSTED` if a rate limit for fetching profiles has been
|
||||
* exceeded, in which case a `retry-after` header containing an ISO 8601
|
||||
* duration string will be present in the response trailers.
|
||||
*/
|
||||
// Retrieves unversioned profile data. Callers with an unidentified access key for the account
|
||||
// should use the version of this method in `ProfileAnonymous` instead.
|
||||
//
|
||||
// This RPC may fail with a `NOT_FOUND` status if the target account was not
|
||||
// found. It may fail with a `RESOURCE_EXHAUSTED` if a rate limit for fetching profiles has been
|
||||
// exceeded, in which case a `retry-after` header containing an ISO 8601
|
||||
// duration string will be present in the response trailers.
|
||||
rpc GetUnversionedProfile(GetUnversionedProfileRequest) returns (GetUnversionedProfileResponse) {}
|
||||
|
||||
/**
|
||||
* Retrieves a profile key credential.
|
||||
* Callers with an unidentified access key for the account
|
||||
* should use the version of this method in `ProfileAnonymous` instead.
|
||||
*
|
||||
* This RPC may fail with a `NOT_FOUND` status if the target account was not
|
||||
* found. It may fail with a `RESOURCE_EXHAUSTED` if a rate limit for fetching profiles has been
|
||||
* exceeded, in which case a `retry-after` header containing an ISO 8601
|
||||
* duration string will be present in the response trailers. It may also fail with an
|
||||
* `INVALID_ARGUMENT` status if the given credential type is invalid.
|
||||
*/
|
||||
// Retrieves a profile key credential.
|
||||
// Callers with an unidentified access key for the account
|
||||
// should use the version of this method in `ProfileAnonymous` instead.
|
||||
//
|
||||
// This RPC may fail with a `NOT_FOUND` status if the target account was not
|
||||
// found. It may fail with a `RESOURCE_EXHAUSTED` if a rate limit for fetching profiles has been
|
||||
// exceeded, in which case a `retry-after` header containing an ISO 8601
|
||||
// duration string will be present in the response trailers. It may also fail with an
|
||||
// `INVALID_ARGUMENT` status if the given credential type is invalid.
|
||||
rpc GetExpiringProfileKeyCredential(GetExpiringProfileKeyCredentialRequest) returns (GetExpiringProfileKeyCredentialResponse) {}
|
||||
}
|
||||
|
||||
/**
|
||||
* Provides methods for working with profiles and profile-related data using "unidentified access"
|
||||
* credentials. Callers must not submit any self-identifying credentials
|
||||
* when calling methods in this service and must instead present the targeted account's
|
||||
* unidentified access key as an anonymous authentication mechanism. Callers
|
||||
* without an unidentified access key should use the equivalent, authenticated
|
||||
* methods in `Profile` instead.
|
||||
*/
|
||||
// Provides methods for working with profiles and profile-related data using "unidentified access"
|
||||
// credentials. Callers must not submit any self-identifying credentials
|
||||
// when calling methods in this service and must instead present the targeted account's
|
||||
// unidentified access key as an anonymous authentication mechanism. Callers
|
||||
// without an unidentified access key should use the equivalent, authenticated
|
||||
// methods in `Profile` instead.
|
||||
service ProfileAnonymous {
|
||||
/**
|
||||
* Retrieves versioned profile data.
|
||||
*
|
||||
* This RPC may fail with a `NOT_FOUND` status if the target account was not
|
||||
* found. It may also fail with an `UNAUTHENTICATED` status if the given
|
||||
* unidentified access key did not match the target account's unidentified
|
||||
* access key.
|
||||
*/
|
||||
// Retrieves versioned profile data.
|
||||
//
|
||||
// This RPC may fail with a `NOT_FOUND` status if the target account was not
|
||||
// found. It may also fail with an `UNAUTHENTICATED` status if the given
|
||||
// unidentified access key did not match the target account's unidentified
|
||||
// access key.
|
||||
rpc GetVersionedProfile(GetVersionedProfileAnonymousRequest) returns (GetVersionedProfileResponse) {}
|
||||
/**
|
||||
* Retrieves unversioned profile data.
|
||||
*
|
||||
* This RPC may fail with a `NOT_FOUND` status if the target account was not
|
||||
* found. It may also fail with an `UNAUTHENTICATED` status if the given
|
||||
* unidentified access key did not match the target account's unidentified
|
||||
* access key.
|
||||
*/
|
||||
// Retrieves unversioned profile data.
|
||||
//
|
||||
// This RPC may fail with a `NOT_FOUND` status if the target account was not
|
||||
// found. It may also fail with an `UNAUTHENTICATED` status if the given
|
||||
// unidentified access key did not match the target account's unidentified
|
||||
// access key.
|
||||
rpc GetUnversionedProfile(GetUnversionedProfileAnonymousRequest) returns (GetUnversionedProfileResponse) {}
|
||||
/**
|
||||
* Retrieves a profile key credential.
|
||||
*
|
||||
* This RPC may fail with a `NOT_FOUND` status if the target account was not
|
||||
* found. It may also fail with an `UNAUTHENTICATED` status if the given
|
||||
* unidentified access key did not match the target account's unidentified
|
||||
* access key, or an `INVALID_ARGUMENT` status if the given credential type is invalid.
|
||||
*/
|
||||
// Retrieves a profile key credential.
|
||||
//
|
||||
// This RPC may fail with a `NOT_FOUND` status if the target account was not
|
||||
// found. It may also fail with an `UNAUTHENTICATED` status if the given
|
||||
// unidentified access key did not match the target account's unidentified
|
||||
// access key, or an `INVALID_ARGUMENT` status if the given credential type is invalid.
|
||||
rpc GetExpiringProfileKeyCredential(GetExpiringProfileKeyCredentialAnonymousRequest) returns (GetExpiringProfileKeyCredentialResponse) {}
|
||||
}
|
||||
|
||||
@@ -104,258 +86,154 @@ message SetProfileRequest {
|
||||
AVATAR_CHANGE_CLEAR = 1;
|
||||
AVATAR_CHANGE_UPDATE = 2;
|
||||
}
|
||||
/**
|
||||
* The profile version. Must be set.
|
||||
*/
|
||||
// The profile version. Must be set.
|
||||
string version = 1;
|
||||
/**
|
||||
* The ciphertext of a name that users must set on the profile.
|
||||
*/
|
||||
// The ciphertext of a name that users must set on the profile.
|
||||
bytes name = 2;
|
||||
/**
|
||||
* An enum to indicate what change, if any, is made to the avatar with this request.
|
||||
*/
|
||||
// An enum to indicate what change, if any, is made to the avatar with this request.
|
||||
AvatarChange avatarChange = 3;
|
||||
/**
|
||||
* The ciphertext of an emoji that users can set on their profile.
|
||||
*/
|
||||
// The ciphertext of an emoji that users can set on their profile.
|
||||
bytes about_emoji = 4;
|
||||
/**
|
||||
* The ciphertext of a description that users can set on their profile.
|
||||
*/
|
||||
// The ciphertext of a description that users can set on their profile.
|
||||
bytes about = 5;
|
||||
/**
|
||||
* The ciphertext of the MobileCoin wallet ID on the profile.
|
||||
*/
|
||||
// The ciphertext of the MobileCoin wallet ID on the profile.
|
||||
bytes payment_address = 6;
|
||||
/**
|
||||
* A list of badge IDs associated with the profile.
|
||||
*/
|
||||
// A list of badge IDs associated with the profile.
|
||||
repeated string badge_ids = 7;
|
||||
/**
|
||||
* The ciphertext of the phone-number sharing setting on the profile. 29-byte encrypted boolean.
|
||||
*/
|
||||
// The ciphertext of the phone-number sharing setting on the profile. 29-byte encrypted boolean.
|
||||
bytes phone_number_sharing = 8;
|
||||
/**
|
||||
* The profile key commitment. Used to issue a profile key credential response.
|
||||
* Must be set on the request.
|
||||
*/
|
||||
// The profile key commitment. Used to issue a profile key credential response.
|
||||
// Must be set on the request.
|
||||
bytes commitment = 9;
|
||||
}
|
||||
|
||||
message SetProfileResponse {
|
||||
/**
|
||||
* The policy and credential used by clients to upload an avatar to S3.
|
||||
*/
|
||||
// The policy and credential used by clients to upload an avatar to S3.
|
||||
ProfileAvatarUploadAttributes attributes = 1;
|
||||
}
|
||||
|
||||
message GetVersionedProfileRequest {
|
||||
/**
|
||||
* The ACI of the account for which to get profile data.
|
||||
*/
|
||||
// The ACI of the account for which to get profile data.
|
||||
common.ServiceIdentifier accountIdentifier = 1;
|
||||
/**
|
||||
* The profile version to retrieve.
|
||||
*/
|
||||
// The profile version to retrieve.
|
||||
string version = 2;
|
||||
}
|
||||
|
||||
message GetVersionedProfileAnonymousRequest {
|
||||
/**
|
||||
* Contains the data necessary to request a versioned profile.
|
||||
*/
|
||||
// Contains the data necessary to request a versioned profile.
|
||||
GetVersionedProfileRequest request = 1;
|
||||
/**
|
||||
* The unidentified access key for the targeted account.
|
||||
*/
|
||||
// The unidentified access key for the targeted account.
|
||||
bytes unidentified_access_key = 2;
|
||||
}
|
||||
|
||||
message GetVersionedProfileResponse {
|
||||
/**
|
||||
* The ciphertext of the name on the profile.
|
||||
*/
|
||||
// The ciphertext of the name on the profile.
|
||||
bytes name = 1;
|
||||
/**
|
||||
* The ciphertext of the description on the profile.
|
||||
*/
|
||||
// The ciphertext of the description on the profile.
|
||||
bytes about = 2;
|
||||
/**
|
||||
* The ciphertext of the emoji on the profile.
|
||||
*/
|
||||
// The ciphertext of the emoji on the profile.
|
||||
bytes about_emoji = 3;
|
||||
/**
|
||||
* The S3 path of the avatar on the profile.
|
||||
*/
|
||||
// The S3 path of the avatar on the profile.
|
||||
string avatar = 4;
|
||||
/**
|
||||
* The ciphertext of the MobileCoin wallet ID on the profile.
|
||||
*/
|
||||
// The ciphertext of the MobileCoin wallet ID on the profile.
|
||||
bytes payment_address = 5;
|
||||
/**
|
||||
* The ciphertext of the phone-number sharing setting on the profile.
|
||||
*/
|
||||
// The ciphertext of the phone-number sharing setting on the profile.
|
||||
bytes phone_number_sharing = 6;
|
||||
}
|
||||
|
||||
message GetUnversionedProfileRequest {
|
||||
/**
|
||||
* The service identifier of the account for which to get profile data.
|
||||
*/
|
||||
// The service identifier of the account for which to get profile data.
|
||||
common.ServiceIdentifier serviceIdentifier = 1;
|
||||
}
|
||||
|
||||
message GetUnversionedProfileAnonymousRequest {
|
||||
/**
|
||||
* Contains the data necessary to request an unversioned profile.
|
||||
*/
|
||||
// Contains the data necessary to request an unversioned profile.
|
||||
GetUnversionedProfileRequest request = 1;
|
||||
|
||||
oneof authentication {
|
||||
/**
|
||||
* The unidentified access key for the targeted account.
|
||||
*/
|
||||
// The unidentified access key for the targeted account.
|
||||
bytes unidentified_access_key = 2;
|
||||
|
||||
/**
|
||||
* A group send endorsement token for the targeted account.
|
||||
*/
|
||||
// A group send endorsement token for the targeted account.
|
||||
bytes group_send_token = 3;
|
||||
}
|
||||
}
|
||||
|
||||
message GetUnversionedProfileResponse {
|
||||
/**
|
||||
* The identity key of the targeted account/identity type.
|
||||
*/
|
||||
// The identity key of the targeted account/identity type.
|
||||
bytes identity_key = 1;
|
||||
/**
|
||||
* A checksum of the unidentified access key for the targeted account.
|
||||
*/
|
||||
// A checksum of the unidentified access key for the targeted account.
|
||||
bytes unidentified_access = 2;
|
||||
/**
|
||||
* Whether the account has enabled sealed sender from anyone.
|
||||
*/
|
||||
// Whether the account has enabled sealed sender from anyone.
|
||||
bool unrestricted_unidentified_access = 3;
|
||||
/**
|
||||
* A list of capabilities enabled on the account.
|
||||
*/
|
||||
// A list of capabilities enabled on the account.
|
||||
repeated common.DeviceCapability capabilities = 4;
|
||||
/**
|
||||
* A list of badges associated with the account.
|
||||
*/
|
||||
// A list of badges associated with the account.
|
||||
repeated Badge badges = 5;
|
||||
}
|
||||
|
||||
message GetExpiringProfileKeyCredentialRequest {
|
||||
/**
|
||||
* The ACI of the account for which to get a profile key credential.
|
||||
*/
|
||||
// The ACI of the account for which to get a profile key credential.
|
||||
common.ServiceIdentifier accountIdentifier = 1;
|
||||
/**
|
||||
* A zkgroup request for a profile key credential.
|
||||
*/
|
||||
// A zkgroup request for a profile key credential.
|
||||
bytes credential_request = 2;
|
||||
/**
|
||||
* The type of credential being requested.
|
||||
*/
|
||||
// The type of credential being requested.
|
||||
CredentialType credential_type = 3;
|
||||
/**
|
||||
* The profile version for which to generate a profile key credential.
|
||||
*/
|
||||
// The profile version for which to generate a profile key credential.
|
||||
string version = 4;
|
||||
}
|
||||
|
||||
message GetExpiringProfileKeyCredentialAnonymousRequest {
|
||||
/**
|
||||
* Contains the data necessary to request an expiring profile key credential.
|
||||
*/
|
||||
// Contains the data necessary to request an expiring profile key credential.
|
||||
GetExpiringProfileKeyCredentialRequest request = 1;
|
||||
/**
|
||||
* The unidentified access key for the targeted account.
|
||||
*/
|
||||
// The unidentified access key for the targeted account.
|
||||
bytes unidentified_access_key = 2;
|
||||
}
|
||||
|
||||
message GetExpiringProfileKeyCredentialResponse {
|
||||
/**
|
||||
* A zkgroup credential used by a client to prove that it has the profile key
|
||||
* of a targeted account.
|
||||
*/
|
||||
// A zkgroup credential used by a client to prove that it has the profile key
|
||||
// of a targeted account.
|
||||
bytes profileKeyCredential = 1;
|
||||
}
|
||||
|
||||
message ProfileAvatarUploadAttributes {
|
||||
/**
|
||||
* The S3 upload path for the profile's avatar.
|
||||
*/
|
||||
// The S3 upload path for the profile's avatar.
|
||||
string path = 1;
|
||||
/**
|
||||
* A scoped credential. Includes the AWS access key, date, region targeted, and AWS service.
|
||||
*/
|
||||
// A scoped credential. Includes the AWS access key, date, region targeted, and AWS service.
|
||||
string credential = 2;
|
||||
/**
|
||||
* The type of access control for the avatar object.
|
||||
*/
|
||||
// The type of access control for the avatar object.
|
||||
string acl = 3;
|
||||
/**
|
||||
* The algorithm used to calculate a signature on the S3 policy.
|
||||
*/
|
||||
// The algorithm used to calculate a signature on the S3 policy.
|
||||
string algorithm = 4;
|
||||
/**
|
||||
* The timestamp at which the S3 policy and signature were generated.
|
||||
*/
|
||||
// The timestamp at which the S3 policy and signature were generated.
|
||||
string date = 5;
|
||||
/**
|
||||
* The S3 policy used to upload the avatar object.
|
||||
*/
|
||||
// The S3 policy used to upload the avatar object.
|
||||
string policy = 6;
|
||||
/**
|
||||
* A digital signature on the S3 policy.
|
||||
*/
|
||||
// A digital signature on the S3 policy.
|
||||
bytes signature = 7;
|
||||
}
|
||||
|
||||
message Badge {
|
||||
/**
|
||||
* An ID that uniquely identifies the badge.
|
||||
*/
|
||||
// An ID that uniquely identifies the badge.
|
||||
string id = 1;
|
||||
/**
|
||||
* The category the badge falls in ("donor" or "other").
|
||||
*/
|
||||
// The category the badge falls in ("donor" or "other").
|
||||
string category = 2;
|
||||
/**
|
||||
* The badge name.
|
||||
*/
|
||||
// The badge name.
|
||||
string name = 3;
|
||||
/**
|
||||
* The badge description.
|
||||
*/
|
||||
// The badge description.
|
||||
string description = 4;
|
||||
/**
|
||||
* Different size badge SVG files.
|
||||
*/
|
||||
// Different size badge SVG files.
|
||||
repeated string sprites6 = 5;
|
||||
/**
|
||||
* File name of the scalable vector graphic representing this badge.
|
||||
*/
|
||||
// File name of the scalable vector graphic representing this badge.
|
||||
string svg = 6;
|
||||
/**
|
||||
* Pairs of light/dark SVG files designed for display at different sizes.
|
||||
*/
|
||||
// Pairs of light/dark SVG files designed for display at different sizes.
|
||||
repeated BadgeSvg svgs = 7;
|
||||
}
|
||||
|
||||
message BadgeSvg {
|
||||
/**
|
||||
* File name of the scalable vector graphic for light mode.
|
||||
*/
|
||||
// File name of the scalable vector graphic for light mode.
|
||||
string light = 1;
|
||||
/**
|
||||
* File name of the scalable vector graphic for dark mode.
|
||||
*/
|
||||
// File name of the scalable vector graphic for dark mode.
|
||||
string dark = 2;
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
/*
|
||||
* Copyright 2025 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
syntax = "proto3";
|
||||
|
||||
option java_multiple_files = true;
|
||||
|
||||
package org.signal.chat.tag;
|
||||
|
||||
import "google/protobuf/descriptor.proto";
|
||||
|
||||
extend google.protobuf.FieldOptions {
|
||||
// Indicate that a message which includes this field (directly or indirectly)
|
||||
// was generated for a particular reason.
|
||||
//
|
||||
// ```
|
||||
// import "org/signal/chat/tag.proto"
|
||||
//
|
||||
// message LookupThingResponse {
|
||||
// oneof response {
|
||||
// string thing = 1;
|
||||
// Error not_found = 2 [(tag.reason) = "not_found"];
|
||||
// Error forbidden = 3 [(tag.reason) = "forbidden"];
|
||||
// }
|
||||
// }
|
||||
// ```
|
||||
//
|
||||
// Metrics middleware may then inspect `LookupThingResponse` and tag responses
|
||||
// with the provided reason. This is useful when multiple outcomes are
|
||||
// potentially represented with a status = "OK" RPC response.
|
||||
//
|
||||
// Valid messages should only have a single reason set. If a message has
|
||||
// multiple fields present that have a reason option set, no guarantees are
|
||||
// made about the reason that is selected.
|
||||
optional string reason = 71000;
|
||||
}
|
||||
+53
-12
@@ -5,47 +5,88 @@
|
||||
|
||||
package org.whispersystems.textsecuregcm.auth;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
import com.google.i18n.phonenumbers.PhoneNumberUtil;
|
||||
import java.io.IOException;
|
||||
import java.security.InvalidKeyException;
|
||||
import java.util.Base64;
|
||||
import java.util.UUID;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
import org.junitpioneer.jupiter.cartesian.CartesianTest;
|
||||
import org.signal.libsignal.protocol.IdentityKey;
|
||||
import org.signal.libsignal.protocol.ecc.ECPrivateKey;
|
||||
import org.signal.libsignal.protocol.ecc.ECPublicKey;
|
||||
import org.whispersystems.textsecuregcm.entities.MessageProtos.SenderCertificate;
|
||||
import org.whispersystems.textsecuregcm.entities.MessageProtos.ServerCertificate;
|
||||
import org.whispersystems.textsecuregcm.identity.IdentityType;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.util.UUIDUtil;
|
||||
|
||||
class CertificateGeneratorTest {
|
||||
|
||||
private static final String SIGNING_CERTIFICATE = "CiUIDBIhBbTz4h1My+tt+vw+TVscgUe/DeHS0W02tPWAWbTO2xc3EkD+go4bJnU0AcnFfbOLKoiBfCzouZtDYMOVi69rE7r4U9cXREEqOkUmU2WJBjykAxWPCcSTmVTYHDw7hkSp/puG";
|
||||
private static final String SIGNING_KEY = "ABOxG29xrfq4E7IrW11Eg7+HBbtba9iiS0500YoBjn4=";
|
||||
private static final byte[] SIGNING_CERTIFICATE_DATA;
|
||||
// This arbitrary test ID is embedded in the serialized certificate
|
||||
private static final int SIGNING_CERTIFICATE_ID = 12;
|
||||
private static final ECPrivateKey SIGNING_KEY;
|
||||
private static final IdentityKey IDENTITY_KEY;
|
||||
private static final UUID ACI = UUID.randomUUID();
|
||||
private static final String E164 = PhoneNumberUtil.getInstance()
|
||||
.format(PhoneNumberUtil.getInstance().getExampleNumber("US"), PhoneNumberUtil.PhoneNumberFormat.E164);
|
||||
|
||||
static {
|
||||
try {
|
||||
SIGNING_CERTIFICATE_DATA = Base64.getDecoder().decode("CiUIDBIhBbTz4h1My+tt+vw+TVscgUe/DeHS0W02tPWAWbTO2xc3EkD+go4bJnU0AcnFfbOLKoiBfCzouZtDYMOVi69rE7r4U9cXREEqOkUmU2WJBjykAxWPCcSTmVTYHDw7hkSp/puG");
|
||||
SIGNING_KEY = new ECPrivateKey(Base64.getDecoder().decode("ABOxG29xrfq4E7IrW11Eg7+HBbtba9iiS0500YoBjn4="));
|
||||
IDENTITY_KEY = new IdentityKey(Base64.getDecoder().decode("BcxxDU9FGMda70E7+Uvm7pnQcEdXQ64aJCpPUeRSfcFo"));
|
||||
} catch (org.signal.libsignal.protocol.InvalidKeyException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void testCreateFor() throws IOException, InvalidKeyException, org.signal.libsignal.protocol.InvalidKeyException {
|
||||
@CartesianTest
|
||||
@ValueSource(booleans = {true, false})
|
||||
void testCreateFor(@CartesianTest.Values(booleans = {true, false}) boolean includeE164,
|
||||
@CartesianTest.Values(booleans = {true, false}) boolean embedSigner)
|
||||
throws IOException, org.signal.libsignal.protocol.InvalidKeyException {
|
||||
final Account account = mock(Account.class);
|
||||
final byte deviceId = 4;
|
||||
final CertificateGenerator certificateGenerator = new CertificateGenerator(
|
||||
Base64.getDecoder().decode(SIGNING_CERTIFICATE),
|
||||
new ECPrivateKey(Base64.getDecoder().decode(SIGNING_KEY)), 1);
|
||||
SIGNING_CERTIFICATE_DATA, SIGNING_KEY, 1, embedSigner);
|
||||
|
||||
when(account.getIdentityKey(IdentityType.ACI)).thenReturn(IDENTITY_KEY);
|
||||
when(account.getUuid()).thenReturn(UUID.randomUUID());
|
||||
when(account.getNumber()).thenReturn("+18005551234");
|
||||
when(account.getUuid()).thenReturn(ACI);
|
||||
when(account.getNumber()).thenReturn(E164);
|
||||
|
||||
assertTrue(certificateGenerator.createFor(account, deviceId, true).length > 0);
|
||||
assertTrue(certificateGenerator.createFor(account, deviceId, false).length > 0);
|
||||
final byte[] contents = certificateGenerator.createFor(account, deviceId, includeE164);
|
||||
final SenderCertificate fullCertificate = SenderCertificate.parseFrom(contents);
|
||||
final SenderCertificate.Certificate certificate = SenderCertificate.Certificate.parseFrom(fullCertificate.getCertificate());
|
||||
assertEquals(deviceId, certificate.getSenderDevice());
|
||||
assertEquals(UUIDUtil.toByteString(ACI), certificate.getSenderUuid());
|
||||
assertEquals(includeE164 ? E164 : "", certificate.getSenderE164());
|
||||
assertArrayEquals(IDENTITY_KEY.serialize(), certificate.getIdentityKey().toByteArray());
|
||||
assertTrue(certificate.getExpires() > 0);
|
||||
|
||||
final ECPublicKey signingKey;
|
||||
if (embedSigner) {
|
||||
// Make sure we can produce certificates with embedded signers, in case of a future rotation
|
||||
assertFalse(certificate.hasSignerId());
|
||||
assertArrayEquals(SIGNING_CERTIFICATE_DATA, certificate.getSignerCertificate().toByteArray());
|
||||
|
||||
final byte[] signingKeyBytes = ServerCertificate.Certificate.parseFrom(
|
||||
certificate.getSignerCertificate().getCertificate()).getKey().toByteArray();
|
||||
signingKey = new ECPublicKey(signingKeyBytes);
|
||||
} else {
|
||||
assertFalse(certificate.hasSignerCertificate());
|
||||
assertEquals(SIGNING_CERTIFICATE_ID, certificate.getSignerId());
|
||||
signingKey = SIGNING_KEY.publicKey();
|
||||
}
|
||||
|
||||
assertTrue(signingKey
|
||||
.verifySignature(fullCertificate.getCertificate().toByteArray(), fullCertificate.getSignature().toByteArray()));
|
||||
}
|
||||
}
|
||||
+3
-3
@@ -15,9 +15,9 @@ import org.whispersystems.textsecuregcm.grpc.EchoServiceImpl;
|
||||
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
|
||||
class ProhibitAuthenticationInterceptorTest {
|
||||
private Server server;
|
||||
@@ -53,7 +53,7 @@ class ProhibitAuthenticationInterceptorTest {
|
||||
|
||||
final StatusRuntimeException e = assertThrows(StatusRuntimeException.class,
|
||||
() -> client.echo(EchoRequest.getDefaultInstance()));
|
||||
assertEquals(e.getStatus().getCode(), Status.Code.UNAUTHENTICATED);
|
||||
assertEquals(Status.Code.INVALID_ARGUMENT, e.getStatus().getCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
+4
-5
@@ -1,7 +1,7 @@
|
||||
package org.whispersystems.textsecuregcm.auth.grpc;
|
||||
|
||||
import static org.junit.Assert.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.mock;
|
||||
@@ -18,7 +18,6 @@ import java.time.Instant;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import org.junit.Assert;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
@@ -72,7 +71,7 @@ class RequireAuthenticationInterceptorTest {
|
||||
|
||||
final GetAuthenticatedDeviceResponse authenticatedDevice = client.getAuthenticatedDevice(
|
||||
GetAuthenticatedDeviceRequest.getDefaultInstance());
|
||||
assertEquals(authenticatedDevice.getDeviceId(), deviceId);
|
||||
assertEquals(deviceId, authenticatedDevice.getDeviceId());
|
||||
assertEquals(UUIDUtil.fromByteString(authenticatedDevice.getAccountIdentifier()), aci);
|
||||
}
|
||||
|
||||
@@ -86,7 +85,7 @@ class RequireAuthenticationInterceptorTest {
|
||||
|
||||
final StatusRuntimeException e = assertThrows(StatusRuntimeException.class,
|
||||
() -> client.getRequestAttributes(GetRequestAttributesRequest.getDefaultInstance()));
|
||||
Assert.assertEquals(e.getStatus().getCode(), Status.Code.UNAUTHENTICATED);
|
||||
assertEquals(Status.Code.UNAUTHENTICATED, e.getStatus().getCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -97,6 +96,6 @@ class RequireAuthenticationInterceptorTest {
|
||||
|
||||
final StatusRuntimeException e = assertThrows(StatusRuntimeException.class,
|
||||
() -> client.getRequestAttributes(GetRequestAttributesRequest.getDefaultInstance()));
|
||||
Assert.assertEquals(e.getStatus().getCode(), Status.Code.UNAUTHENTICATED);
|
||||
assertEquals(Status.Code.UNAUTHENTICATED, e.getStatus().getCode());
|
||||
}
|
||||
}
|
||||
+74
-92
@@ -6,12 +6,12 @@
|
||||
package org.whispersystems.textsecuregcm.backup;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatException;
|
||||
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.anyLong;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.doThrow;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.reset;
|
||||
@@ -20,8 +20,6 @@ import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.verifyNoInteractions;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
import io.grpc.Status;
|
||||
import io.grpc.StatusRuntimeException;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.time.temporal.ChronoUnit;
|
||||
@@ -64,7 +62,6 @@ import org.whispersystems.textsecuregcm.storage.AccountsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.Device;
|
||||
import org.whispersystems.textsecuregcm.storage.RedeemedReceiptsManager;
|
||||
import org.whispersystems.textsecuregcm.tests.util.ExperimentHelper;
|
||||
import org.whispersystems.textsecuregcm.util.CompletableFutureTestUtil;
|
||||
import org.whispersystems.textsecuregcm.util.TestClock;
|
||||
import org.whispersystems.textsecuregcm.util.TestRandomUtil;
|
||||
|
||||
@@ -107,19 +104,18 @@ public class BackupAuthManagerTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
void commitBackupId() {
|
||||
void commitBackupId() throws RateLimitExceededException, BackupInvalidArgumentException, BackupPermissionException {
|
||||
final BackupAuthManager authManager = create();
|
||||
|
||||
final Account account = mock(Account.class);
|
||||
when(account.getUuid()).thenReturn(aci);
|
||||
when(accountsManager.updateAsync(any(), any()))
|
||||
when(accountsManager.update(any(), any()))
|
||||
.thenAnswer(invocation -> {
|
||||
final Account a = invocation.getArgument(0);
|
||||
final Consumer<Account> updater = invocation.getArgument(1);
|
||||
|
||||
updater.accept(a);
|
||||
|
||||
return CompletableFuture.completedFuture(a);
|
||||
return a;
|
||||
});
|
||||
|
||||
final BackupAuthCredentialRequest messagesCredentialRequest = backupAuthTestUtil.getRequest(messagesBackupKey, aci);
|
||||
@@ -127,7 +123,7 @@ public class BackupAuthManagerTest {
|
||||
|
||||
authManager.commitBackupId(account, primaryDevice(),
|
||||
Optional.of(messagesCredentialRequest),
|
||||
Optional.of(mediaCredentialRequest)).join();
|
||||
Optional.of(mediaCredentialRequest));
|
||||
|
||||
verify(account).setBackupCredentialRequests(messagesCredentialRequest.serialize(),
|
||||
mediaCredentialRequest.serialize());
|
||||
@@ -138,13 +134,13 @@ public class BackupAuthManagerTest {
|
||||
void commitOnAnyBackupLevel(final BackupLevel backupLevel) {
|
||||
final BackupAuthManager authManager = create();
|
||||
final Account account = new MockAccountBuilder().backupLevel(backupLevel).build();
|
||||
when(accountsManager.updateAsync(any(), any())).thenReturn(CompletableFuture.completedFuture(account));
|
||||
when(accountsManager.update(any(), any())).thenReturn(account);
|
||||
|
||||
final ThrowableAssert.ThrowingCallable commit = () ->
|
||||
authManager.commitBackupId(account,
|
||||
primaryDevice(),
|
||||
Optional.of(backupAuthTestUtil.getRequest(messagesBackupKey, aci)),
|
||||
Optional.of(backupAuthTestUtil.getRequest(mediaBackupKey, aci))).join();
|
||||
Optional.of(backupAuthTestUtil.getRequest(mediaBackupKey, aci)));
|
||||
Assertions.assertThatNoException().isThrownBy(commit);
|
||||
}
|
||||
|
||||
@@ -152,22 +148,20 @@ public class BackupAuthManagerTest {
|
||||
void commitRequiresPrimary() {
|
||||
final BackupAuthManager authManager = create();
|
||||
final Account account = new MockAccountBuilder().build();
|
||||
when(accountsManager.updateAsync(any(), any())).thenReturn(CompletableFuture.completedFuture(account));
|
||||
when(accountsManager.update(any(), any())).thenReturn(account);
|
||||
|
||||
final ThrowableAssert.ThrowingCallable commit = () ->
|
||||
authManager.commitBackupId(account,
|
||||
linkedDevice(),
|
||||
Optional.of(backupAuthTestUtil.getRequest(messagesBackupKey, aci)),
|
||||
Optional.of(backupAuthTestUtil.getRequest(mediaBackupKey, aci))).join();
|
||||
assertThatExceptionOfType(StatusRuntimeException.class)
|
||||
.isThrownBy(commit)
|
||||
.extracting(ex -> ex.getStatus().getCode())
|
||||
.isEqualTo(Status.Code.PERMISSION_DENIED);
|
||||
Optional.of(backupAuthTestUtil.getRequest(mediaBackupKey, aci)));
|
||||
assertThatExceptionOfType(BackupPermissionException.class)
|
||||
.isThrownBy(commit);
|
||||
}
|
||||
|
||||
@CartesianTest
|
||||
void paidTierCredentialViaConfiguration(@CartesianTest.Enum final BackupCredentialType credentialType)
|
||||
throws VerificationFailedException {
|
||||
throws VerificationFailedException, BackupNotFoundException {
|
||||
final BackupAuthManager authManager = create(BackupLevel.PAID, rateLimiter(aci, false, false));
|
||||
|
||||
final byte[] backupKey = switch (credentialType) {
|
||||
@@ -186,7 +180,7 @@ public class BackupAuthManagerTest {
|
||||
|
||||
final RedemptionRange range = range(Duration.ofDays(1));
|
||||
final List<BackupAuthManager.Credential> creds =
|
||||
authManager.getBackupAuthCredentials(account, credentialType, range(Duration.ofDays(1))).join();
|
||||
authManager.getBackupAuthCredentials(account, credentialType, range(Duration.ofDays(1)));
|
||||
|
||||
assertThat(creds).hasSize(2);
|
||||
assertThat(requestContext
|
||||
@@ -197,7 +191,7 @@ public class BackupAuthManagerTest {
|
||||
|
||||
@CartesianTest
|
||||
void getBackupAuthCredentials(@CartesianTest.Enum final BackupLevel backupLevel,
|
||||
@CartesianTest.Enum final BackupCredentialType credentialType) {
|
||||
@CartesianTest.Enum final BackupCredentialType credentialType) throws BackupNotFoundException {
|
||||
|
||||
final BackupAuthManager authManager = create();
|
||||
|
||||
@@ -207,7 +201,7 @@ public class BackupAuthManagerTest {
|
||||
.mediaCredential(backupAuthTestUtil.getRequest(mediaBackupKey, aci))
|
||||
.build();
|
||||
|
||||
assertThat(authManager.getBackupAuthCredentials(account, credentialType, range(Duration.ofDays(1))).join())
|
||||
assertThat(authManager.getBackupAuthCredentials(account, credentialType, range(Duration.ofDays(1))))
|
||||
.hasSize(2);
|
||||
}
|
||||
|
||||
@@ -218,16 +212,14 @@ public class BackupAuthManagerTest {
|
||||
|
||||
final Account account = new MockAccountBuilder().build();
|
||||
|
||||
assertThatExceptionOfType(StatusRuntimeException.class)
|
||||
.isThrownBy(() ->
|
||||
authManager.getBackupAuthCredentials(account, credentialType, range(Duration.ofDays(1))).join())
|
||||
.extracting(ex -> ex.getStatus().getCode())
|
||||
.isEqualTo(Status.Code.NOT_FOUND);
|
||||
assertThatExceptionOfType(BackupNotFoundException.class)
|
||||
.isThrownBy(() -> authManager.getBackupAuthCredentials(account, credentialType, range(Duration.ofDays(1))));
|
||||
}
|
||||
|
||||
@CartesianTest
|
||||
void getReceiptCredentials(@CartesianTest.Enum final BackupLevel backupLevel,
|
||||
@CartesianTest.Enum final BackupCredentialType credentialType) throws VerificationFailedException {
|
||||
@CartesianTest.Enum final BackupCredentialType credentialType)
|
||||
throws VerificationFailedException, BackupNotFoundException {
|
||||
final BackupAuthManager authManager = create();
|
||||
|
||||
final byte[] backupKey = switch (credentialType) {
|
||||
@@ -245,7 +237,7 @@ public class BackupAuthManagerTest {
|
||||
.build();
|
||||
|
||||
final List<BackupAuthManager.Credential> creds = authManager.getBackupAuthCredentials(account,
|
||||
credentialType, range(Duration.ofDays(7))).join();
|
||||
credentialType, range(Duration.ofDays(7)));
|
||||
|
||||
assertThat(creds).hasSize(8);
|
||||
Instant redemptionTime = clock.instant().truncatedTo(ChronoUnit.DAYS);
|
||||
@@ -260,7 +252,7 @@ public class BackupAuthManagerTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
void expiringBackupPayment() throws VerificationFailedException {
|
||||
void expiringBackupPayment() throws VerificationFailedException, BackupNotFoundException {
|
||||
clock.pin(Instant.ofEpochSecond(1));
|
||||
final Instant day4 = Instant.EPOCH.plus(Duration.ofDays(4));
|
||||
|
||||
@@ -275,7 +267,7 @@ public class BackupAuthManagerTest {
|
||||
final List<BackupAuthManager.Credential> creds = authManager.getBackupAuthCredentials(
|
||||
account,
|
||||
BackupCredentialType.MESSAGES,
|
||||
range(RedemptionRange.MAX_REDEMPTION_DURATION)).join();
|
||||
range(RedemptionRange.MAX_REDEMPTION_DURATION));
|
||||
Instant redemptionTime = Instant.EPOCH;
|
||||
final BackupAuthCredentialRequestContext requestContext = BackupAuthCredentialRequestContext.create(
|
||||
messagesBackupKey, aci);
|
||||
@@ -293,7 +285,7 @@ public class BackupAuthManagerTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
void expiredBackupPayment() {
|
||||
void expiredBackupPayment() throws BackupNotFoundException {
|
||||
final Instant day1 = Instant.EPOCH.plus(Duration.ofDays(1));
|
||||
final Instant day2 = Instant.EPOCH.plus(Duration.ofDays(2));
|
||||
final Instant day3 = Instant.EPOCH.plus(Duration.ofDays(3));
|
||||
@@ -311,15 +303,15 @@ public class BackupAuthManagerTest {
|
||||
.backupVoucher(null)
|
||||
.build();
|
||||
|
||||
when(accountsManager.updateAsync(any(), any())).thenReturn(CompletableFuture.completedFuture(updated));
|
||||
when(accountsManager.update(any(), any())).thenReturn(updated);
|
||||
|
||||
clock.pin(day2.plus(Duration.ofSeconds(1)));
|
||||
assertThat(authManager.getBackupAuthCredentials(account, BackupCredentialType.MESSAGES, range(Duration.ofDays(7))).join())
|
||||
assertThat(authManager.getBackupAuthCredentials(account, BackupCredentialType.MESSAGES, range(Duration.ofDays(7))))
|
||||
.hasSize(8);
|
||||
|
||||
@SuppressWarnings("unchecked") final ArgumentCaptor<Consumer<Account>> accountUpdater = ArgumentCaptor.forClass(
|
||||
Consumer.class);
|
||||
verify(accountsManager, times(1)).updateAsync(any(), accountUpdater.capture());
|
||||
verify(accountsManager, times(1)).update(any(), accountUpdater.capture());
|
||||
|
||||
// If the account is not expired when we go to update it, we shouldn't wipe it out
|
||||
final Account alreadyUpdated = mock(Account.class);
|
||||
@@ -336,18 +328,19 @@ public class BackupAuthManagerTest {
|
||||
|
||||
|
||||
@Test
|
||||
void redeemReceipt() throws InvalidInputException, VerificationFailedException {
|
||||
void redeemReceipt()
|
||||
throws InvalidInputException, VerificationFailedException, BackupInvalidArgumentException, BackupMissingIdCommitmentException, BackupBadReceiptException {
|
||||
final Instant expirationTime = Instant.EPOCH.plus(Duration.ofDays(1));
|
||||
final BackupAuthManager authManager = create();
|
||||
final Account account = new MockAccountBuilder()
|
||||
.mediaCredential(Optional.of(new byte[0]))
|
||||
.build();
|
||||
clock.pin(Instant.EPOCH.plus(Duration.ofDays(1)));
|
||||
when(accountsManager.updateAsync(any(), any())).thenReturn(CompletableFuture.completedFuture(account));
|
||||
when(accountsManager.update(any(), any())).thenReturn(account);
|
||||
when(redeemedReceiptsManager.put(any(), eq(expirationTime.getEpochSecond()), eq(201L), eq(aci)))
|
||||
.thenReturn(CompletableFuture.completedFuture(true));
|
||||
authManager.redeemReceipt(account, receiptPresentation(201, expirationTime)).join();
|
||||
verify(accountsManager, times(1)).updateAsync(any(), any());
|
||||
authManager.redeemReceipt(account, receiptPresentation(201, expirationTime));
|
||||
verify(accountsManager, times(1)).update(any(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -359,15 +352,13 @@ public class BackupAuthManagerTest {
|
||||
clock.pin(Instant.EPOCH.plus(Duration.ofDays(1)));
|
||||
when(redeemedReceiptsManager.put(any(), eq(expirationTime.getEpochSecond()), eq(201L), eq(aci)))
|
||||
.thenReturn(CompletableFuture.completedFuture(true));
|
||||
assertThatExceptionOfType(StatusRuntimeException.class)
|
||||
.isThrownBy(() ->
|
||||
authManager.redeemReceipt(account, receiptPresentation(201, expirationTime)).join())
|
||||
.extracting(ex -> ex.getStatus().getCode())
|
||||
.isEqualTo(Status.Code.ABORTED);
|
||||
assertThatExceptionOfType(BackupMissingIdCommitmentException.class)
|
||||
.isThrownBy(() -> authManager.redeemReceipt(account, receiptPresentation(201, expirationTime)));
|
||||
}
|
||||
|
||||
@Test
|
||||
void mergeRedemptions() throws InvalidInputException, VerificationFailedException {
|
||||
void mergeRedemptions()
|
||||
throws InvalidInputException, VerificationFailedException, BackupInvalidArgumentException, BackupMissingIdCommitmentException, BackupBadReceiptException {
|
||||
final Instant newExpirationTime = Instant.EPOCH.plus(Duration.ofDays(1));
|
||||
final Instant existingExpirationTime = Instant.EPOCH.plus(Duration.ofDays(1)).plus(Duration.ofSeconds(1));
|
||||
|
||||
@@ -379,13 +370,13 @@ public class BackupAuthManagerTest {
|
||||
.build();
|
||||
|
||||
clock.pin(Instant.EPOCH.plus(Duration.ofDays(1)));
|
||||
when(accountsManager.updateAsync(any(), any())).thenReturn(CompletableFuture.completedFuture(account));
|
||||
when(accountsManager.update(any(), any())).thenReturn(account);
|
||||
when(redeemedReceiptsManager.put(any(), eq(newExpirationTime.getEpochSecond()), eq(201L), eq(aci)))
|
||||
.thenReturn(CompletableFuture.completedFuture(true));
|
||||
authManager.redeemReceipt(account, receiptPresentation(201, newExpirationTime)).join();
|
||||
authManager.redeemReceipt(account, receiptPresentation(201, newExpirationTime));
|
||||
|
||||
final ArgumentCaptor<Consumer<Account>> updaterCaptor = ArgumentCaptor.captor();
|
||||
verify(accountsManager, times(1)).updateAsync(any(), updaterCaptor.capture());
|
||||
verify(accountsManager, times(1)).update(any(), updaterCaptor.capture());
|
||||
|
||||
updaterCaptor.getValue().accept(account);
|
||||
// Should select the voucher with the later expiration time
|
||||
@@ -397,10 +388,8 @@ public class BackupAuthManagerTest {
|
||||
final Instant expirationTime = Instant.EPOCH.plus(Duration.ofDays(1));
|
||||
clock.pin(expirationTime.plus(Duration.ofSeconds(1)));
|
||||
final BackupAuthManager authManager = create();
|
||||
assertThatExceptionOfType(StatusRuntimeException.class)
|
||||
.isThrownBy(() -> authManager.redeemReceipt(mock(Account.class), receiptPresentation(3, expirationTime)).join())
|
||||
.extracting(ex -> ex.getStatus().getCode())
|
||||
.isEqualTo(Status.Code.INVALID_ARGUMENT);
|
||||
assertThatExceptionOfType(BackupBadReceiptException.class)
|
||||
.isThrownBy(() -> authManager.redeemReceipt(mock(Account.class), receiptPresentation(3, expirationTime)));
|
||||
verifyNoInteractions(accountsManager);
|
||||
verifyNoInteractions(redeemedReceiptsManager);
|
||||
}
|
||||
@@ -411,11 +400,8 @@ public class BackupAuthManagerTest {
|
||||
final Instant expirationTime = Instant.EPOCH.plus(Duration.ofDays(1));
|
||||
clock.pin(expirationTime.plus(Duration.ofSeconds(1)));
|
||||
final BackupAuthManager authManager = create();
|
||||
assertThatExceptionOfType(StatusRuntimeException.class)
|
||||
.isThrownBy(() ->
|
||||
authManager.redeemReceipt(mock(Account.class), receiptPresentation(level, expirationTime)).join())
|
||||
.extracting(ex -> ex.getStatus().getCode())
|
||||
.isEqualTo(Status.Code.INVALID_ARGUMENT);
|
||||
assertThatExceptionOfType(BackupBadReceiptException.class)
|
||||
.isThrownBy(() -> authManager.redeemReceipt(mock(Account.class), receiptPresentation(level, expirationTime)));
|
||||
verifyNoInteractions(accountsManager);
|
||||
verifyNoInteractions(redeemedReceiptsManager);
|
||||
}
|
||||
@@ -424,16 +410,14 @@ public class BackupAuthManagerTest {
|
||||
void redeemInvalidPresentation() throws InvalidInputException, VerificationFailedException {
|
||||
final BackupAuthManager authManager = create();
|
||||
final ReceiptCredentialPresentation invalid = receiptPresentation(ServerSecretParams.generate(), 3L, Instant.EPOCH);
|
||||
assertThatExceptionOfType(StatusRuntimeException.class)
|
||||
.isThrownBy(() -> authManager.redeemReceipt(mock(Account.class), invalid).join())
|
||||
.extracting(ex -> ex.getStatus().getCode())
|
||||
.isEqualTo(Status.Code.INVALID_ARGUMENT);
|
||||
assertThatExceptionOfType(BackupBadReceiptException.class)
|
||||
.isThrownBy(() -> authManager.redeemReceipt(mock(Account.class), invalid));
|
||||
verifyNoInteractions(accountsManager);
|
||||
verifyNoInteractions(redeemedReceiptsManager);
|
||||
}
|
||||
|
||||
@Test
|
||||
void receiptAlreadyRedeemed() throws InvalidInputException, VerificationFailedException {
|
||||
void receiptAlreadyRedeemed() {
|
||||
final Instant expirationTime = Instant.EPOCH.plus(Duration.ofDays(1));
|
||||
final BackupAuthManager authManager = create();
|
||||
final Account account = new MockAccountBuilder()
|
||||
@@ -441,14 +425,12 @@ public class BackupAuthManagerTest {
|
||||
.build();
|
||||
|
||||
clock.pin(Instant.EPOCH.plus(Duration.ofDays(1)));
|
||||
when(accountsManager.updateAsync(any(), any())).thenReturn(CompletableFuture.completedFuture(account));
|
||||
when(accountsManager.update(any(), any())).thenReturn(account);
|
||||
when(redeemedReceiptsManager.put(any(), eq(expirationTime.getEpochSecond()), eq(201L), eq(aci)))
|
||||
.thenReturn(CompletableFuture.completedFuture(false));
|
||||
|
||||
final CompletableFuture<Void> result = authManager.redeemReceipt(account, receiptPresentation(201, expirationTime));
|
||||
assertThat(CompletableFutureTestUtil.assertFailsWithCause(StatusRuntimeException.class, result))
|
||||
.extracting(ex -> ex.getStatus().getCode())
|
||||
.isEqualTo(Status.Code.INVALID_ARGUMENT);
|
||||
assertThatExceptionOfType(BackupBadReceiptException.class)
|
||||
.isThrownBy(() -> authManager.redeemReceipt(account, receiptPresentation(201, expirationTime)));
|
||||
verifyNoInteractions(accountsManager);
|
||||
}
|
||||
|
||||
@@ -484,8 +466,7 @@ public class BackupAuthManagerTest {
|
||||
? new Account.BackupVoucher(1, Instant.EPOCH.plus(Duration.ofSeconds(1)))
|
||||
: null)
|
||||
.build();
|
||||
final BackupAuthManager.BackupIdRotationLimit limit = authManager.checkBackupIdRotationLimit(account)
|
||||
.toCompletableFuture().join();
|
||||
final BackupAuthManager.BackupIdRotationLimit limit = authManager.checkBackupIdRotationLimit(account);
|
||||
final boolean expectHasPermits = !messageLimited && (!mediaLimited || !hasVoucher);
|
||||
final Duration expectedDuration = expectHasPermits ? Duration.ZERO : Duration.ofDays(1);
|
||||
assertThat(limit.hasPermitsRemaining()).isEqualTo(expectHasPermits);
|
||||
@@ -524,7 +505,7 @@ public class BackupAuthManagerTest {
|
||||
.backupVoucher(backupVoucher)
|
||||
.build();
|
||||
|
||||
when(accountsManager.updateAsync(any(), any())).thenReturn(CompletableFuture.completedFuture(account));
|
||||
when(accountsManager.update(any(), any())).thenReturn(account);
|
||||
|
||||
final Optional<BackupAuthCredentialRequest> newMessagesCredential = switch (messageChange) {
|
||||
case MATCH -> Optional.of(storedMessagesCredential);
|
||||
@@ -543,15 +524,13 @@ public class BackupAuthManagerTest {
|
||||
final boolean expectRateLimit = ((mediaChange == CredentialChangeType.MISMATCH) && rateLimitMediaBackupId && paid)
|
||||
|| ((messageChange == CredentialChangeType.MISMATCH) && rateLimitMessagesBackupId);
|
||||
final ThrowableAssert.ThrowingCallable commit = () ->
|
||||
authManager.commitBackupId(account, primaryDevice(), newMessagesCredential, newMediaCredential).join();
|
||||
authManager.commitBackupId(account, primaryDevice(), newMessagesCredential, newMediaCredential);
|
||||
|
||||
if (messageChange == CredentialChangeType.NO_UPDATE && mediaChange == CredentialChangeType.NO_UPDATE) {
|
||||
assertThatExceptionOfType(StatusRuntimeException.class)
|
||||
.isThrownBy(commit)
|
||||
.extracting(ex -> ex.getStatus().getCode())
|
||||
.isEqualTo(Status.Code.INVALID_ARGUMENT);
|
||||
assertThatExceptionOfType(BackupInvalidArgumentException.class)
|
||||
.isThrownBy(commit);
|
||||
} else if (expectRateLimit) {
|
||||
assertThatException().isThrownBy(commit).withRootCauseInstanceOf(RateLimitExceededException.class);
|
||||
assertThatExceptionOfType(RateLimitExceededException.class).isThrownBy(commit);
|
||||
} else {
|
||||
assertThatNoException().isThrownBy(commit);
|
||||
}
|
||||
@@ -611,26 +590,29 @@ public class BackupAuthManagerTest {
|
||||
}
|
||||
|
||||
|
||||
private static RateLimiters rateLimiter(final UUID aci, boolean rateLimitBackupId,
|
||||
boolean rateLimitPaidMediaBackupId) {
|
||||
final RateLimiters limiters = mock(RateLimiters.class);
|
||||
private static RateLimiters rateLimiter(final UUID aci, boolean rateLimitBackupId, boolean rateLimitPaidMediaBackupId) {
|
||||
try {
|
||||
final RateLimiters limiters = mock(RateLimiters.class);
|
||||
|
||||
final RateLimiter allowLimiter = mock(RateLimiter.class);
|
||||
when(allowLimiter.hasAvailablePermitsAsync(eq(aci), anyLong())).thenReturn(CompletableFuture.completedFuture(true));
|
||||
when(allowLimiter.validateAsync(aci)).thenReturn(CompletableFuture.completedFuture(null));
|
||||
when(allowLimiter.config()).thenReturn(new RateLimiterConfig(1, Duration.ofDays(1), false));
|
||||
final RateLimiter allowLimiter = mock(RateLimiter.class);
|
||||
when(allowLimiter.hasAvailablePermitsAsync(eq(aci), anyLong())).thenReturn(
|
||||
CompletableFuture.completedFuture(true));
|
||||
when(allowLimiter.config()).thenReturn(new RateLimiterConfig(1, Duration.ofDays(1), false));
|
||||
|
||||
final RateLimiter denyLimiter = mock(RateLimiter.class);
|
||||
when(denyLimiter.hasAvailablePermitsAsync(eq(aci), anyLong())).thenReturn(CompletableFuture.completedFuture(false));
|
||||
when(denyLimiter.validateAsync(aci))
|
||||
.thenReturn(CompletableFuture.failedFuture(new RateLimitExceededException(null)));
|
||||
when(denyLimiter.config()).thenReturn(new RateLimiterConfig(1, Duration.ofDays(1), false));
|
||||
final RateLimiter denyLimiter = mock(RateLimiter.class);
|
||||
when(denyLimiter.hasAvailablePermitsAsync(eq(aci), anyLong())).thenReturn(
|
||||
CompletableFuture.completedFuture(false));
|
||||
doThrow(new RateLimitExceededException(null)).when(denyLimiter).validate(aci);
|
||||
when(denyLimiter.config()).thenReturn(new RateLimiterConfig(1, Duration.ofDays(1), false));
|
||||
|
||||
when(limiters.forDescriptor(RateLimiters.For.SET_BACKUP_ID))
|
||||
.thenReturn(rateLimitBackupId ? denyLimiter : allowLimiter);
|
||||
when(limiters.forDescriptor(RateLimiters.For.SET_PAID_MEDIA_BACKUP_ID))
|
||||
.thenReturn(rateLimitPaidMediaBackupId ? denyLimiter : allowLimiter);
|
||||
return limiters;
|
||||
when(limiters.forDescriptor(RateLimiters.For.SET_BACKUP_ID))
|
||||
.thenReturn(rateLimitBackupId ? denyLimiter : allowLimiter);
|
||||
when(limiters.forDescriptor(RateLimiters.For.SET_PAID_MEDIA_BACKUP_ID))
|
||||
.thenReturn(rateLimitPaidMediaBackupId ? denyLimiter : allowLimiter);
|
||||
return limiters;
|
||||
} catch (RateLimitExceededException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
|
||||
private RedemptionRange range(Duration length) {
|
||||
|
||||
+6
-1
@@ -14,6 +14,7 @@ import java.time.temporal.ChronoUnit;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import org.junit.jupiter.api.Assertions;
|
||||
import org.signal.libsignal.zkgroup.GenericServerSecretParams;
|
||||
import org.signal.libsignal.zkgroup.VerificationFailedException;
|
||||
import org.signal.libsignal.zkgroup.backups.BackupAuthCredentialPresentation;
|
||||
@@ -76,6 +77,10 @@ public class BackupAuthTestUtil {
|
||||
});
|
||||
final RedemptionRange redemptionRange;
|
||||
redemptionRange = RedemptionRange.inclusive(clock, redemptionStart, redemptionEnd);
|
||||
return issuer.getBackupAuthCredentials(account, credentialType, redemptionRange).join();
|
||||
try {
|
||||
return issuer.getBackupAuthCredentials(account, credentialType, redemptionRange);
|
||||
} catch (BackupNotFoundException e) {
|
||||
return Assertions.fail("Backup credential request not found even though we set one");
|
||||
}
|
||||
}
|
||||
}
|
||||
+91
-142
@@ -13,6 +13,7 @@ import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyLong;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.doThrow;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.reset;
|
||||
import static org.mockito.Mockito.times;
|
||||
@@ -23,8 +24,6 @@ import static org.mockito.Mockito.when;
|
||||
import static org.whispersystems.textsecuregcm.util.MockUtils.randomSecretBytes;
|
||||
|
||||
import io.dropwizard.util.DataSize;
|
||||
import io.grpc.Status;
|
||||
import io.grpc.StatusRuntimeException;
|
||||
import java.io.IOException;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
@@ -183,11 +182,7 @@ public class BackupManagerTest {
|
||||
() -> BackupManager.checkBackupLevel(backupUser, requiredLevel);
|
||||
|
||||
if (expectException) {
|
||||
assertThatExceptionOfType(StatusRuntimeException.class)
|
||||
.isThrownBy(checkBackupLevel)
|
||||
.extracting(StatusRuntimeException::getStatus)
|
||||
.extracting(Status::getCode)
|
||||
.isEqualTo(Status.Code.PERMISSION_DENIED);
|
||||
assertThatExceptionOfType(BackupPermissionException.class).isThrownBy(checkBackupLevel);
|
||||
} else {
|
||||
assertThatNoException().isThrownBy(checkBackupLevel);
|
||||
}
|
||||
@@ -211,11 +206,7 @@ public class BackupManagerTest {
|
||||
() -> BackupManager.checkBackupCredentialType(backupUser, requiredCredentialType);
|
||||
|
||||
if (expectException) {
|
||||
assertThatExceptionOfType(StatusRuntimeException.class)
|
||||
.isThrownBy(checkCredentialType)
|
||||
.extracting(StatusRuntimeException::getStatus)
|
||||
.extracting(Status::getCode)
|
||||
.isEqualTo(Status.Code.UNAUTHENTICATED);
|
||||
assertThatExceptionOfType(BackupWrongCredentialTypeException.class).isThrownBy(checkCredentialType);
|
||||
} else {
|
||||
assertThatNoException().isThrownBy(checkCredentialType);
|
||||
}
|
||||
@@ -223,18 +214,18 @@ public class BackupManagerTest {
|
||||
|
||||
@ParameterizedTest
|
||||
@EnumSource
|
||||
public void createBackup(final BackupLevel backupLevel) {
|
||||
public void createBackup(final BackupLevel backupLevel) throws BackupException {
|
||||
|
||||
final Instant now = Instant.ofEpochSecond(Duration.ofDays(1).getSeconds());
|
||||
testClock.pin(now);
|
||||
|
||||
final AuthenticatedBackupUser backupUser = backupUser(TestRandomUtil.nextBytes(16), BackupCredentialType.MESSAGES, backupLevel);
|
||||
|
||||
backupManager.createMessageBackupUploadDescriptor(backupUser).join();
|
||||
backupManager.createMessageBackupUploadDescriptor(backupUser);
|
||||
verify(tusCredentialGenerator, times(1))
|
||||
.generateUpload("%s/%s".formatted(backupUser.backupDir(), BackupManager.MESSAGE_BACKUP_NAME));
|
||||
|
||||
final BackupManager.BackupInfo info = backupManager.backupInfo(backupUser).join();
|
||||
final BackupManager.BackupInfo info = backupManager.backupInfo(backupUser);
|
||||
assertThat(info.backupSubdir()).isEqualTo(backupUser.backupDir()).isNotBlank();
|
||||
assertThat(info.messageBackupKey()).isEqualTo(BackupManager.MESSAGE_BACKUP_NAME);
|
||||
assertThat(info.mediaUsedSpace()).isEqualTo(Optional.empty());
|
||||
@@ -252,44 +243,36 @@ public class BackupManagerTest {
|
||||
|
||||
final AuthenticatedBackupUser backupUser = backupUser(TestRandomUtil.nextBytes(16), BackupCredentialType.MEDIA, backupLevel);
|
||||
|
||||
assertThatExceptionOfType(StatusRuntimeException.class)
|
||||
.isThrownBy(() -> backupManager.createMessageBackupUploadDescriptor(backupUser).join())
|
||||
.matches(exception -> exception.getStatus().getCode() == Status.UNAUTHENTICATED.getCode());
|
||||
assertThatExceptionOfType(BackupWrongCredentialTypeException.class)
|
||||
.isThrownBy(() -> backupManager.createMessageBackupUploadDescriptor(backupUser));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void createTemporaryMediaAttachmentRateLimited() {
|
||||
public void createTemporaryMediaAttachmentRateLimited() throws RateLimitExceededException {
|
||||
final AuthenticatedBackupUser backupUser = backupUser(TestRandomUtil.nextBytes(16), BackupCredentialType.MEDIA, BackupLevel.PAID);
|
||||
when(mediaUploadLimiter.validateAsync(eq(BackupManager.rateLimitKey(backupUser))))
|
||||
.thenReturn(CompletableFuture.failedFuture(new RateLimitExceededException(null)));
|
||||
CompletableFutureTestUtil.assertFailsWithCause(
|
||||
RateLimitExceededException.class,
|
||||
backupManager.createTemporaryAttachmentUploadDescriptor(backupUser).toCompletableFuture());
|
||||
doThrow(new RateLimitExceededException(null))
|
||||
.when(mediaUploadLimiter).validate(eq(BackupManager.rateLimitKey(backupUser)));
|
||||
assertThatExceptionOfType(RateLimitExceededException.class)
|
||||
.isThrownBy(() -> backupManager.createTemporaryAttachmentUploadDescriptor(backupUser));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void createTemporaryMediaAttachmentWrongTier() {
|
||||
final AuthenticatedBackupUser backupUser = backupUser(TestRandomUtil.nextBytes(16), BackupCredentialType.MEDIA, BackupLevel.FREE);
|
||||
assertThatExceptionOfType(StatusRuntimeException.class)
|
||||
.isThrownBy(() -> backupManager.createTemporaryAttachmentUploadDescriptor(backupUser))
|
||||
.extracting(StatusRuntimeException::getStatus)
|
||||
.extracting(Status::getCode)
|
||||
.isEqualTo(Status.Code.PERMISSION_DENIED);
|
||||
assertThatExceptionOfType(BackupPermissionException.class)
|
||||
.isThrownBy(() -> backupManager.createTemporaryAttachmentUploadDescriptor(backupUser));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void createTemporaryMediaAttachmentWrongCredentialType() {
|
||||
final AuthenticatedBackupUser backupUser = backupUser(TestRandomUtil.nextBytes(16), BackupCredentialType.MESSAGES, BackupLevel.PAID);
|
||||
assertThatExceptionOfType(StatusRuntimeException.class)
|
||||
.isThrownBy(() -> backupManager.createTemporaryAttachmentUploadDescriptor(backupUser))
|
||||
.extracting(StatusRuntimeException::getStatus)
|
||||
.extracting(Status::getCode)
|
||||
.isEqualTo(Status.Code.UNAUTHENTICATED);
|
||||
assertThatExceptionOfType(BackupWrongCredentialTypeException.class)
|
||||
.isThrownBy(() -> backupManager.createTemporaryAttachmentUploadDescriptor(backupUser));
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@EnumSource
|
||||
public void ttlRefresh(final BackupLevel backupLevel) {
|
||||
public void ttlRefresh(final BackupLevel backupLevel) throws BackupException {
|
||||
final AuthenticatedBackupUser backupUser = backupUser(TestRandomUtil.nextBytes(16), BackupCredentialType.MESSAGES, backupLevel);
|
||||
|
||||
final Instant tstart = Instant.ofEpochSecond(1).plus(Duration.ofDays(1));
|
||||
@@ -297,11 +280,11 @@ public class BackupManagerTest {
|
||||
|
||||
// create backup at t=tstart
|
||||
testClock.pin(tstart);
|
||||
backupManager.createMessageBackupUploadDescriptor(backupUser).join();
|
||||
backupManager.createMessageBackupUploadDescriptor(backupUser);
|
||||
|
||||
// refresh at t=tnext
|
||||
testClock.pin(tnext);
|
||||
backupManager.ttlRefresh(backupUser).join();
|
||||
backupManager.ttlRefresh(backupUser);
|
||||
|
||||
checkExpectedExpirations(
|
||||
tnext.truncatedTo(ChronoUnit.DAYS),
|
||||
@@ -311,7 +294,7 @@ public class BackupManagerTest {
|
||||
|
||||
@ParameterizedTest
|
||||
@EnumSource
|
||||
public void createBackupRefreshesTtl(final BackupLevel backupLevel) {
|
||||
public void createBackupRefreshesTtl(final BackupLevel backupLevel) throws BackupException {
|
||||
final Instant tstart = Instant.ofEpochSecond(1).plus(Duration.ofDays(1));
|
||||
final Instant tnext = tstart.plus(Duration.ofDays(1));
|
||||
|
||||
@@ -319,11 +302,11 @@ public class BackupManagerTest {
|
||||
|
||||
// create backup at t=tstart
|
||||
testClock.pin(tstart);
|
||||
backupManager.createMessageBackupUploadDescriptor(backupUser).join();
|
||||
backupManager.createMessageBackupUploadDescriptor(backupUser);
|
||||
|
||||
// create again at t=tnext
|
||||
testClock.pin(tnext);
|
||||
backupManager.createMessageBackupUploadDescriptor(backupUser).join();
|
||||
backupManager.createMessageBackupUploadDescriptor(backupUser);
|
||||
|
||||
checkExpectedExpirations(
|
||||
tnext.truncatedTo(ChronoUnit.DAYS),
|
||||
@@ -340,19 +323,16 @@ public class BackupManagerTest {
|
||||
final ECKeyPair keyPair = ECKeyPair.generate();
|
||||
|
||||
// haven't set a public key yet, but should fail before hitting the database anyway
|
||||
assertThatExceptionOfType(StatusRuntimeException.class)
|
||||
assertThatExceptionOfType(BackupFailedZkAuthenticationException.class)
|
||||
.isThrownBy(() -> backupManager.authenticateBackupUser(
|
||||
invalidPresentation,
|
||||
keyPair.getPrivateKey().calculateSignature(invalidPresentation.serialize()),
|
||||
null))
|
||||
.extracting(StatusRuntimeException::getStatus)
|
||||
.extracting(Status::getCode)
|
||||
.isEqualTo(Status.UNAUTHENTICATED.getCode());
|
||||
null));
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void invalidPresentationCorrectSignature() throws VerificationFailedException {
|
||||
public void invalidPresentationCorrectSignature() throws VerificationFailedException, BackupException {
|
||||
final BackupAuthCredentialPresentation presentation = backupAuthTestUtil.getPresentation(
|
||||
BackupLevel.FREE, backupKey, aci);
|
||||
final BackupAuthCredentialPresentation invalidPresentation = backupAuthTestUtil.getPresentation(
|
||||
@@ -363,16 +343,13 @@ public class BackupManagerTest {
|
||||
backupManager.setPublicKey(
|
||||
presentation,
|
||||
keyPair.getPrivateKey().calculateSignature(presentation.serialize()),
|
||||
keyPair.getPublicKey()).join();
|
||||
keyPair.getPublicKey());
|
||||
|
||||
assertThatExceptionOfType(StatusRuntimeException.class)
|
||||
assertThatExceptionOfType(BackupFailedZkAuthenticationException.class)
|
||||
.isThrownBy(() -> backupManager.authenticateBackupUser(
|
||||
invalidPresentation,
|
||||
keyPair.getPrivateKey().calculateSignature(invalidPresentation.serialize()),
|
||||
null))
|
||||
.extracting(StatusRuntimeException::getStatus)
|
||||
.extracting(Status::getCode)
|
||||
.isEqualTo(Status.UNAUTHENTICATED.getCode());
|
||||
null));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -384,15 +361,12 @@ public class BackupManagerTest {
|
||||
final byte[] signature = keyPair.getPrivateKey().calculateSignature(presentation.serialize());
|
||||
|
||||
// haven't set a public key yet
|
||||
assertThat(CompletableFutureTestUtil.assertFailsWithCause(
|
||||
StatusRuntimeException.class,
|
||||
backupManager.authenticateBackupUser(presentation, signature, null))
|
||||
.getStatus().getCode())
|
||||
.isEqualTo(Status.UNAUTHENTICATED.getCode());
|
||||
assertThatExceptionOfType(BackupFailedZkAuthenticationException.class)
|
||||
.isThrownBy(() -> backupManager.authenticateBackupUser(presentation, signature, null));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void mismatchedPublicKey() throws VerificationFailedException {
|
||||
public void mismatchedPublicKey() throws VerificationFailedException, BackupException {
|
||||
final BackupAuthCredentialPresentation presentation = backupAuthTestUtil.getPresentation(
|
||||
BackupLevel.FREE, backupKey, aci);
|
||||
|
||||
@@ -401,21 +375,18 @@ public class BackupManagerTest {
|
||||
final byte[] signature1 = keyPair1.getPrivateKey().calculateSignature(presentation.serialize());
|
||||
final byte[] signature2 = keyPair2.getPrivateKey().calculateSignature(presentation.serialize());
|
||||
|
||||
backupManager.setPublicKey(presentation, signature1, keyPair1.getPublicKey()).join();
|
||||
backupManager.setPublicKey(presentation, signature1, keyPair1.getPublicKey());
|
||||
|
||||
// shouldn't be able to set a different public key
|
||||
assertThat(CompletableFutureTestUtil.assertFailsWithCause(
|
||||
StatusRuntimeException.class,
|
||||
backupManager.setPublicKey(presentation, signature2, keyPair2.getPublicKey()))
|
||||
.getStatus().getCode())
|
||||
.isEqualTo(Status.UNAUTHENTICATED.getCode());
|
||||
assertThatExceptionOfType(BackupFailedZkAuthenticationException.class)
|
||||
.isThrownBy(() -> backupManager.setPublicKey(presentation, signature2, keyPair2.getPublicKey()));
|
||||
|
||||
// should be able to set the same public key again (noop)
|
||||
backupManager.setPublicKey(presentation, signature1, keyPair1.getPublicKey()).join();
|
||||
backupManager.setPublicKey(presentation, signature1, keyPair1.getPublicKey());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void signatureValidation() throws VerificationFailedException {
|
||||
public void signatureValidation() throws VerificationFailedException, BackupException {
|
||||
final BackupAuthCredentialPresentation presentation = backupAuthTestUtil.getPresentation(
|
||||
BackupLevel.FREE, backupKey, aci);
|
||||
|
||||
@@ -427,28 +398,23 @@ public class BackupManagerTest {
|
||||
wrongSignature[1] += 1;
|
||||
|
||||
// shouldn't be able to set a public key with an invalid signature
|
||||
assertThatExceptionOfType(StatusRuntimeException.class)
|
||||
.isThrownBy(() -> backupManager.setPublicKey(presentation, wrongSignature, keyPair.getPublicKey()))
|
||||
.extracting(ex -> ex.getStatus().getCode())
|
||||
.isEqualTo(Status.UNAUTHENTICATED.getCode());
|
||||
assertThatExceptionOfType(BackupFailedZkAuthenticationException.class)
|
||||
.isThrownBy(() -> backupManager.setPublicKey(presentation, wrongSignature, keyPair.getPublicKey()));
|
||||
|
||||
backupManager.setPublicKey(presentation, signature, keyPair.getPublicKey()).join();
|
||||
backupManager.setPublicKey(presentation, signature, keyPair.getPublicKey());
|
||||
|
||||
// shouldn't be able to authenticate with an invalid signature
|
||||
assertThat(CompletableFutureTestUtil.assertFailsWithCause(
|
||||
StatusRuntimeException.class,
|
||||
backupManager.authenticateBackupUser(presentation, wrongSignature, null))
|
||||
.getStatus().getCode())
|
||||
.isEqualTo(Status.UNAUTHENTICATED.getCode());
|
||||
assertThatExceptionOfType(BackupFailedZkAuthenticationException.class)
|
||||
.isThrownBy(() -> backupManager.authenticateBackupUser(presentation, wrongSignature, null));
|
||||
|
||||
// correct signature
|
||||
final AuthenticatedBackupUser user = backupManager.authenticateBackupUser(presentation, signature, null).join();
|
||||
final AuthenticatedBackupUser user = backupManager.authenticateBackupUser(presentation, signature, null);
|
||||
assertThat(user.backupId()).isEqualTo(presentation.getBackupId());
|
||||
assertThat(user.backupLevel()).isEqualTo(BackupLevel.FREE);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void credentialExpiration() throws VerificationFailedException {
|
||||
public void credentialExpiration() throws VerificationFailedException, BackupException {
|
||||
|
||||
// credential for 1 day after epoch
|
||||
testClock.pin(Instant.ofEpochSecond(1).plus(Duration.ofDays(1)));
|
||||
@@ -456,27 +422,24 @@ public class BackupManagerTest {
|
||||
backupKey, aci);
|
||||
final ECKeyPair keyPair = ECKeyPair.generate();
|
||||
final byte[] signature = keyPair.getPrivateKey().calculateSignature(oldCredential.serialize());
|
||||
backupManager.setPublicKey(oldCredential, signature, keyPair.getPublicKey()).join();
|
||||
backupManager.setPublicKey(oldCredential, signature, keyPair.getPublicKey());
|
||||
|
||||
// should be accepted the day before to forgive clock skew
|
||||
testClock.pin(Instant.ofEpochSecond(1));
|
||||
assertThatNoException().isThrownBy(() -> backupManager.authenticateBackupUser(oldCredential, signature, null).join());
|
||||
assertThatNoException().isThrownBy(() -> backupManager.authenticateBackupUser(oldCredential, signature, null));
|
||||
|
||||
// should be accepted the day after to forgive clock skew
|
||||
testClock.pin(Instant.ofEpochSecond(1).plus(Duration.ofDays(2)));
|
||||
assertThatNoException().isThrownBy(() -> backupManager.authenticateBackupUser(oldCredential, signature, null).join());
|
||||
assertThatNoException().isThrownBy(() -> backupManager.authenticateBackupUser(oldCredential, signature, null));
|
||||
|
||||
// should be rejected the day after that
|
||||
testClock.pin(Instant.ofEpochSecond(1).plus(Duration.ofDays(3)));
|
||||
assertThatExceptionOfType(StatusRuntimeException.class)
|
||||
.isThrownBy(() -> backupManager.authenticateBackupUser(oldCredential, signature, null))
|
||||
.extracting(StatusRuntimeException::getStatus)
|
||||
.extracting(Status::getCode)
|
||||
.isEqualTo(Status.UNAUTHENTICATED.getCode());
|
||||
assertThatExceptionOfType(BackupFailedZkAuthenticationException.class)
|
||||
.isThrownBy(() -> backupManager.authenticateBackupUser(oldCredential, signature, null));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void copySuccess() {
|
||||
public void copySuccess() throws BackupException {
|
||||
final AuthenticatedBackupUser backupUser = backupUser(TestRandomUtil.nextBytes(16), BackupCredentialType.MEDIA, BackupLevel.PAID);
|
||||
final CopyResult copied = copy(backupUser);
|
||||
|
||||
@@ -493,7 +456,7 @@ public class BackupManagerTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void copyUsageCheckpoints() throws InterruptedException {
|
||||
public void copyUsageCheckpoints() throws InterruptedException, BackupException {
|
||||
final AuthenticatedBackupUser backupUser = backupUser(TestRandomUtil.nextBytes(16), BackupCredentialType.MEDIA, BackupLevel.PAID);
|
||||
backupsDb.setMediaUsage(backupUser, new UsageInfo(0, 0)).join();
|
||||
|
||||
@@ -512,7 +475,7 @@ public class BackupManagerTest {
|
||||
.thenReturn(slow);
|
||||
final ArrayBlockingQueue<CopyResult> copyResults = new ArrayBlockingQueue<>(100);
|
||||
final CompletableFuture<Void> future = backupManager
|
||||
.copyToBackup(backupUser, toCopy)
|
||||
.copyToBackup(backupManager.getCopyQuota(backupUser, toCopy))
|
||||
.doOnNext(copyResults::add).then().toFuture();
|
||||
|
||||
for (int i = 0; i < slowIndex; i++) {
|
||||
@@ -540,7 +503,7 @@ public class BackupManagerTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void copyFailure() {
|
||||
public void copyFailure() throws BackupException {
|
||||
final AuthenticatedBackupUser backupUser = backupUser(TestRandomUtil.nextBytes(16), BackupCredentialType.MEDIA, BackupLevel.PAID);
|
||||
assertThat(copyError(backupUser, new SourceObjectNotFoundException()).outcome())
|
||||
.isEqualTo(CopyResult.Outcome.SOURCE_NOT_FOUND);
|
||||
@@ -552,7 +515,7 @@ public class BackupManagerTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void copyPartialSuccess() {
|
||||
public void copyPartialSuccess() throws BackupException {
|
||||
final AuthenticatedBackupUser backupUser = backupUser(TestRandomUtil.nextBytes(16), BackupCredentialType.MEDIA, BackupLevel.PAID);
|
||||
final List<CopyParameters> toCopy = List.of(
|
||||
new CopyParameters(3, "success", 100, COPY_ENCRYPTION_PARAM, TestRandomUtil.nextBytes(15)),
|
||||
@@ -568,7 +531,7 @@ public class BackupManagerTest {
|
||||
when(remoteStorageManager.copy(eq(3), eq("badlength"), eq(300), any(), any()))
|
||||
.thenReturn(CompletableFuture.failedFuture(new InvalidLengthException("")));
|
||||
|
||||
final List<CopyResult> results = backupManager.copyToBackup(backupUser, toCopy)
|
||||
final List<CopyResult> results = backupManager.copyToBackup(backupManager.getCopyQuota(backupUser, toCopy))
|
||||
.collectList().block();
|
||||
|
||||
assertThat(results).hasSize(3);
|
||||
@@ -587,15 +550,11 @@ public class BackupManagerTest {
|
||||
public void copyWrongCredentialType() {
|
||||
final AuthenticatedBackupUser backupUser = backupUser(TestRandomUtil.nextBytes(16), BackupCredentialType.MESSAGES, BackupLevel.PAID);
|
||||
|
||||
assertThatExceptionOfType(StatusRuntimeException.class)
|
||||
.isThrownBy(() -> copy(backupUser))
|
||||
.extracting(StatusRuntimeException::getStatus)
|
||||
.extracting(Status::getCode)
|
||||
.isEqualTo(Status.Code.UNAUTHENTICATED);
|
||||
assertThatExceptionOfType(BackupWrongCredentialTypeException.class).isThrownBy(() -> copy(backupUser));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void quotaEnforcementNoRecalculation() {
|
||||
public void quotaEnforcementNoRecalculation() throws BackupException {
|
||||
final AuthenticatedBackupUser backupUser = backupUser(TestRandomUtil.nextBytes(16), BackupCredentialType.MEDIA, BackupLevel.PAID);
|
||||
verifyNoInteractions(remoteStorageManager);
|
||||
|
||||
@@ -612,7 +571,7 @@ public class BackupManagerTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void quotaEnforcementRecalculation() {
|
||||
public void quotaEnforcementRecalculation() throws BackupException {
|
||||
final AuthenticatedBackupUser backupUser = backupUser(TestRandomUtil.nextBytes(16), BackupCredentialType.MEDIA, BackupLevel.PAID);
|
||||
final String backupMediaPrefix = "%s/%s/".formatted(backupUser.backupDir(), backupUser.mediaDir());
|
||||
|
||||
@@ -642,7 +601,7 @@ public class BackupManagerTest {
|
||||
public void quotaEnforcement(
|
||||
@CartesianTest.Values(booleans = {true, false}) boolean hasSpaceBeforeRecalc,
|
||||
@CartesianTest.Values(booleans = {true, false}) boolean hasSpaceAfterRecalc,
|
||||
@CartesianTest.Values(booleans = {true, false}) boolean doesReaclc) {
|
||||
@CartesianTest.Values(booleans = {true, false}) boolean doesReaclc) throws BackupException {
|
||||
final AuthenticatedBackupUser backupUser = backupUser(TestRandomUtil.nextBytes(16), BackupCredentialType.MEDIA, BackupLevel.PAID);
|
||||
final String backupMediaPrefix = "%s/%s/".formatted(backupUser.backupDir(), backupUser.mediaDir());
|
||||
|
||||
@@ -701,7 +660,7 @@ public class BackupManagerTest {
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"", "cursor"})
|
||||
public void list(final String cursorVal) {
|
||||
public void list(final String cursorVal) throws BackupException {
|
||||
final Optional<String> cursor = Optional.of(cursorVal).filter(StringUtils::isNotBlank);
|
||||
final AuthenticatedBackupUser backupUser = backupUser(TestRandomUtil.nextBytes(16), BackupCredentialType.MESSAGES, BackupLevel.PAID);
|
||||
final String backupMediaPrefix = "%s/%s/".formatted(backupUser.backupDir(), backupUser.mediaDir());
|
||||
@@ -713,8 +672,7 @@ public class BackupManagerTest {
|
||||
Optional.of("newCursor")
|
||||
)));
|
||||
|
||||
final BackupManager.ListMediaResult result = backupManager.list(backupUser, cursor, 17)
|
||||
.toCompletableFuture().join();
|
||||
final BackupManager.ListMediaResult result = backupManager.list(backupUser, cursor, 17);
|
||||
assertThat(result.media()).hasSize(1);
|
||||
assertThat(result.media().getFirst().cdn()).isEqualTo(13);
|
||||
assertThat(result.media().getFirst().key()).isEqualTo(
|
||||
@@ -725,7 +683,7 @@ public class BackupManagerTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void deleteEntireBackup() {
|
||||
public void deleteEntireBackup() throws BackupException {
|
||||
final AuthenticatedBackupUser original = backupUser(TestRandomUtil.nextBytes(16), BackupCredentialType.MESSAGES, BackupLevel.PAID);
|
||||
|
||||
testClock.pin(Instant.ofEpochSecond(10));
|
||||
@@ -733,7 +691,7 @@ public class BackupManagerTest {
|
||||
when(svrbClient.removeData(anyString())).thenReturn(CompletableFuture.completedFuture(null));
|
||||
|
||||
// Deleting should swap the backupDir for the user
|
||||
backupManager.deleteEntireBackup(original).join();
|
||||
backupManager.deleteEntireBackup(original);
|
||||
verifyNoInteractions(remoteStorageManager);
|
||||
verify(svrbClient).removeData(HexFormat.of().formatHex(BackupsDb.hashedBackupId(original.backupId())));
|
||||
|
||||
@@ -747,7 +705,7 @@ public class BackupManagerTest {
|
||||
Collections.emptyList(),
|
||||
Optional.empty()
|
||||
)));
|
||||
backupManager.deleteEntireBackup(after).join();
|
||||
backupManager.deleteEntireBackup(after);
|
||||
verify(remoteStorageManager, times(1))
|
||||
.list(eq(after.backupDir() + "/"), eq(Optional.empty()), anyLong());
|
||||
|
||||
@@ -763,7 +721,7 @@ public class BackupManagerTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void delete() {
|
||||
public void delete() throws BackupException {
|
||||
final AuthenticatedBackupUser backupUser = backupUser(TestRandomUtil.nextBytes(16), BackupCredentialType.MEDIA, BackupLevel.PAID);
|
||||
final byte[] mediaId = TestRandomUtil.nextBytes(16);
|
||||
final String backupMediaKey = "%s/%s/%s".formatted(
|
||||
@@ -787,10 +745,8 @@ public class BackupManagerTest {
|
||||
public void deleteWrongCredentialType() {
|
||||
final AuthenticatedBackupUser backupUser = backupUser(TestRandomUtil.nextBytes(16), BackupCredentialType.MESSAGES, BackupLevel.PAID);
|
||||
final byte[] mediaId = TestRandomUtil.nextBytes(16);
|
||||
assertThatThrownBy(() ->
|
||||
backupManager.deleteMedia(backupUser, List.of(new BackupManager.StorageDescriptor(5, mediaId))).then().block())
|
||||
.isInstanceOf(StatusRuntimeException.class)
|
||||
.matches(e -> ((StatusRuntimeException) e).getStatus().getCode() == Status.UNAUTHENTICATED.getCode());
|
||||
assertThatExceptionOfType(BackupWrongCredentialTypeException.class)
|
||||
.isThrownBy(() -> backupManager.deleteMedia(backupUser, List.of(new BackupManager.StorageDescriptor(5, mediaId))).then().block());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -798,14 +754,12 @@ public class BackupManagerTest {
|
||||
final AuthenticatedBackupUser backupUser = backupUser(TestRandomUtil.nextBytes(16), BackupCredentialType.MEDIA, BackupLevel.PAID);
|
||||
final BackupManager.StorageDescriptor sd = new BackupManager.StorageDescriptor(4, TestRandomUtil.nextBytes(15));
|
||||
when(remoteStorageManager.cdnNumber()).thenReturn(5);
|
||||
assertThatThrownBy(() ->
|
||||
backupManager.deleteMedia(backupUser, List.of(sd)).then().block())
|
||||
.isInstanceOf(StatusRuntimeException.class)
|
||||
.matches(e -> ((StatusRuntimeException) e).getStatus().getCode() == Status.INVALID_ARGUMENT.getCode());
|
||||
assertThatThrownBy(() -> backupManager.deleteMedia(backupUser, List.of(sd)).then().toFuture().join())
|
||||
.hasCauseInstanceOf(BackupInvalidArgumentException.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void deleteUsageCheckpoints() throws InterruptedException {
|
||||
public void deleteUsageCheckpoints() throws InterruptedException, BackupException {
|
||||
final AuthenticatedBackupUser backupUser = backupUser(TestRandomUtil.nextBytes(16), BackupCredentialType.MEDIA,
|
||||
BackupLevel.PAID);
|
||||
|
||||
@@ -850,7 +804,7 @@ public class BackupManagerTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void deletePartialFailure() {
|
||||
public void deletePartialFailure() throws BackupException {
|
||||
final AuthenticatedBackupUser backupUser = backupUser(TestRandomUtil.nextBytes(16), BackupCredentialType.MEDIA, BackupLevel.PAID);
|
||||
|
||||
final List<BackupManager.StorageDescriptor> descriptors = new ArrayList<>();
|
||||
@@ -888,7 +842,7 @@ public class BackupManagerTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void alreadyDeleted() {
|
||||
public void alreadyDeleted() throws BackupException {
|
||||
final AuthenticatedBackupUser backupUser = backupUser(TestRandomUtil.nextBytes(16), BackupCredentialType.MEDIA, BackupLevel.PAID);
|
||||
final byte[] mediaId = TestRandomUtil.nextBytes(16);
|
||||
final String backupMediaKey = "%s/%s/%s".formatted(
|
||||
@@ -908,13 +862,13 @@ public class BackupManagerTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void listExpiredBackups() {
|
||||
public void listExpiredBackups() throws BackupException {
|
||||
final List<AuthenticatedBackupUser> backupUsers = IntStream.range(0, 10)
|
||||
.mapToObj(_ -> backupUser(TestRandomUtil.nextBytes(16), BackupCredentialType.MESSAGES, BackupLevel.PAID))
|
||||
.toList();
|
||||
for (int i = 0; i < backupUsers.size(); i++) {
|
||||
testClock.pin(days(i));
|
||||
backupManager.createMessageBackupUploadDescriptor(backupUsers.get(i)).join();
|
||||
backupManager.createMessageBackupUploadDescriptor(backupUsers.get(i));
|
||||
}
|
||||
|
||||
// set of backup-id hashes that should be expired (initially t=0)
|
||||
@@ -944,16 +898,16 @@ public class BackupManagerTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void listExpiredBackupsByTier() {
|
||||
public void listExpiredBackupsByTier() throws BackupException {
|
||||
final byte[] backupId = TestRandomUtil.nextBytes(16);
|
||||
|
||||
// refreshed media timestamp at t=5
|
||||
testClock.pin(days(5));
|
||||
backupManager.createMessageBackupUploadDescriptor(backupUser(backupId, BackupCredentialType.MESSAGES, BackupLevel.PAID)).join();
|
||||
backupManager.createMessageBackupUploadDescriptor(backupUser(backupId, BackupCredentialType.MESSAGES, BackupLevel.PAID));
|
||||
|
||||
// refreshed messages timestamp at t=6
|
||||
testClock.pin(days(6));
|
||||
backupManager.createMessageBackupUploadDescriptor(backupUser(backupId, BackupCredentialType.MESSAGES, BackupLevel.FREE)).join();
|
||||
backupManager.createMessageBackupUploadDescriptor(backupUser(backupId, BackupCredentialType.MESSAGES, BackupLevel.FREE));
|
||||
|
||||
Function<Instant, List<ExpiredBackup>> getExpired = time -> backupManager
|
||||
.getExpiredBackups(1, Schedulers.immediate(), time)
|
||||
@@ -972,9 +926,9 @@ public class BackupManagerTest {
|
||||
|
||||
@ParameterizedTest
|
||||
@EnumSource(mode = EnumSource.Mode.INCLUDE, names = {"MEDIA", "ALL"})
|
||||
public void expireBackup(ExpiredBackup.ExpirationType expirationType) {
|
||||
public void expireBackup(ExpiredBackup.ExpirationType expirationType) throws BackupException {
|
||||
final AuthenticatedBackupUser backupUser = backupUser(TestRandomUtil.nextBytes(16), BackupCredentialType.MESSAGES, BackupLevel.PAID);
|
||||
backupManager.createMessageBackupUploadDescriptor(backupUser).join();
|
||||
backupManager.createMessageBackupUploadDescriptor(backupUser);
|
||||
|
||||
final String expectedPrefixToDelete = switch (expirationType) {
|
||||
case ALL -> backupUser.backupDir();
|
||||
@@ -1006,11 +960,9 @@ public class BackupManagerTest {
|
||||
|
||||
if (expirationType == ExpiredBackup.ExpirationType.ALL) {
|
||||
// should have deleted the db row for the backup
|
||||
assertThat(CompletableFutureTestUtil.assertFailsWithCause(
|
||||
StatusRuntimeException.class,
|
||||
backupsDb.describeBackup(backupUser))
|
||||
.getStatus().getCode())
|
||||
.isEqualTo(Status.NOT_FOUND.getCode());
|
||||
CompletableFutureTestUtil.assertFailsWithCause(
|
||||
BackupNotFoundException.class,
|
||||
backupsDb.describeBackup(backupUser));
|
||||
} else {
|
||||
// should have deleted all the media, but left the backup descriptor in place
|
||||
assertThatNoException().isThrownBy(() -> backupsDb.describeBackup(backupUser).join());
|
||||
@@ -1018,9 +970,9 @@ public class BackupManagerTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void deleteBackupPaginated() {
|
||||
public void deleteBackupPaginated() throws BackupException {
|
||||
final AuthenticatedBackupUser backupUser = backupUser(TestRandomUtil.nextBytes(16), BackupCredentialType.MESSAGES, BackupLevel.PAID);
|
||||
backupManager.createMessageBackupUploadDescriptor(backupUser).join();
|
||||
backupManager.createMessageBackupUploadDescriptor(backupUser);
|
||||
|
||||
final ExpiredBackup expiredBackup = expiredBackup(ExpiredBackup.ExpirationType.MEDIA, backupUser);
|
||||
final String mediaPrefix = expiredBackup.prefixToDelete() + "/";
|
||||
@@ -1056,7 +1008,7 @@ public class BackupManagerTest {
|
||||
|
||||
@ParameterizedTest
|
||||
@EnumSource(BackupLevel.class)
|
||||
void svrbAuthValid(BackupLevel backupLevel) {
|
||||
void svrbAuthValid(BackupLevel backupLevel) throws BackupException {
|
||||
testClock.pin(Instant.ofEpochSecond(123));
|
||||
final AuthenticatedBackupUser backupUser =
|
||||
backupUser(TestRandomUtil.nextBytes(16), BackupCredentialType.MESSAGES, backupLevel);
|
||||
@@ -1073,29 +1025,26 @@ public class BackupManagerTest {
|
||||
// Can't use MEDIA for svrb auth
|
||||
final AuthenticatedBackupUser backupUser =
|
||||
backupUser(TestRandomUtil.nextBytes(16), BackupCredentialType.MEDIA, backupLevel);
|
||||
assertThatExceptionOfType(StatusRuntimeException.class)
|
||||
.isThrownBy(() -> backupManager.generateSvrbAuth(backupUser))
|
||||
.extracting(StatusRuntimeException::getStatus)
|
||||
.extracting(Status::getCode)
|
||||
.isEqualTo(Status.Code.UNAUTHENTICATED);
|
||||
assertThatExceptionOfType(BackupWrongCredentialTypeException.class)
|
||||
.isThrownBy(() -> backupManager.generateSvrbAuth(backupUser));
|
||||
}
|
||||
|
||||
private CopyResult copyError(final AuthenticatedBackupUser backupUser, Throwable copyException) {
|
||||
private CopyResult copyError(final AuthenticatedBackupUser backupUser, Throwable copyException) throws BackupException {
|
||||
when(tusCredentialGenerator.generateUpload(any()))
|
||||
.thenReturn(new BackupUploadDescriptor(3, "def", Collections.emptyMap(), ""));
|
||||
when(remoteStorageManager.copy(eq(3), eq(COPY_PARAM.sourceKey()), eq(COPY_PARAM.sourceLength()), any(), any()))
|
||||
.thenReturn(CompletableFuture.failedFuture(copyException));
|
||||
return backupManager.copyToBackup(backupUser, List.of(COPY_PARAM)).single().block();
|
||||
return backupManager.copyToBackup(backupManager.getCopyQuota(backupUser, List.of(COPY_PARAM))).single().block();
|
||||
}
|
||||
|
||||
private CopyResult copy(final AuthenticatedBackupUser backupUser) {
|
||||
private CopyResult copy(final AuthenticatedBackupUser backupUser) throws BackupException {
|
||||
when(tusCredentialGenerator.generateUpload(any()))
|
||||
.thenReturn(new BackupUploadDescriptor(3, "def", Collections.emptyMap(), ""));
|
||||
when(tusCredentialGenerator.generateUpload(any()))
|
||||
.thenReturn(new BackupUploadDescriptor(3, "def", Collections.emptyMap(), ""));
|
||||
when(remoteStorageManager.copy(eq(3), eq(COPY_PARAM.sourceKey()), eq(COPY_PARAM.sourceLength()), any(), any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(null));
|
||||
return backupManager.copyToBackup(backupUser, List.of(COPY_PARAM)).single().block();
|
||||
return backupManager.copyToBackup(backupManager.getCopyQuota(backupUser, List.of(COPY_PARAM))).single().block();
|
||||
}
|
||||
|
||||
private static ExpiredBackup expiredBackup(final ExpiredBackup.ExpirationType expirationType,
|
||||
|
||||
@@ -8,8 +8,6 @@ package org.whispersystems.textsecuregcm.backup;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import io.grpc.Status;
|
||||
import io.grpc.StatusRuntimeException;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.time.temporal.ChronoUnit;
|
||||
@@ -212,10 +210,9 @@ public class BackupsDbTest {
|
||||
backupsDb.finishExpiration(opt.get()).join();
|
||||
|
||||
// The backup entry should be gone
|
||||
assertThat(CompletableFutureTestUtil.assertFailsWithCause(StatusRuntimeException.class,
|
||||
backupsDb.describeBackup(backupUser(backupId, BackupCredentialType.MEDIA, BackupLevel.PAID)))
|
||||
.getStatus().getCode())
|
||||
.isEqualTo(Status.Code.NOT_FOUND);
|
||||
CompletableFutureTestUtil.assertFailsWithCause(
|
||||
BackupNotFoundException.class,
|
||||
backupsDb.describeBackup(backupUser(backupId, BackupCredentialType.MEDIA, BackupLevel.PAID)));
|
||||
assertThat(expiredBackups.apply(Instant.ofEpochSecond(10))).isEmpty();
|
||||
}
|
||||
}
|
||||
|
||||
+60
-69
@@ -8,6 +8,7 @@ package org.whispersystems.textsecuregcm.controllers;
|
||||
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.doThrow;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.reset;
|
||||
import static org.mockito.Mockito.verify;
|
||||
@@ -16,7 +17,6 @@ import static org.mockito.Mockito.when;
|
||||
import io.dropwizard.auth.AuthValueFactoryProvider;
|
||||
import io.dropwizard.testing.junit5.DropwizardExtensionsSupport;
|
||||
import io.dropwizard.testing.junit5.ResourceExtension;
|
||||
import io.grpc.Status;
|
||||
import jakarta.ws.rs.client.Entity;
|
||||
import jakarta.ws.rs.client.Invocation;
|
||||
import jakarta.ws.rs.client.WebTarget;
|
||||
@@ -33,7 +33,6 @@ import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.stream.IntStream;
|
||||
import java.util.stream.Stream;
|
||||
import org.glassfish.jersey.server.ServerProperties;
|
||||
@@ -67,10 +66,16 @@ import org.whispersystems.textsecuregcm.auth.ExternalServiceCredentials;
|
||||
import org.whispersystems.textsecuregcm.auth.RedemptionRange;
|
||||
import org.whispersystems.textsecuregcm.backup.BackupAuthManager;
|
||||
import org.whispersystems.textsecuregcm.backup.BackupAuthTestUtil;
|
||||
import org.whispersystems.textsecuregcm.backup.BackupException;
|
||||
import org.whispersystems.textsecuregcm.backup.BackupFailedZkAuthenticationException;
|
||||
import org.whispersystems.textsecuregcm.backup.BackupInvalidArgumentException;
|
||||
import org.whispersystems.textsecuregcm.backup.BackupManager;
|
||||
import org.whispersystems.textsecuregcm.backup.BackupNotFoundException;
|
||||
import org.whispersystems.textsecuregcm.backup.BackupPermissionException;
|
||||
import org.whispersystems.textsecuregcm.backup.BackupUploadDescriptor;
|
||||
import org.whispersystems.textsecuregcm.backup.CopyResult;
|
||||
import org.whispersystems.textsecuregcm.entities.RemoteAttachment;
|
||||
import org.whispersystems.textsecuregcm.mappers.BackupExceptionMapper;
|
||||
import org.whispersystems.textsecuregcm.mappers.CompletionExceptionMapper;
|
||||
import org.whispersystems.textsecuregcm.mappers.GrpcStatusRuntimeExceptionMapper;
|
||||
import org.whispersystems.textsecuregcm.mappers.RateLimitExceededExceptionMapper;
|
||||
@@ -96,6 +101,7 @@ public class ArchiveControllerTest {
|
||||
.addProvider(new AuthValueFactoryProvider.Binder<>(AuthenticatedDevice.class))
|
||||
.addProvider(new CompletionExceptionMapper())
|
||||
.addResource(new GrpcStatusRuntimeExceptionMapper())
|
||||
.addResource(new BackupExceptionMapper())
|
||||
.addProvider(new RateLimitExceededExceptionMapper())
|
||||
.setMapper(SystemMapper.jsonMapper())
|
||||
.setTestContainerFactory(new GrizzlyWebTestContainerFactory())
|
||||
@@ -111,8 +117,8 @@ public class ArchiveControllerTest {
|
||||
reset(backupAuthManager);
|
||||
reset(backupManager);
|
||||
|
||||
when(accountsManager.getByAccountIdentifierAsync(AuthHelper.VALID_UUID))
|
||||
.thenReturn(CompletableFuture.completedFuture(Optional.of(AuthHelper.VALID_ACCOUNT)));
|
||||
when(accountsManager.getByAccountIdentifier(AuthHelper.VALID_UUID))
|
||||
.thenReturn(Optional.of(AuthHelper.VALID_ACCOUNT));
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@@ -164,9 +170,7 @@ public class ArchiveControllerTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void setBackupId() {
|
||||
when(backupAuthManager.commitBackupId(any(), any(), any(), any())).thenReturn(CompletableFuture.completedFuture(null));
|
||||
|
||||
public void setBackupId() throws RateLimitExceededException, BackupInvalidArgumentException, BackupPermissionException {
|
||||
final Response response = resources.getJerseyTest()
|
||||
.target("v1/archives/backupid")
|
||||
.request()
|
||||
@@ -184,9 +188,8 @@ public class ArchiveControllerTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void setBackupIdPartial() {
|
||||
when(backupAuthManager.commitBackupId(any(), any(), any(), any())).thenReturn(CompletableFuture.completedFuture(null));
|
||||
|
||||
public void setBackupIdPartial()
|
||||
throws RateLimitExceededException, BackupInvalidArgumentException, BackupPermissionException {
|
||||
final Response response = resources.getJerseyTest()
|
||||
.target("v1/archives/backupid")
|
||||
.request()
|
||||
@@ -210,8 +213,7 @@ public class ArchiveControllerTest {
|
||||
})
|
||||
public void backupIdLimits(boolean hasPermits, long waitSeconds) {
|
||||
when(backupAuthManager.checkBackupIdRotationLimit(any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(
|
||||
new BackupAuthManager.BackupIdRotationLimit(hasPermits, Duration.ofSeconds(waitSeconds))));
|
||||
.thenReturn(new BackupAuthManager.BackupIdRotationLimit(hasPermits, Duration.ofSeconds(waitSeconds)));
|
||||
|
||||
final ArchiveController.BackupIdLimitResponse response = resources.getJerseyTest()
|
||||
.target("v1/archives/backupid/limits")
|
||||
@@ -233,7 +235,6 @@ public class ArchiveControllerTest {
|
||||
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));
|
||||
|
||||
final Response response = resources.getJerseyTest()
|
||||
.target("v1/archives/redeem-receipt")
|
||||
@@ -248,8 +249,6 @@ public class ArchiveControllerTest {
|
||||
|
||||
@Test
|
||||
public void setBadPublicKey() throws VerificationFailedException {
|
||||
when(backupManager.setPublicKey(any(), any(), any())).thenReturn(CompletableFuture.completedFuture(null));
|
||||
|
||||
final BackupAuthCredentialPresentation presentation = backupAuthTestUtil.getPresentation(
|
||||
BackupLevel.PAID, messagesBackupKey, aci);
|
||||
final Response response = resources.getJerseyTest()
|
||||
@@ -265,8 +264,6 @@ public class ArchiveControllerTest {
|
||||
|
||||
@Test
|
||||
public void setMissingPublicKey() throws VerificationFailedException {
|
||||
when(backupManager.setPublicKey(any(), any(), any())).thenReturn(CompletableFuture.completedFuture(null));
|
||||
|
||||
final BackupAuthCredentialPresentation presentation = backupAuthTestUtil.getPresentation(
|
||||
BackupLevel.PAID, messagesBackupKey, aci);
|
||||
final Response response = resources.getJerseyTest()
|
||||
@@ -280,8 +277,6 @@ public class ArchiveControllerTest {
|
||||
|
||||
@Test
|
||||
public void setPublicKey() throws VerificationFailedException {
|
||||
when(backupManager.setPublicKey(any(), any(), any())).thenReturn(CompletableFuture.completedFuture(null));
|
||||
|
||||
final BackupAuthCredentialPresentation presentation = backupAuthTestUtil.getPresentation(
|
||||
BackupLevel.PAID, messagesBackupKey, aci);
|
||||
final Response response = resources.getJerseyTest()
|
||||
@@ -312,20 +307,17 @@ public class ArchiveControllerTest {
|
||||
|
||||
public static Stream<Arguments> setBackupIdException() {
|
||||
return Stream.of(
|
||||
Arguments.of(new RateLimitExceededException(null), false, 429),
|
||||
Arguments.of(Status.INVALID_ARGUMENT.withDescription("async").asRuntimeException(), false, 400),
|
||||
Arguments.of(Status.INVALID_ARGUMENT.withDescription("sync").asRuntimeException(), true, 400)
|
||||
Arguments.of(new RateLimitExceededException(null), 429),
|
||||
Arguments.of(new BackupInvalidArgumentException("test"), 400),
|
||||
Arguments.of(new BackupPermissionException("test"), 403)
|
||||
);
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@MethodSource
|
||||
public void setBackupIdException(final Exception ex, final boolean sync, final int expectedStatus) {
|
||||
if (sync) {
|
||||
when(backupAuthManager.commitBackupId(any(), any(), any(), any())).thenThrow(ex);
|
||||
} else {
|
||||
when(backupAuthManager.commitBackupId(any(), any(), any(), any())).thenReturn(CompletableFuture.failedFuture(ex));
|
||||
}
|
||||
public void setBackupIdException(final Exception ex, final int expectedStatus)
|
||||
throws RateLimitExceededException, BackupInvalidArgumentException, BackupPermissionException {
|
||||
doThrow(ex).when(backupAuthManager).commitBackupId(any(), any(), any(), any());
|
||||
final Response response = resources.getJerseyTest()
|
||||
.target("v1/archives/backupid")
|
||||
.request()
|
||||
@@ -338,7 +330,7 @@ public class ArchiveControllerTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void getCredentials() {
|
||||
public void getCredentials() throws BackupNotFoundException {
|
||||
final Instant start = Instant.now().truncatedTo(ChronoUnit.DAYS);
|
||||
final Instant end = start.plus(Duration.ofDays(1));
|
||||
final RedemptionRange expectedRange = RedemptionRange.inclusive(Clock.systemUTC(), start, end);
|
||||
@@ -347,9 +339,12 @@ public class ArchiveControllerTest {
|
||||
EnumMapUtil.toEnumMap(BackupCredentialType.class, credentialType -> backupAuthTestUtil.getCredentials(
|
||||
BackupLevel.PAID, backupAuthTestUtil.getRequest(messagesBackupKey, aci), credentialType, start, end));
|
||||
|
||||
expectedCredentialsByType.forEach((credentialType, expectedCredentials) ->
|
||||
for (Map.Entry<BackupCredentialType, List<BackupAuthManager.Credential>> entry : expectedCredentialsByType.entrySet()) {
|
||||
final BackupCredentialType credentialType = entry.getKey();
|
||||
final List<BackupAuthManager.Credential> expectedCredentials = entry.getValue();
|
||||
when(backupAuthManager.getBackupAuthCredentials(any(), eq(credentialType), eq(expectedRange)))
|
||||
.thenReturn(CompletableFuture.completedFuture(expectedCredentials)));
|
||||
.thenReturn(expectedCredentials);
|
||||
}
|
||||
|
||||
final ArchiveController.BackupAuthCredentialsResponse credentialResponse = resources.getJerseyTest()
|
||||
.target("v1/archives/auth")
|
||||
@@ -401,13 +396,13 @@ public class ArchiveControllerTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void getBackupInfo() throws VerificationFailedException {
|
||||
public void getBackupInfo() throws VerificationFailedException, BackupException {
|
||||
final BackupAuthCredentialPresentation presentation = backupAuthTestUtil.getPresentation(
|
||||
BackupLevel.PAID, messagesBackupKey, aci);
|
||||
when(backupManager.authenticateBackupUser(any(), any(), any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(backupUser(presentation.getBackupId(), BackupCredentialType.MESSAGES, BackupLevel.PAID)));
|
||||
when(backupManager.backupInfo(any())).thenReturn(CompletableFuture.completedFuture(new BackupManager.BackupInfo(
|
||||
1, "myBackupDir", "myMediaDir", "filename", Optional.empty())));
|
||||
.thenReturn(backupUser(presentation.getBackupId(), BackupCredentialType.MESSAGES, BackupLevel.PAID));
|
||||
when(backupManager.backupInfo(any()))
|
||||
.thenReturn(new BackupManager.BackupInfo(1, "myBackupDir", "myMediaDir", "filename", Optional.empty()));
|
||||
final ArchiveController.BackupInfoResponse response = resources.getJerseyTest()
|
||||
.target("v1/archives")
|
||||
.request()
|
||||
@@ -421,13 +416,13 @@ public class ArchiveControllerTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void putMediaBatchSuccess() throws VerificationFailedException {
|
||||
public void putMediaBatchSuccess() throws VerificationFailedException, BackupException {
|
||||
final BackupAuthCredentialPresentation presentation = backupAuthTestUtil.getPresentation(
|
||||
BackupLevel.PAID, messagesBackupKey, aci);
|
||||
when(backupManager.authenticateBackupUser(any(), any(), any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(backupUser(presentation.getBackupId(), BackupCredentialType.MESSAGES, BackupLevel.PAID)));
|
||||
.thenReturn(backupUser(presentation.getBackupId(), BackupCredentialType.MESSAGES, BackupLevel.PAID));
|
||||
final byte[][] mediaIds = new byte[][]{TestRandomUtil.nextBytes(15), TestRandomUtil.nextBytes(15)};
|
||||
when(backupManager.copyToBackup(any(), any()))
|
||||
when(backupManager.copyToBackup(any()))
|
||||
.thenReturn(Flux.just(
|
||||
new CopyResult(CopyResult.Outcome.SUCCESS, mediaIds[0], 1),
|
||||
new CopyResult(CopyResult.Outcome.SUCCESS, mediaIds[1], 1)));
|
||||
@@ -465,15 +460,15 @@ public class ArchiveControllerTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void putMediaBatchPartialFailure() throws VerificationFailedException {
|
||||
public void putMediaBatchPartialFailure() throws VerificationFailedException, BackupException {
|
||||
|
||||
final BackupAuthCredentialPresentation presentation = backupAuthTestUtil.getPresentation(
|
||||
BackupLevel.PAID, messagesBackupKey, aci);
|
||||
when(backupManager.authenticateBackupUser(any(), any(), any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(backupUser(presentation.getBackupId(), BackupCredentialType.MESSAGES, BackupLevel.PAID)));
|
||||
.thenReturn(backupUser(presentation.getBackupId(), BackupCredentialType.MESSAGES, BackupLevel.PAID));
|
||||
|
||||
final byte[][] mediaIds = IntStream.range(0, 4).mapToObj(i -> TestRandomUtil.nextBytes(15)).toArray(byte[][]::new);
|
||||
when(backupManager.copyToBackup(any(), any()))
|
||||
when(backupManager.copyToBackup(any()))
|
||||
.thenReturn(Flux.just(
|
||||
new CopyResult(CopyResult.Outcome.SUCCESS, mediaIds[0], 1),
|
||||
new CopyResult(CopyResult.Outcome.SOURCE_NOT_FOUND, mediaIds[1], null),
|
||||
@@ -524,11 +519,11 @@ public class ArchiveControllerTest {
|
||||
|
||||
|
||||
@Test
|
||||
public void copyMediaWithNegativeLength() throws VerificationFailedException {
|
||||
public void copyMediaWithNegativeLength() throws VerificationFailedException, BackupException {
|
||||
final BackupAuthCredentialPresentation presentation = backupAuthTestUtil.getPresentation(
|
||||
BackupLevel.PAID, messagesBackupKey, aci);
|
||||
when(backupManager.authenticateBackupUser(any(), any(), any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(backupUser(presentation.getBackupId(), BackupCredentialType.MESSAGES, BackupLevel.PAID)));
|
||||
.thenReturn(backupUser(presentation.getBackupId(), BackupCredentialType.MESSAGES, BackupLevel.PAID));
|
||||
final byte[][] mediaIds = new byte[][]{TestRandomUtil.nextBytes(15), TestRandomUtil.nextBytes(15)};
|
||||
final Response r = resources.getJerseyTest()
|
||||
.target("v1/archives/media/batch")
|
||||
@@ -557,21 +552,21 @@ public class ArchiveControllerTest {
|
||||
public void list(
|
||||
@CartesianTest.Values(booleans = {true, false}) final boolean cursorProvided,
|
||||
@CartesianTest.Values(booleans = {true, false}) final boolean cursorReturned)
|
||||
throws VerificationFailedException {
|
||||
throws VerificationFailedException, BackupException {
|
||||
final BackupAuthCredentialPresentation presentation = backupAuthTestUtil.getPresentation(
|
||||
BackupLevel.PAID, messagesBackupKey, aci);
|
||||
when(backupManager.authenticateBackupUser(any(), any(), any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(backupUser(presentation.getBackupId(), BackupCredentialType.MESSAGES, BackupLevel.PAID)));
|
||||
.thenReturn(backupUser(presentation.getBackupId(), BackupCredentialType.MESSAGES, BackupLevel.PAID));
|
||||
|
||||
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();
|
||||
|
||||
when(backupManager.list(any(), eq(expectedCursor), eq(17)))
|
||||
.thenReturn(CompletableFuture.completedFuture(new BackupManager.ListMediaResult(
|
||||
.thenReturn(new BackupManager.ListMediaResult(
|
||||
List.of(new BackupManager.StorageDescriptorWithLength(1, mediaId, 100)),
|
||||
returnedCursor
|
||||
)));
|
||||
));
|
||||
|
||||
WebTarget target = resources.getJerseyTest()
|
||||
.target("v1/archives/media/")
|
||||
@@ -592,11 +587,11 @@ public class ArchiveControllerTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void delete() throws VerificationFailedException {
|
||||
public void delete() throws VerificationFailedException, BackupException {
|
||||
final BackupAuthCredentialPresentation presentation = backupAuthTestUtil.getPresentation(BackupLevel.PAID,
|
||||
messagesBackupKey, aci);
|
||||
when(backupManager.authenticateBackupUser(any(), any(), any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(backupUser(presentation.getBackupId(), BackupCredentialType.MESSAGES, BackupLevel.PAID)));
|
||||
.thenReturn(backupUser(presentation.getBackupId(), BackupCredentialType.MESSAGES, BackupLevel.PAID));
|
||||
|
||||
final ArchiveController.DeleteMedia deleteRequest = new ArchiveController.DeleteMedia(
|
||||
IntStream
|
||||
@@ -628,14 +623,13 @@ public class ArchiveControllerTest {
|
||||
|
||||
@ParameterizedTest
|
||||
@MethodSource
|
||||
public void messagesUploadForm(Optional<Long> uploadLength, boolean expectSuccess) throws VerificationFailedException {
|
||||
public void messagesUploadForm(Optional<Long> uploadLength, boolean expectSuccess) throws VerificationFailedException, BackupException {
|
||||
final BackupAuthCredentialPresentation presentation =
|
||||
backupAuthTestUtil.getPresentation(BackupLevel.PAID, messagesBackupKey, aci);
|
||||
when(backupManager.authenticateBackupUser(any(), any(), any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(backupUser(presentation.getBackupId(), BackupCredentialType.MESSAGES, BackupLevel.PAID)));
|
||||
.thenReturn(backupUser(presentation.getBackupId(), BackupCredentialType.MESSAGES, BackupLevel.PAID));
|
||||
when(backupManager.createMessageBackupUploadDescriptor(any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(
|
||||
new BackupUploadDescriptor(3, "abc", Map.of("k", "v"), "example.org")));
|
||||
.thenReturn(new BackupUploadDescriptor(3, "abc", Map.of("k", "v"), "example.org"));
|
||||
|
||||
final WebTarget builder = resources.getJerseyTest().target("v1/archives/upload/form");
|
||||
final Response response = uploadLength
|
||||
@@ -658,14 +652,13 @@ public class ArchiveControllerTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void mediaUploadForm() throws VerificationFailedException {
|
||||
public void mediaUploadForm() throws VerificationFailedException, BackupException, RateLimitExceededException {
|
||||
final BackupAuthCredentialPresentation presentation =
|
||||
backupAuthTestUtil.getPresentation(BackupLevel.PAID, messagesBackupKey, aci);
|
||||
when(backupManager.authenticateBackupUser(any(), any(), any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(backupUser(presentation.getBackupId(), BackupCredentialType.MESSAGES, BackupLevel.PAID)));
|
||||
.thenReturn(backupUser(presentation.getBackupId(), BackupCredentialType.MESSAGES, BackupLevel.PAID));
|
||||
when(backupManager.createTemporaryAttachmentUploadDescriptor(any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(
|
||||
new BackupUploadDescriptor(3, "abc", Map.of("k", "v"), "example.org")));
|
||||
.thenReturn(new BackupUploadDescriptor(3, "abc", Map.of("k", "v"), "example.org"));
|
||||
final ArchiveController.UploadDescriptorResponse desc = resources.getJerseyTest()
|
||||
.target("v1/archives/media/upload/form")
|
||||
.request()
|
||||
@@ -678,8 +671,7 @@ public class ArchiveControllerTest {
|
||||
assertThat(desc.signedUploadLocation()).isEqualTo("example.org");
|
||||
|
||||
// rate limit
|
||||
when(backupManager.createTemporaryAttachmentUploadDescriptor(any()))
|
||||
.thenReturn(CompletableFuture.failedFuture(new RateLimitExceededException(null)));
|
||||
when(backupManager.createTemporaryAttachmentUploadDescriptor(any())).thenThrow(new RateLimitExceededException(null));
|
||||
final Response response = resources.getJerseyTest()
|
||||
.target("v1/archives/media/upload/form")
|
||||
.request()
|
||||
@@ -690,11 +682,11 @@ public class ArchiveControllerTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void readAuth() throws VerificationFailedException {
|
||||
public void readAuth() throws VerificationFailedException, BackupException {
|
||||
final BackupAuthCredentialPresentation presentation =
|
||||
backupAuthTestUtil.getPresentation(BackupLevel.PAID, messagesBackupKey, aci);
|
||||
when(backupManager.authenticateBackupUser(any(), any(), any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(backupUser(presentation.getBackupId(), BackupCredentialType.MESSAGES, BackupLevel.PAID)));
|
||||
.thenReturn(backupUser(presentation.getBackupId(), BackupCredentialType.MESSAGES, BackupLevel.PAID));
|
||||
when(backupManager.generateReadAuth(any(), eq(3))).thenReturn(Map.of("key", "value"));
|
||||
final ArchiveController.ReadAuthResponse response = resources.getJerseyTest()
|
||||
.target("v1/archives/auth/read")
|
||||
@@ -708,11 +700,11 @@ public class ArchiveControllerTest {
|
||||
|
||||
|
||||
@Test
|
||||
public void svrbAuth() throws VerificationFailedException {
|
||||
public void svrbAuth() throws VerificationFailedException, BackupException {
|
||||
final BackupAuthCredentialPresentation presentation =
|
||||
backupAuthTestUtil.getPresentation(BackupLevel.PAID, messagesBackupKey, aci);
|
||||
when(backupManager.authenticateBackupUser(any(), any(), any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(backupUser(presentation.getBackupId(), BackupCredentialType.MESSAGES, BackupLevel.PAID)));
|
||||
.thenReturn(backupUser(presentation.getBackupId(), BackupCredentialType.MESSAGES, BackupLevel.PAID));
|
||||
final ExternalServiceCredentials credentials = new ExternalServiceCredentials("username", "password");
|
||||
when(backupManager.generateSvrbAuth(any())).thenReturn(credentials);
|
||||
final ExternalServiceCredentials response = resources.getJerseyTest()
|
||||
@@ -725,7 +717,7 @@ public class ArchiveControllerTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void readAuthInvalidParam() throws VerificationFailedException {
|
||||
public void readAuthInvalidParam() throws VerificationFailedException, BackupException {
|
||||
final BackupAuthCredentialPresentation presentation =
|
||||
backupAuthTestUtil.getPresentation(BackupLevel.PAID, messagesBackupKey, aci);
|
||||
Response response = resources.getJerseyTest()
|
||||
@@ -747,12 +739,11 @@ public class ArchiveControllerTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void deleteEntireBackup() throws VerificationFailedException {
|
||||
public void deleteEntireBackup() throws VerificationFailedException, BackupException {
|
||||
final BackupAuthCredentialPresentation presentation =
|
||||
backupAuthTestUtil.getPresentation(BackupLevel.PAID, messagesBackupKey, aci);
|
||||
when(backupManager.authenticateBackupUser(any(), any(), any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(backupUser(presentation.getBackupId(), BackupCredentialType.MESSAGES, BackupLevel.PAID)));
|
||||
when(backupManager.deleteEntireBackup(any())).thenReturn(CompletableFuture.completedFuture(null));
|
||||
.thenReturn(backupUser(presentation.getBackupId(), BackupCredentialType.MESSAGES, BackupLevel.PAID));
|
||||
Response response = resources.getJerseyTest()
|
||||
.target("v1/archives/")
|
||||
.request()
|
||||
@@ -763,11 +754,11 @@ public class ArchiveControllerTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void invalidSourceAttachmentKey() throws VerificationFailedException {
|
||||
public void invalidSourceAttachmentKey() throws VerificationFailedException, BackupException {
|
||||
final BackupAuthCredentialPresentation presentation = backupAuthTestUtil.getPresentation(
|
||||
BackupLevel.PAID, messagesBackupKey, aci);
|
||||
when(backupManager.authenticateBackupUser(any(), any(), any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(backupUser(presentation.getBackupId(), BackupCredentialType.MESSAGES, BackupLevel.PAID)));
|
||||
.thenReturn(backupUser(presentation.getBackupId(), BackupCredentialType.MESSAGES, BackupLevel.PAID));
|
||||
final Response r = resources.getJerseyTest()
|
||||
.target("v1/archives/media")
|
||||
.request()
|
||||
|
||||
+68
-85
@@ -23,8 +23,9 @@ import java.time.Instant;
|
||||
import java.time.ZoneId;
|
||||
import java.time.temporal.ChronoUnit;
|
||||
import java.util.Base64;
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.stream.Stream;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.glassfish.jersey.test.grizzly.GrizzlyWebTestContainerFactory;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
@@ -53,57 +54,60 @@ import org.whispersystems.textsecuregcm.storage.AccountsManager;
|
||||
import org.whispersystems.textsecuregcm.tests.util.AuthHelper;
|
||||
import org.whispersystems.textsecuregcm.util.HeaderUtils;
|
||||
import org.whispersystems.textsecuregcm.util.SystemMapper;
|
||||
import org.whispersystems.textsecuregcm.util.UUIDUtil;
|
||||
|
||||
@ExtendWith(DropwizardExtensionsSupport.class)
|
||||
class CertificateControllerTest {
|
||||
|
||||
private static final ECPublicKey caPublicKey;
|
||||
private static final ECPublicKey CA_PUBLIC_KEY;
|
||||
private static final byte[] SIGNING_CERTIFICATE_DATA;
|
||||
private static final CertificateGenerator CERTIFICATE_GENERATOR;
|
||||
private static final ServerCertificate.Certificate SIGNING_CERTIFICATE;
|
||||
|
||||
static {
|
||||
try {
|
||||
caPublicKey = new ECPublicKey(Base64.getDecoder().decode("BWh+UOhT1hD8bkb+MFRvb6tVqhoG8YYGCzOd7mgjo8cV"));
|
||||
} catch (InvalidKeyException e) {
|
||||
throw new AssertionError("Statically-defined key was invalid", e);
|
||||
}
|
||||
}
|
||||
|
||||
@SuppressWarnings("unused")
|
||||
private static final String caPrivateKey = "EO3Mnf0kfVlVnwSaqPoQnAxhnnGL1JTdXqktCKEe9Eo=";
|
||||
|
||||
private static final String signingCertificate = "CiUIDBIhBbTz4h1My+tt+vw+TVscgUe/DeHS0W02tPWAWbTO2xc3EkD+go4bJnU0AcnFfbOLKoiBfCzouZtDYMOVi69rE7r4U9cXREEqOkUmU2WJBjykAxWPCcSTmVTYHDw7hkSp/puG";
|
||||
private static final String signingKey = "ABOxG29xrfq4E7IrW11Eg7+HBbtba9iiS0500YoBjn4=";
|
||||
|
||||
private static final ServerSecretParams serverSecretParams = ServerSecretParams.generate();
|
||||
private static final ServerSecretParams SERVER_SECRET_PARAMS = ServerSecretParams.generate();
|
||||
|
||||
private static final GenericServerSecretParams genericServerSecretParams = GenericServerSecretParams.generate();
|
||||
private static final CertificateGenerator certificateGenerator;
|
||||
private static final ServerZkAuthOperations serverZkAuthOperations;
|
||||
|
||||
private static final ServerZkAuthOperations SERVER_ZK_AUTH_OPERATIONS;
|
||||
private static final Clock clock = Clock.fixed(Instant.now(), ZoneId.systemDefault());
|
||||
|
||||
private static final AccountsManager accountsManager = mock(AccountsManager.class);
|
||||
private static final AccountsManager ACCOUNTS_MANAGER = mock(AccountsManager.class);
|
||||
|
||||
static {
|
||||
try {
|
||||
certificateGenerator = new CertificateGenerator(Base64.getDecoder().decode(signingCertificate),
|
||||
new ECPrivateKey(Base64.getDecoder().decode(signingKey)), 1);
|
||||
serverZkAuthOperations = new ServerZkAuthOperations(serverSecretParams);
|
||||
CA_PUBLIC_KEY = new ECPrivateKey(Base64.getDecoder().decode("EO3Mnf0kfVlVnwSaqPoQnAxhnnGL1JTdXqktCKEe9Eo="))
|
||||
.publicKey();
|
||||
SIGNING_CERTIFICATE_DATA = Base64.getDecoder().decode(
|
||||
"CiUIDBIhBbTz4h1My+tt+vw+TVscgUe/DeHS0W02tPWAWbTO2xc3EkD+go4bJnU0AcnFfbOLKoiBfCzouZtDYMOVi69rE7r4U9cXREEqOkUmU2WJBjykAxWPCcSTmVTYHDw7hkSp/puG");
|
||||
final ECPrivateKey signingKey = new ECPrivateKey(Base64.getDecoder().decode("ABOxG29xrfq4E7IrW11Eg7+HBbtba9iiS0500YoBjn4="));
|
||||
|
||||
CERTIFICATE_GENERATOR = new CertificateGenerator(SIGNING_CERTIFICATE_DATA, signingKey, 1, false);
|
||||
SIGNING_CERTIFICATE = ServerCertificate.Certificate.parseFrom(
|
||||
ServerCertificate.parseFrom(SIGNING_CERTIFICATE_DATA).getCertificate());
|
||||
SERVER_ZK_AUTH_OPERATIONS = new ServerZkAuthOperations(SERVER_SECRET_PARAMS);
|
||||
} catch (IOException | InvalidKeyException e) {
|
||||
throw new AssertionError(e);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
private static final ResourceExtension resources = ResourceExtension.builder()
|
||||
.addProvider(AuthHelper.getAuthFilter())
|
||||
.addProvider(new AuthValueFactoryProvider.Binder<>(AuthenticatedDevice.class))
|
||||
.setMapper(SystemMapper.jsonMapper())
|
||||
.setTestContainerFactory(new GrizzlyWebTestContainerFactory())
|
||||
.addResource(new CertificateController(accountsManager, certificateGenerator, serverZkAuthOperations, genericServerSecretParams, clock))
|
||||
.addResource(new CertificateController(ACCOUNTS_MANAGER, CERTIFICATE_GENERATOR, SERVER_ZK_AUTH_OPERATIONS, genericServerSecretParams, clock))
|
||||
.build();
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
when(accountsManager.getByAccountIdentifier(AuthHelper.VALID_UUID)).thenReturn(Optional.of(AuthHelper.VALID_ACCOUNT));
|
||||
when(ACCOUNTS_MANAGER.getByAccountIdentifier(AuthHelper.VALID_UUID)).thenReturn(Optional.of(AuthHelper.VALID_ACCOUNT));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testSigningCertificate() throws Exception {
|
||||
final ServerCertificate fullCertificate = ServerCertificate.parseFrom(SIGNING_CERTIFICATE_DATA);
|
||||
assertTrue(CA_PUBLIC_KEY.verifySignature(fullCertificate.getCertificate().toByteArray(),
|
||||
fullCertificate.getSignature().toByteArray()));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -118,20 +122,16 @@ class CertificateControllerTest {
|
||||
SenderCertificate.Certificate certificate = SenderCertificate.Certificate.parseFrom(
|
||||
certificateHolder.getCertificate());
|
||||
|
||||
ServerCertificate serverCertificateHolder = certificate.getSigner();
|
||||
ServerCertificate.Certificate serverCertificate = ServerCertificate.Certificate.parseFrom(
|
||||
serverCertificateHolder.getCertificate());
|
||||
ECPublicKey serverPublicKey = new ECPublicKey(serverCertificate.getKey().toByteArray());
|
||||
assertEquals(SIGNING_CERTIFICATE.getId(), certificate.getSignerId());
|
||||
ECPublicKey serverPublicKey = new ECPublicKey(SIGNING_CERTIFICATE.getKey().toByteArray());
|
||||
|
||||
assertTrue(serverPublicKey.verifySignature(
|
||||
certificateHolder.getCertificate().toByteArray(), certificateHolder.getSignature().toByteArray()));
|
||||
assertTrue(caPublicKey.verifySignature(serverCertificateHolder.getCertificate().toByteArray(),
|
||||
serverCertificateHolder.getSignature().toByteArray()));
|
||||
|
||||
assertEquals(certificate.getSender(), AuthHelper.VALID_NUMBER);
|
||||
assertEquals(certificate.getSenderDevice(), 1L);
|
||||
assertEquals(AuthHelper.VALID_NUMBER, certificate.getSenderE164());
|
||||
assertEquals(1L, certificate.getSenderDevice());
|
||||
assertTrue(certificate.hasSenderUuid());
|
||||
assertEquals(AuthHelper.VALID_UUID.toString(), certificate.getSenderUuid());
|
||||
assertEquals(UUIDUtil.toByteString(AuthHelper.VALID_UUID), certificate.getSenderUuid());
|
||||
assertArrayEquals(certificate.getIdentityKey().toByteArray(), AuthHelper.VALID_IDENTITY.serialize());
|
||||
}
|
||||
|
||||
@@ -148,19 +148,15 @@ class CertificateControllerTest {
|
||||
SenderCertificate.Certificate certificate = SenderCertificate.Certificate.parseFrom(
|
||||
certificateHolder.getCertificate());
|
||||
|
||||
ServerCertificate serverCertificateHolder = certificate.getSigner();
|
||||
ServerCertificate.Certificate serverCertificate = ServerCertificate.Certificate.parseFrom(
|
||||
serverCertificateHolder.getCertificate());
|
||||
ECPublicKey serverPublicKey = new ECPublicKey(serverCertificate.getKey().toByteArray());
|
||||
assertEquals(SIGNING_CERTIFICATE.getId(), certificate.getSignerId());
|
||||
ECPublicKey serverPublicKey = new ECPublicKey(SIGNING_CERTIFICATE.getKey().toByteArray());
|
||||
|
||||
assertTrue(serverPublicKey.verifySignature(certificateHolder.getCertificate().toByteArray(),
|
||||
certificateHolder.getSignature().toByteArray()));
|
||||
assertTrue(caPublicKey.verifySignature(serverCertificateHolder.getCertificate().toByteArray(),
|
||||
serverCertificateHolder.getSignature().toByteArray()));
|
||||
|
||||
assertEquals(certificate.getSender(), AuthHelper.VALID_NUMBER);
|
||||
assertEquals(certificate.getSenderDevice(), 1L);
|
||||
assertEquals(certificate.getSenderUuid(), AuthHelper.VALID_UUID.toString());
|
||||
assertEquals(AuthHelper.VALID_NUMBER, certificate.getSenderE164());
|
||||
assertEquals(1L, certificate.getSenderDevice());
|
||||
assertEquals(certificate.getSenderUuid(), UUIDUtil.toByteString(AuthHelper.VALID_UUID));
|
||||
assertArrayEquals(certificate.getIdentityKey().toByteArray(), AuthHelper.VALID_IDENTITY.serialize());
|
||||
}
|
||||
|
||||
@@ -178,19 +174,15 @@ class CertificateControllerTest {
|
||||
SenderCertificate.Certificate certificate = SenderCertificate.Certificate.parseFrom(
|
||||
certificateHolder.getCertificate());
|
||||
|
||||
ServerCertificate serverCertificateHolder = certificate.getSigner();
|
||||
ServerCertificate.Certificate serverCertificate = ServerCertificate.Certificate.parseFrom(
|
||||
serverCertificateHolder.getCertificate());
|
||||
ECPublicKey serverPublicKey = new ECPublicKey(serverCertificate.getKey().toByteArray());
|
||||
assertEquals(SIGNING_CERTIFICATE.getId(), certificate.getSignerId());
|
||||
ECPublicKey serverPublicKey = new ECPublicKey(SIGNING_CERTIFICATE.getKey().toByteArray());
|
||||
|
||||
assertTrue(serverPublicKey.verifySignature(certificateHolder.getCertificate().toByteArray(),
|
||||
certificateHolder.getSignature().toByteArray()));
|
||||
assertTrue(caPublicKey.verifySignature(serverCertificateHolder.getCertificate().toByteArray(),
|
||||
serverCertificateHolder.getSignature().toByteArray()));
|
||||
|
||||
assertTrue(StringUtils.isBlank(certificate.getSender()));
|
||||
assertEquals(certificate.getSenderDevice(), 1L);
|
||||
assertEquals(certificate.getSenderUuid(), AuthHelper.VALID_UUID.toString());
|
||||
assertTrue(StringUtils.isBlank(certificate.getSenderE164()));
|
||||
assertEquals(1L, certificate.getSenderDevice());
|
||||
assertEquals(certificate.getSenderUuid(), UUIDUtil.toByteString(AuthHelper.VALID_UUID));
|
||||
assertArrayEquals(certificate.getIdentityKey().toByteArray(), AuthHelper.VALID_IDENTITY.serialize());
|
||||
}
|
||||
|
||||
@@ -202,7 +194,7 @@ class CertificateControllerTest {
|
||||
.header("Authorization", AuthHelper.getAuthHeader(AuthHelper.VALID_UUID, AuthHelper.INVALID_PASSWORD))
|
||||
.get();
|
||||
|
||||
assertEquals(response.getStatus(), 401);
|
||||
assertEquals(401, response.getStatus());
|
||||
}
|
||||
|
||||
|
||||
@@ -213,7 +205,7 @@ class CertificateControllerTest {
|
||||
.request()
|
||||
.get();
|
||||
|
||||
assertEquals(response.getStatus(), 401);
|
||||
assertEquals(401, response.getStatus());
|
||||
}
|
||||
|
||||
|
||||
@@ -225,7 +217,7 @@ class CertificateControllerTest {
|
||||
.header(HeaderUtils.UNIDENTIFIED_ACCESS_KEY, AuthHelper.getUnidentifiedAccessHeader("1234".getBytes()))
|
||||
.get();
|
||||
|
||||
assertEquals(response.getStatus(), 401);
|
||||
assertEquals(401, response.getStatus());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -245,35 +237,34 @@ class CertificateControllerTest {
|
||||
assertEquals(1, credentials.callLinkAuthCredentials().size());
|
||||
|
||||
assertEquals(AuthHelper.VALID_PNI, credentials.pni());
|
||||
assertEquals(startOfDay.getEpochSecond(), credentials.credentials().get(0).redemptionTime());
|
||||
assertEquals(startOfDay.getEpochSecond(), credentials.callLinkAuthCredentials().get(0).redemptionTime());
|
||||
assertEquals(startOfDay.getEpochSecond(), credentials.credentials().getFirst().redemptionTime());
|
||||
assertEquals(startOfDay.getEpochSecond(), credentials.callLinkAuthCredentials().getFirst().redemptionTime());
|
||||
|
||||
final ClientZkAuthOperations clientZkAuthOperations =
|
||||
new ClientZkAuthOperations(serverSecretParams.getPublicParams());
|
||||
new ClientZkAuthOperations(SERVER_SECRET_PARAMS.getPublicParams());
|
||||
|
||||
assertDoesNotThrow(() -> {
|
||||
clientZkAuthOperations.receiveAuthCredentialWithPniAsServiceId(
|
||||
new ServiceId.Aci(AuthHelper.VALID_UUID),
|
||||
new ServiceId.Pni(AuthHelper.VALID_PNI),
|
||||
(int) startOfDay.getEpochSecond(),
|
||||
new AuthCredentialWithPniResponse(credentials.credentials().get(0).credential()));
|
||||
new AuthCredentialWithPniResponse(credentials.credentials().getFirst().credential()));
|
||||
});
|
||||
|
||||
assertDoesNotThrow(() -> {
|
||||
new CallLinkAuthCredentialResponse(credentials.callLinkAuthCredentials().get(0).credential())
|
||||
new CallLinkAuthCredentialResponse(credentials.callLinkAuthCredentials().getFirst().credential())
|
||||
.receive(new ServiceId.Aci(AuthHelper.VALID_UUID), startOfDay, genericServerSecretParams.getPublicParams());
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetSingleGroupCredentialZkc() {
|
||||
void testGetSingleGroupCredential() {
|
||||
final Instant startOfDay = clock.instant().truncatedTo(ChronoUnit.DAYS);
|
||||
|
||||
final GroupCredentials credentials = resources.getJerseyTest()
|
||||
.target("/v1/certificate/auth/group")
|
||||
.queryParam("redemptionStartSeconds", startOfDay.getEpochSecond())
|
||||
.queryParam("redemptionEndSeconds", startOfDay.getEpochSecond())
|
||||
.queryParam("zkcCredential", true)
|
||||
.request()
|
||||
.header("Authorization", AuthHelper.getAuthHeader(AuthHelper.VALID_UUID, AuthHelper.VALID_PASSWORD))
|
||||
.get(GroupCredentials.class);
|
||||
@@ -282,22 +273,22 @@ class CertificateControllerTest {
|
||||
assertEquals(1, credentials.callLinkAuthCredentials().size());
|
||||
|
||||
assertEquals(AuthHelper.VALID_PNI, credentials.pni());
|
||||
assertEquals(startOfDay.getEpochSecond(), credentials.credentials().get(0).redemptionTime());
|
||||
assertEquals(startOfDay.getEpochSecond(), credentials.callLinkAuthCredentials().get(0).redemptionTime());
|
||||
assertEquals(startOfDay.getEpochSecond(), credentials.credentials().getFirst().redemptionTime());
|
||||
assertEquals(startOfDay.getEpochSecond(), credentials.callLinkAuthCredentials().getFirst().redemptionTime());
|
||||
|
||||
final ClientZkAuthOperations clientZkAuthOperations =
|
||||
new ClientZkAuthOperations(serverSecretParams.getPublicParams());
|
||||
new ClientZkAuthOperations(SERVER_SECRET_PARAMS.getPublicParams());
|
||||
|
||||
assertDoesNotThrow(() -> {
|
||||
clientZkAuthOperations.receiveAuthCredentialWithPniAsServiceId(
|
||||
new ServiceId.Aci(AuthHelper.VALID_UUID),
|
||||
new ServiceId.Pni(AuthHelper.VALID_PNI),
|
||||
(int) startOfDay.getEpochSecond(),
|
||||
new AuthCredentialWithPniResponse(credentials.credentials().get(0).credential()));
|
||||
new AuthCredentialWithPniResponse(credentials.credentials().getFirst().credential()));
|
||||
});
|
||||
|
||||
assertDoesNotThrow(() -> {
|
||||
new CallLinkAuthCredentialResponse(credentials.callLinkAuthCredentials().get(0).credential())
|
||||
new CallLinkAuthCredentialResponse(credentials.callLinkAuthCredentials().getFirst().credential())
|
||||
.receive(new ServiceId.Aci(AuthHelper.VALID_UUID), startOfDay, genericServerSecretParams.getPublicParams());
|
||||
});
|
||||
}
|
||||
@@ -320,7 +311,7 @@ class CertificateControllerTest {
|
||||
assertEquals(8, credentials.callLinkAuthCredentials().size());
|
||||
|
||||
final ClientZkAuthOperations clientZkAuthOperations =
|
||||
new ClientZkAuthOperations(serverSecretParams.getPublicParams());
|
||||
new ClientZkAuthOperations(SERVER_SECRET_PARAMS.getPublicParams());
|
||||
|
||||
for (int i = 0; i < 8; i++) {
|
||||
final Instant redemptionTime = startOfDay.plus(Duration.ofDays(i));
|
||||
@@ -358,23 +349,15 @@ class CertificateControllerTest {
|
||||
assertEquals(400, response.getStatus());
|
||||
}
|
||||
|
||||
private static Stream<Arguments> testBadRedemptionTimes() {
|
||||
return Stream.of(
|
||||
// Start is after end
|
||||
Arguments.of(clock.instant().plus(Duration.ofDays(1)), clock.instant()),
|
||||
|
||||
// Start is in the past
|
||||
Arguments.of(clock.instant().minus(Duration.ofDays(1)), clock.instant()),
|
||||
|
||||
// End is too far in the future
|
||||
Arguments.of(clock.instant(),
|
||||
private static Collection<Arguments> testBadRedemptionTimes() {
|
||||
return List.of(
|
||||
Arguments.argumentSet("Start is after end", clock.instant().plus(Duration.ofDays(1)), clock.instant()),
|
||||
Arguments.argumentSet("Start is in the past", clock.instant().minus(Duration.ofDays(1)), clock.instant()),
|
||||
Arguments.argumentSet("End is too far in the future", clock.instant(),
|
||||
clock.instant().plus(CertificateController.MAX_REDEMPTION_DURATION).plus(Duration.ofDays(1))),
|
||||
|
||||
// Start is not at a day boundary
|
||||
Arguments.of(clock.instant().plusSeconds(17), clock.instant().plus(Duration.ofDays(1))),
|
||||
|
||||
// End is not at a day boundary
|
||||
Arguments.of(clock.instant(), clock.instant().plusSeconds(17))
|
||||
Arguments.argumentSet("Start is not at a day boundary", clock.instant().plusSeconds(17),
|
||||
clock.instant().plus(Duration.ofDays(1))),
|
||||
Arguments.argumentSet("End is not at a day boundary", clock.instant(), clock.instant().plusSeconds(17))
|
||||
);
|
||||
}
|
||||
}
|
||||
-7
@@ -29,7 +29,6 @@ import java.util.Base64;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import org.glassfish.jersey.server.ServerProperties;
|
||||
import org.glassfish.jersey.test.grizzly.GrizzlyWebTestContainerFactory;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
@@ -45,7 +44,6 @@ import org.whispersystems.textsecuregcm.limits.RateLimiters;
|
||||
import org.whispersystems.textsecuregcm.mappers.CompletionExceptionMapper;
|
||||
import org.whispersystems.textsecuregcm.mappers.GrpcStatusRuntimeExceptionMapper;
|
||||
import org.whispersystems.textsecuregcm.mappers.RateLimitExceededExceptionMapper;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.devicecheck.AppleDeviceCheckManager;
|
||||
import org.whispersystems.textsecuregcm.storage.devicecheck.ChallengeNotFoundException;
|
||||
@@ -206,11 +204,6 @@ class DeviceCheckControllerTest {
|
||||
{"action": "backup", "challenge": "embeddedChallenge"}
|
||||
""";
|
||||
|
||||
when(backupAuthManager.extendBackupVoucher(any(), eq(new Account.BackupVoucher(
|
||||
REDEMPTION_LEVEL,
|
||||
clock.instant().plus(REDEMPTION_DURATION)))))
|
||||
.thenReturn(CompletableFuture.completedFuture(null));
|
||||
|
||||
final Response response = resources.getJerseyTest()
|
||||
.target("v1/devicecheck/assert")
|
||||
.queryParam("keyId", Base64.getUrlEncoder().encodeToString(keyId))
|
||||
|
||||
+32
-23
@@ -58,6 +58,7 @@ import org.junit.jupiter.params.provider.ValueSource;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
import org.whispersystems.textsecuregcm.captcha.AssessmentResult;
|
||||
import org.whispersystems.textsecuregcm.captcha.RegistrationCaptchaManager;
|
||||
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicCarrierDataLookupConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicRegistrationConfiguration;
|
||||
import org.whispersystems.textsecuregcm.entities.RegistrationServiceSession;
|
||||
@@ -83,6 +84,7 @@ import org.whispersystems.textsecuregcm.storage.DynamicConfigurationManager;
|
||||
import org.whispersystems.textsecuregcm.storage.PhoneNumberIdentifiers;
|
||||
import org.whispersystems.textsecuregcm.storage.RegistrationRecoveryPasswordsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.VerificationSessionManager;
|
||||
import org.whispersystems.textsecuregcm.telephony.CarrierDataProvider;
|
||||
import org.whispersystems.textsecuregcm.util.SystemMapper;
|
||||
import org.whispersystems.textsecuregcm.util.TestRemoteAddressFilterProvider;
|
||||
|
||||
@@ -106,6 +108,7 @@ class VerificationControllerTest {
|
||||
private final PhoneNumberIdentifiers phoneNumberIdentifiers = mock(PhoneNumberIdentifiers.class);
|
||||
private final RateLimiters rateLimiters = mock(RateLimiters.class);
|
||||
private final AccountsManager accountsManager = mock(AccountsManager.class);
|
||||
private final CarrierDataProvider carrierDataProvider = mock(CarrierDataProvider.class);
|
||||
private final Clock clock = Clock.systemUTC();
|
||||
|
||||
private final RateLimiter captchaLimiter = mock(RateLimiter.class);
|
||||
@@ -127,7 +130,7 @@ class VerificationControllerTest {
|
||||
.addResource(
|
||||
new VerificationController(registrationServiceClient, verificationSessionManager, pushNotificationManager,
|
||||
registrationCaptchaManager, registrationRecoveryPasswordsManager, phoneNumberIdentifiers, rateLimiters, accountsManager,
|
||||
RegistrationFraudChecker.noop(), dynamicConfigurationManager, clock))
|
||||
carrierDataProvider, RegistrationFraudChecker.noop(), dynamicConfigurationManager, clock))
|
||||
.build();
|
||||
|
||||
@BeforeEach
|
||||
@@ -140,6 +143,8 @@ class VerificationControllerTest {
|
||||
.thenReturn(Optional.empty());
|
||||
when(dynamicConfiguration.getRegistrationConfiguration())
|
||||
.thenReturn(new DynamicRegistrationConfiguration(false));
|
||||
when(dynamicConfiguration.getCarrierDataLookupConfiguration())
|
||||
.thenReturn(new DynamicCarrierDataLookupConfiguration());
|
||||
when(dynamicConfigurationManager.getConfiguration())
|
||||
.thenReturn(dynamicConfiguration);
|
||||
when(phoneNumberIdentifiers.getPhoneNumberIdentifier(NUMBER))
|
||||
@@ -388,7 +393,7 @@ class VerificationControllerTest {
|
||||
when(verificationSessionManager.findForId(any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(
|
||||
Optional.of(
|
||||
new VerificationSession(null, List.of(VerificationSession.Information.CAPTCHA), Collections.emptyList(),
|
||||
new VerificationSession(null, null, List.of(VerificationSession.Information.CAPTCHA), Collections.emptyList(),
|
||||
null, null, false, clock.millis(), clock.millis(), registrationServiceSession.expiration()))));
|
||||
|
||||
when(verificationSessionManager.update(any(), any()))
|
||||
@@ -432,7 +437,7 @@ class VerificationControllerTest {
|
||||
registrationServiceSession)));
|
||||
when(verificationSessionManager.findForId(any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(
|
||||
Optional.of(new VerificationSession(null, Collections.emptyList(), Collections.emptyList(), null, null, false,
|
||||
Optional.of(new VerificationSession(null, null, Collections.emptyList(), Collections.emptyList(), null, null, false,
|
||||
clock.millis(), clock.millis(), registrationServiceSession.expiration()))));
|
||||
|
||||
when(verificationSessionManager.update(any(), any()))
|
||||
@@ -468,7 +473,7 @@ class VerificationControllerTest {
|
||||
registrationServiceSession)));
|
||||
when(verificationSessionManager.findForId(any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(
|
||||
Optional.of(new VerificationSession(null, Collections.emptyList(), Collections.emptyList(), null, null, false,
|
||||
Optional.of(new VerificationSession(null, null, Collections.emptyList(), Collections.emptyList(), null, null, false,
|
||||
clock.millis(), clock.millis(), registrationServiceSession.expiration()))));
|
||||
|
||||
when(verificationSessionManager.update(any(), any()))
|
||||
@@ -504,7 +509,7 @@ class VerificationControllerTest {
|
||||
registrationServiceSession)));
|
||||
when(verificationSessionManager.findForId(any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(
|
||||
Optional.of(new VerificationSession("challenge", List.of(VerificationSession.Information.PUSH_CHALLENGE),
|
||||
Optional.of(new VerificationSession("challenge", null, List.of(VerificationSession.Information.PUSH_CHALLENGE),
|
||||
Collections.emptyList(), null, null, false, clock.millis(), clock.millis(),
|
||||
registrationServiceSession.expiration()))));
|
||||
when(verificationSessionManager.update(any(), any()))
|
||||
@@ -538,7 +543,7 @@ class VerificationControllerTest {
|
||||
registrationServiceSession)));
|
||||
when(verificationSessionManager.findForId(any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(
|
||||
Optional.of(new VerificationSession(null, List.of(VerificationSession.Information.CAPTCHA),
|
||||
Optional.of(new VerificationSession(null, null, List.of(VerificationSession.Information.CAPTCHA),
|
||||
Collections.emptyList(), null, null, false, clock.millis(), clock.millis(),
|
||||
registrationServiceSession.expiration()))));
|
||||
|
||||
@@ -586,6 +591,7 @@ class VerificationControllerTest {
|
||||
when(verificationSessionManager.findForId(any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(
|
||||
Optional.of(new VerificationSession("challenge",
|
||||
null,
|
||||
List.of(VerificationSession.Information.CAPTCHA),
|
||||
List.of(VerificationSession.Information.PUSH_CHALLENGE),
|
||||
null, null, false,
|
||||
@@ -630,7 +636,7 @@ class VerificationControllerTest {
|
||||
Optional.of(registrationServiceSession)));
|
||||
when(verificationSessionManager.findForId(any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(
|
||||
Optional.of(new VerificationSession("challenge", List.of(), List.of(), null, null, true,
|
||||
Optional.of(new VerificationSession("challenge", null, List.of(), List.of(), null, null, true,
|
||||
clock.millis(), clock.millis(), registrationServiceSession.expiration()))));
|
||||
|
||||
when(verificationSessionManager.update(any(), any()))
|
||||
@@ -667,6 +673,7 @@ class VerificationControllerTest {
|
||||
when(verificationSessionManager.findForId(any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(
|
||||
Optional.of(new VerificationSession("challenge",
|
||||
null,
|
||||
List.of(VerificationSession.Information.PUSH_CHALLENGE, VerificationSession.Information.CAPTCHA),
|
||||
Collections.emptyList(), null, null, false, clock.millis(), clock.millis(),
|
||||
registrationServiceSession.expiration()))));
|
||||
@@ -710,7 +717,7 @@ class VerificationControllerTest {
|
||||
registrationServiceSession)));
|
||||
when(verificationSessionManager.findForId(any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(
|
||||
Optional.of(new VerificationSession(null, List.of(VerificationSession.Information.CAPTCHA),
|
||||
Optional.of(new VerificationSession(null, null, List.of(VerificationSession.Information.CAPTCHA),
|
||||
Collections.emptyList(), null, null, false, clock.millis(), clock.millis(),
|
||||
registrationServiceSession.expiration()))));
|
||||
|
||||
@@ -758,6 +765,7 @@ class VerificationControllerTest {
|
||||
when(verificationSessionManager.findForId(any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(
|
||||
Optional.of(new VerificationSession("challenge",
|
||||
null,
|
||||
List.of(VerificationSession.Information.CAPTCHA, VerificationSession.Information.CAPTCHA),
|
||||
Collections.emptyList(), null, null, false, clock.millis(), clock.millis(),
|
||||
registrationServiceSession.expiration()))));
|
||||
@@ -805,6 +813,7 @@ class VerificationControllerTest {
|
||||
when(verificationSessionManager.findForId(any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(
|
||||
Optional.of(new VerificationSession(null,
|
||||
null,
|
||||
List.of(VerificationSession.Information.CAPTCHA),
|
||||
Collections.emptyList(), null, null, false, clock.millis(), clock.millis(),
|
||||
registrationServiceSession.expiration()))));
|
||||
@@ -961,7 +970,7 @@ class VerificationControllerTest {
|
||||
.thenReturn(CompletableFuture.completedFuture(Optional.of(registrationServiceSession)));
|
||||
when(verificationSessionManager.findForId(any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(
|
||||
Optional.of(new VerificationSession(null, Collections.emptyList(), Collections.emptyList(), null, null, true,
|
||||
Optional.of(new VerificationSession(null, null, Collections.emptyList(), Collections.emptyList(), null, null, true,
|
||||
clock.millis(), clock.millis(), registrationServiceSession.expiration()))));
|
||||
when(registrationServiceClient.sendVerificationCode(any(), any(), any(), any(), any(), any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(registrationServiceSession));
|
||||
@@ -991,8 +1000,8 @@ class VerificationControllerTest {
|
||||
Optional.of(
|
||||
registrationServiceSession)));
|
||||
when(verificationSessionManager.findForId(any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(Optional.of(new VerificationSession(null, List.of(
|
||||
VerificationSession.Information.CAPTCHA), Collections.emptyList(), null, null, false, clock.millis(), clock.millis(),
|
||||
.thenReturn(CompletableFuture.completedFuture(Optional.of(new VerificationSession(null, null,
|
||||
List.of(VerificationSession.Information.CAPTCHA), Collections.emptyList(), null, null, false, clock.millis(), clock.millis(),
|
||||
registrationServiceSession.expiration()))));
|
||||
|
||||
final Invocation.Builder request = resources.getJerseyTest()
|
||||
@@ -1023,7 +1032,7 @@ class VerificationControllerTest {
|
||||
registrationServiceSession)));
|
||||
when(verificationSessionManager.findForId(any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(
|
||||
Optional.of(new VerificationSession(null, Collections.emptyList(), Collections.emptyList(), null, null, false,
|
||||
Optional.of(new VerificationSession(null, null, Collections.emptyList(), Collections.emptyList(), null, null, false,
|
||||
clock.millis(), clock.millis(), registrationServiceSession.expiration()))));
|
||||
|
||||
final Invocation.Builder request = resources.getJerseyTest()
|
||||
@@ -1051,7 +1060,7 @@ class VerificationControllerTest {
|
||||
.thenReturn(CompletableFuture.completedFuture(Optional.of(registrationServiceSession)));
|
||||
when(verificationSessionManager.findForId(any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(
|
||||
Optional.of(new VerificationSession(null, Collections.emptyList(), Collections.emptyList(), null, null, true,
|
||||
Optional.of(new VerificationSession(null, null, Collections.emptyList(), Collections.emptyList(), null, null, true,
|
||||
clock.millis(), clock.millis(), registrationServiceSession.expiration()))));
|
||||
when(registrationServiceClient.sendVerificationCode(any(), any(), any(), any(), any(), any()))
|
||||
.thenReturn(CompletableFuture.failedFuture(
|
||||
@@ -1083,7 +1092,7 @@ class VerificationControllerTest {
|
||||
.thenReturn(CompletableFuture.completedFuture(Optional.of(registrationServiceSession)));
|
||||
when(verificationSessionManager.findForId(any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(
|
||||
Optional.of(new VerificationSession(null, Collections.emptyList(), Collections.emptyList(), null, null, true,
|
||||
Optional.of(new VerificationSession(null, null, Collections.emptyList(), Collections.emptyList(), null, null, true,
|
||||
clock.millis(), clock.millis(), registrationServiceSession.expiration()))));
|
||||
when(registrationServiceClient.sendVerificationCode(any(), any(), any(), any(), any(), any()))
|
||||
.thenReturn(CompletableFuture.failedFuture(
|
||||
@@ -1115,7 +1124,7 @@ class VerificationControllerTest {
|
||||
.thenReturn(CompletableFuture.completedFuture(Optional.of(registrationServiceSession)));
|
||||
when(verificationSessionManager.findForId(any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(
|
||||
Optional.of(new VerificationSession(null, Collections.emptyList(), Collections.emptyList(), null, null, true,
|
||||
Optional.of(new VerificationSession(null, null, Collections.emptyList(), Collections.emptyList(), null, null, true,
|
||||
clock.millis(), clock.millis(), registrationServiceSession.expiration()))));
|
||||
when(registrationServiceClient.sendVerificationCode(any(), any(), any(), any(), any(), any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(registrationServiceSession));
|
||||
@@ -1148,7 +1157,7 @@ class VerificationControllerTest {
|
||||
Optional.of(registrationServiceSession)));
|
||||
when(verificationSessionManager.findForId(any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(
|
||||
Optional.of(new VerificationSession(null, Collections.emptyList(), Collections.emptyList(), null, null, true,
|
||||
Optional.of(new VerificationSession(null, null, Collections.emptyList(), Collections.emptyList(), null, null, true,
|
||||
clock.millis(), clock.millis(), registrationServiceSession.expiration()))));
|
||||
|
||||
when(registrationServiceClient.sendVerificationCode(any(), any(), any(), any(), any(), any()))
|
||||
@@ -1192,7 +1201,7 @@ class VerificationControllerTest {
|
||||
.thenReturn(CompletableFuture.completedFuture(Optional.of(registrationServiceSession)));
|
||||
when(verificationSessionManager.findForId(any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(
|
||||
Optional.of(new VerificationSession(null, Collections.emptyList(), Collections.emptyList(), null, null, true,
|
||||
Optional.of(new VerificationSession(null, null, Collections.emptyList(), Collections.emptyList(), null, null, true,
|
||||
clock.millis(), clock.millis(), registrationServiceSession.expiration()))));
|
||||
|
||||
when(registrationServiceClient.sendVerificationCode(any(), any(), any(), any(), any(), any()))
|
||||
@@ -1226,7 +1235,7 @@ class VerificationControllerTest {
|
||||
Optional.of(registrationServiceSession)));
|
||||
when(verificationSessionManager.findForId(any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(
|
||||
Optional.of(new VerificationSession(null, Collections.emptyList(), Collections.emptyList(), null, null, true,
|
||||
Optional.of(new VerificationSession(null, null, Collections.emptyList(), Collections.emptyList(), null, null, true,
|
||||
clock.millis(), clock.millis(), registrationServiceSession.expiration()))));
|
||||
|
||||
when(registrationServiceClient.checkVerificationCode(any(), any(), any()))
|
||||
@@ -1253,7 +1262,7 @@ class VerificationControllerTest {
|
||||
Optional.of(registrationServiceSession)));
|
||||
when(verificationSessionManager.findForId(any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(
|
||||
Optional.of(new VerificationSession(null, Collections.emptyList(), Collections.emptyList(), null, null, true,
|
||||
Optional.of(new VerificationSession(null, null, Collections.emptyList(), Collections.emptyList(), null, null, true,
|
||||
clock.millis(), clock.millis(), registrationServiceSession.expiration()))));
|
||||
|
||||
final Invocation.Builder request = resources.getJerseyTest()
|
||||
@@ -1288,7 +1297,7 @@ class VerificationControllerTest {
|
||||
Optional.of(registrationServiceSession)));
|
||||
when(verificationSessionManager.findForId(any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(
|
||||
Optional.of(new VerificationSession(null, Collections.emptyList(), Collections.emptyList(), null, null, true,
|
||||
Optional.of(new VerificationSession(null, null, Collections.emptyList(), Collections.emptyList(), null, null, true,
|
||||
clock.millis(), clock.millis(), registrationServiceSession.expiration()))));
|
||||
|
||||
// There is no explicit indication in the exception that no code has been sent, but we treat all RegistrationServiceExceptions
|
||||
@@ -1325,7 +1334,7 @@ class VerificationControllerTest {
|
||||
Optional.of(registrationServiceSession)));
|
||||
when(verificationSessionManager.findForId(any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(
|
||||
Optional.of(new VerificationSession(null, Collections.emptyList(), Collections.emptyList(), null, null, true,
|
||||
Optional.of(new VerificationSession(null, null, Collections.emptyList(), Collections.emptyList(), null, null, true,
|
||||
clock.millis(), clock.millis(), registrationServiceSession.expiration()))));
|
||||
|
||||
when(registrationServiceClient.checkVerificationCode(any(), any(), any()))
|
||||
@@ -1351,7 +1360,7 @@ class VerificationControllerTest {
|
||||
Optional.of(registrationServiceSession)));
|
||||
when(verificationSessionManager.findForId(any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(
|
||||
Optional.of(new VerificationSession(null, Collections.emptyList(), Collections.emptyList(), null, null, true,
|
||||
Optional.of(new VerificationSession(null, null, Collections.emptyList(), Collections.emptyList(), null, null, true,
|
||||
clock.millis(), clock.millis(), registrationServiceSession.expiration()))));
|
||||
when(registrationServiceClient.checkVerificationCode(any(), any(), any()))
|
||||
.thenReturn(CompletableFuture.failedFuture(
|
||||
@@ -1383,7 +1392,7 @@ class VerificationControllerTest {
|
||||
Optional.of(registrationServiceSession)));
|
||||
when(verificationSessionManager.findForId(any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(
|
||||
Optional.of(new VerificationSession(null, Collections.emptyList(), Collections.emptyList(), null, null, true,
|
||||
Optional.of(new VerificationSession(null, null, Collections.emptyList(), Collections.emptyList(), null, null, true,
|
||||
clock.millis(), clock.millis(), registrationServiceSession.expiration()))));
|
||||
|
||||
final RegistrationServiceSession verifiedSession = new RegistrationServiceSession(SESSION_ID, NUMBER, true, null,
|
||||
|
||||
+12
-2
@@ -5,6 +5,7 @@
|
||||
|
||||
package org.whispersystems.textsecuregcm.filters;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
@@ -17,12 +18,14 @@ import static org.mockito.Mockito.when;
|
||||
import com.google.common.net.HttpHeaders;
|
||||
import com.google.common.net.InetAddresses;
|
||||
import com.google.protobuf.ByteString;
|
||||
import com.google.rpc.ErrorInfo;
|
||||
import com.vdurmont.semver4j.Semver;
|
||||
import io.grpc.ManagedChannel;
|
||||
import io.grpc.Server;
|
||||
import io.grpc.StatusRuntimeException;
|
||||
import io.grpc.inprocess.InProcessChannelBuilder;
|
||||
import io.grpc.inprocess.InProcessServerBuilder;
|
||||
import io.grpc.protobuf.StatusProto;
|
||||
import jakarta.servlet.FilterChain;
|
||||
import jakarta.servlet.ServletException;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
@@ -40,9 +43,9 @@ import org.signal.chat.rpc.EchoServiceGrpc;
|
||||
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicRemoteDeprecationConfiguration;
|
||||
import org.whispersystems.textsecuregcm.grpc.EchoServiceImpl;
|
||||
import org.whispersystems.textsecuregcm.grpc.GrpcExceptions;
|
||||
import org.whispersystems.textsecuregcm.grpc.MockRequestAttributesInterceptor;
|
||||
import org.whispersystems.textsecuregcm.grpc.RequestAttributes;
|
||||
import org.whispersystems.textsecuregcm.grpc.StatusConstants;
|
||||
import org.whispersystems.textsecuregcm.storage.DynamicConfigurationManager;
|
||||
import org.whispersystems.textsecuregcm.util.ua.ClientPlatform;
|
||||
|
||||
@@ -153,7 +156,14 @@ class RemoteDeprecationFilterTest {
|
||||
final StatusRuntimeException e = assertThrows(
|
||||
StatusRuntimeException.class,
|
||||
() -> client.echo(req));
|
||||
assertEquals(StatusConstants.UPGRADE_NEEDED_STATUS.toString(), e.getStatus().toString());
|
||||
final com.google.rpc.Status status = StatusProto.fromThrowable(e);
|
||||
final ErrorInfo errorInfo = assertDoesNotThrow(() -> status.getDetailsList().stream()
|
||||
.filter(any -> any.is(ErrorInfo.class)).findFirst()
|
||||
.orElseThrow(() -> new AssertionError("No error info found"))
|
||||
.unpack(ErrorInfo.class));
|
||||
assertEquals(GrpcExceptions.DOMAIN, errorInfo.getDomain());
|
||||
assertEquals(io.grpc.Status.Code.INVALID_ARGUMENT.value(), status.getCode());
|
||||
assertEquals("UPGRADE_REQUIRED", errorInfo.getReason());
|
||||
} else {
|
||||
assertEquals("cluck cluck, i'm a parrot", client.echo(req).getPayload().toStringUtf8());
|
||||
}
|
||||
|
||||
+13
-9
@@ -29,8 +29,11 @@ import org.mockito.Mock;
|
||||
import org.signal.chat.account.AccountsAnonymousGrpc;
|
||||
import org.signal.chat.account.CheckAccountExistenceRequest;
|
||||
import org.signal.chat.account.LookupUsernameHashRequest;
|
||||
import org.signal.chat.account.LookupUsernameHashResponse;
|
||||
import org.signal.chat.account.LookupUsernameLinkRequest;
|
||||
import org.signal.chat.account.LookupUsernameLinkResponse;
|
||||
import org.signal.chat.common.IdentityType;
|
||||
import org.signal.chat.errors.NotFound;
|
||||
import org.signal.chat.common.ServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.controllers.AccountController;
|
||||
import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
|
||||
@@ -151,8 +154,8 @@ class AccountsAnonymousGrpcServiceTest extends
|
||||
.getServiceIdentifier());
|
||||
|
||||
//noinspection ResultOfMethodCallIgnored
|
||||
GrpcTestUtils.assertStatusException(Status.NOT_FOUND,
|
||||
() -> unauthenticatedServiceStub().lookupUsernameHash(LookupUsernameHashRequest.newBuilder()
|
||||
assertEquals(LookupUsernameHashResponse.newBuilder().setNotFound(NotFound.getDefaultInstance()).build(),
|
||||
unauthenticatedServiceStub().lookupUsernameHash(LookupUsernameHashRequest.newBuilder()
|
||||
.setUsernameHash(ByteString.copyFrom(new byte[AccountController.USERNAME_HASH_LENGTH]))
|
||||
.build()));
|
||||
}
|
||||
@@ -217,15 +220,16 @@ class AccountsAnonymousGrpcServiceTest extends
|
||||
|
||||
when(account.getEncryptedUsername()).thenReturn(Optional.empty());
|
||||
|
||||
//noinspection ResultOfMethodCallIgnored
|
||||
GrpcTestUtils.assertStatusException(Status.NOT_FOUND,
|
||||
() -> unauthenticatedServiceStub().lookupUsernameLink(LookupUsernameLinkRequest.newBuilder()
|
||||
final LookupUsernameLinkResponse notFoundResponse = LookupUsernameLinkResponse.newBuilder()
|
||||
.setNotFound(NotFound.getDefaultInstance())
|
||||
.build();
|
||||
|
||||
assertEquals(notFoundResponse,
|
||||
unauthenticatedServiceStub().lookupUsernameLink(LookupUsernameLinkRequest.newBuilder()
|
||||
.setUsernameLinkHandle(UUIDUtil.toByteString(linkHandle))
|
||||
.build()));
|
||||
|
||||
//noinspection ResultOfMethodCallIgnored
|
||||
GrpcTestUtils.assertStatusException(Status.NOT_FOUND,
|
||||
() -> unauthenticatedServiceStub().lookupUsernameLink(LookupUsernameLinkRequest.newBuilder()
|
||||
assertEquals(notFoundResponse,
|
||||
unauthenticatedServiceStub().lookupUsernameLink(LookupUsernameLinkRequest.newBuilder()
|
||||
.setUsernameLinkHandle(UUIDUtil.toByteString(UUID.randomUUID()))
|
||||
.build()));
|
||||
}
|
||||
|
||||
+29
-20
@@ -47,8 +47,6 @@ import org.signal.chat.account.DeleteUsernameHashRequest;
|
||||
import org.signal.chat.account.DeleteUsernameLinkRequest;
|
||||
import org.signal.chat.account.GetAccountIdentityRequest;
|
||||
import org.signal.chat.account.GetAccountIdentityResponse;
|
||||
import org.signal.chat.account.ReserveUsernameHashError;
|
||||
import org.signal.chat.account.ReserveUsernameHashErrorType;
|
||||
import org.signal.chat.account.ReserveUsernameHashRequest;
|
||||
import org.signal.chat.account.ReserveUsernameHashResponse;
|
||||
import org.signal.chat.account.SetDiscoverableByPhoneNumberRequest;
|
||||
@@ -57,7 +55,9 @@ import org.signal.chat.account.SetRegistrationLockResponse;
|
||||
import org.signal.chat.account.SetRegistrationRecoveryPasswordRequest;
|
||||
import org.signal.chat.account.SetUsernameLinkRequest;
|
||||
import org.signal.chat.account.SetUsernameLinkResponse;
|
||||
import org.signal.chat.account.UsernameNotAvailable;
|
||||
import org.signal.chat.common.AccountIdentifiers;
|
||||
import org.signal.chat.errors.FailedPrecondition;
|
||||
import org.signal.libsignal.usernames.BaseUsernameException;
|
||||
import org.whispersystems.textsecuregcm.auth.SaltedTokenHash;
|
||||
import org.whispersystems.textsecuregcm.auth.UnidentifiedAccessUtil;
|
||||
@@ -173,7 +173,7 @@ class AccountsGrpcServiceTest extends SimpleBaseGrpcTest<AccountsGrpcService, Ac
|
||||
getMockAuthenticationInterceptor().setAuthenticatedDevice(AUTHENTICATED_ACI, (byte) (Device.PRIMARY_ID + 1));
|
||||
|
||||
//noinspection ResultOfMethodCallIgnored
|
||||
GrpcTestUtils.assertStatusException(Status.PERMISSION_DENIED,
|
||||
GrpcTestUtils.assertStatusException(Status.INVALID_ARGUMENT, "BAD_AUTHENTICATION",
|
||||
() -> authenticatedServiceStub().deleteAccount(DeleteAccountRequest.newBuilder().build()));
|
||||
|
||||
verify(accountsManager, never()).delete(any(), any());
|
||||
@@ -217,7 +217,7 @@ class AccountsGrpcServiceTest extends SimpleBaseGrpcTest<AccountsGrpcService, Ac
|
||||
getMockAuthenticationInterceptor().setAuthenticatedDevice(AUTHENTICATED_ACI, (byte) (Device.PRIMARY_ID + 1));
|
||||
|
||||
//noinspection ResultOfMethodCallIgnored
|
||||
GrpcTestUtils.assertStatusException(Status.PERMISSION_DENIED,
|
||||
GrpcTestUtils.assertStatusException(Status.INVALID_ARGUMENT, "BAD_AUTHENTICATION",
|
||||
() -> authenticatedServiceStub().setRegistrationLock(SetRegistrationLockRequest.newBuilder()
|
||||
.build()));
|
||||
|
||||
@@ -242,7 +242,7 @@ class AccountsGrpcServiceTest extends SimpleBaseGrpcTest<AccountsGrpcService, Ac
|
||||
getMockAuthenticationInterceptor().setAuthenticatedDevice(AUTHENTICATED_ACI, (byte) (Device.PRIMARY_ID + 1));
|
||||
|
||||
//noinspection ResultOfMethodCallIgnored
|
||||
GrpcTestUtils.assertStatusException(Status.PERMISSION_DENIED,
|
||||
GrpcTestUtils.assertStatusException(Status.INVALID_ARGUMENT,
|
||||
() -> authenticatedServiceStub().clearRegistrationLock(ClearRegistrationLockRequest.newBuilder().build()));
|
||||
|
||||
verify(accountsManager, never()).updateAsync(any(), any());
|
||||
@@ -288,9 +288,7 @@ class AccountsGrpcServiceTest extends SimpleBaseGrpcTest<AccountsGrpcService, Ac
|
||||
.thenReturn(CompletableFuture.failedFuture(new UsernameHashNotAvailableException()));
|
||||
|
||||
final ReserveUsernameHashResponse expectedResponse = ReserveUsernameHashResponse.newBuilder()
|
||||
.setError(ReserveUsernameHashError.newBuilder()
|
||||
.setErrorType(ReserveUsernameHashErrorType.RESERVE_USERNAME_HASH_ERROR_TYPE_NO_HASHES_AVAILABLE)
|
||||
.build())
|
||||
.setUsernameNotAvailable(UsernameNotAvailable.getDefaultInstance())
|
||||
.build();
|
||||
|
||||
assertEquals(expectedResponse,
|
||||
@@ -379,8 +377,10 @@ class AccountsGrpcServiceTest extends SimpleBaseGrpcTest<AccountsGrpcService, Ac
|
||||
});
|
||||
|
||||
final ConfirmUsernameHashResponse expectedResponse = ConfirmUsernameHashResponse.newBuilder()
|
||||
.setUsernameHash(ByteString.copyFrom(usernameHash))
|
||||
.setUsernameLinkHandle(UUIDUtil.toByteString(linkHandle))
|
||||
.setConfirmedUsernameHash(ConfirmUsernameHashResponse.ConfirmedUsernameHash.newBuilder()
|
||||
.setUsernameHash(ByteString.copyFrom(usernameHash))
|
||||
.setUsernameLinkHandle(UUIDUtil.toByteString(linkHandle))
|
||||
.build())
|
||||
.build();
|
||||
|
||||
assertEquals(expectedResponse,
|
||||
@@ -393,7 +393,7 @@ class AccountsGrpcServiceTest extends SimpleBaseGrpcTest<AccountsGrpcService, Ac
|
||||
|
||||
@ParameterizedTest
|
||||
@MethodSource
|
||||
void confirmUsernameHashConfirmationException(final Exception confirmationException, final Status expectedStatus) {
|
||||
void confirmUsernameHashConfirmationException(final Exception confirmationException, final ConfirmUsernameHashResponse expectedResponse) {
|
||||
final byte[] usernameHash = TestRandomUtil.nextBytes(AccountController.USERNAME_HASH_LENGTH);
|
||||
|
||||
final byte[] usernameCiphertext = TestRandomUtil.nextBytes(32);
|
||||
@@ -408,19 +408,26 @@ class AccountsGrpcServiceTest extends SimpleBaseGrpcTest<AccountsGrpcService, Ac
|
||||
when(accountsManager.confirmReservedUsernameHash(any(), any(), any()))
|
||||
.thenReturn(CompletableFuture.failedFuture(confirmationException));
|
||||
|
||||
//noinspection ResultOfMethodCallIgnored
|
||||
GrpcTestUtils.assertStatusException(expectedStatus,
|
||||
() -> authenticatedServiceStub().confirmUsernameHash(ConfirmUsernameHashRequest.newBuilder()
|
||||
final ConfirmUsernameHashResponse actualResponse = authenticatedServiceStub()
|
||||
.confirmUsernameHash(ConfirmUsernameHashRequest.newBuilder()
|
||||
.setUsernameHash(ByteString.copyFrom(usernameHash))
|
||||
.setUsernameCiphertext(ByteString.copyFrom(usernameCiphertext))
|
||||
.setZkProof(ByteString.copyFrom(zkProof))
|
||||
.build()));
|
||||
.build());
|
||||
|
||||
assertEquals(expectedResponse, actualResponse);
|
||||
}
|
||||
|
||||
private static Stream<Arguments> confirmUsernameHashConfirmationException() {
|
||||
return Stream.of(
|
||||
Arguments.of(new UsernameHashNotAvailableException(), Status.NOT_FOUND),
|
||||
Arguments.of(new UsernameReservationNotFoundException(), Status.FAILED_PRECONDITION)
|
||||
Arguments.of( new UsernameHashNotAvailableException(),
|
||||
ConfirmUsernameHashResponse.newBuilder()
|
||||
.setUsernameNotAvailable(UsernameNotAvailable.getDefaultInstance())
|
||||
.build()),
|
||||
Arguments.of(new UsernameReservationNotFoundException(),
|
||||
ConfirmUsernameHashResponse.newBuilder()
|
||||
.setReservationNotFound(FailedPrecondition.getDefaultInstance())
|
||||
.build())
|
||||
);
|
||||
}
|
||||
|
||||
@@ -546,9 +553,11 @@ class AccountsGrpcServiceTest extends SimpleBaseGrpcTest<AccountsGrpcService, Ac
|
||||
|
||||
final byte[] usernameCiphertext = TestRandomUtil.nextBytes(EncryptedUsername.MAX_SIZE);
|
||||
|
||||
//noinspection ResultOfMethodCallIgnored
|
||||
GrpcTestUtils.assertStatusException(Status.FAILED_PRECONDITION,
|
||||
() -> authenticatedServiceStub().setUsernameLink(SetUsernameLinkRequest.newBuilder()
|
||||
assertEquals(
|
||||
SetUsernameLinkResponse.newBuilder()
|
||||
.setNoUsernameSet(FailedPrecondition.getDefaultInstance())
|
||||
.build(),
|
||||
authenticatedServiceStub().setUsernameLink(SetUsernameLinkRequest.newBuilder()
|
||||
.setUsernameCiphertext(ByteString.copyFrom(usernameCiphertext))
|
||||
.build()));
|
||||
}
|
||||
|
||||
+48
-56
@@ -8,7 +8,6 @@ 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.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.when;
|
||||
@@ -17,20 +16,18 @@ import com.google.protobuf.ByteString;
|
||||
import io.grpc.Status;
|
||||
import io.grpc.StatusRuntimeException;
|
||||
import java.time.Clock;
|
||||
import java.time.Duration;
|
||||
import java.util.Arrays;
|
||||
import java.util.Base64;
|
||||
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 java.util.stream.Stream;
|
||||
import jakarta.ws.rs.client.WebTarget;
|
||||
import jakarta.ws.rs.core.Response;
|
||||
import org.junit.jupiter.api.Assertions;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
@@ -61,10 +58,11 @@ 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.BackupException;
|
||||
import org.whispersystems.textsecuregcm.backup.BackupFailedZkAuthenticationException;
|
||||
import org.whispersystems.textsecuregcm.backup.BackupManager;
|
||||
import org.whispersystems.textsecuregcm.backup.BackupUploadDescriptor;
|
||||
import org.whispersystems.textsecuregcm.backup.CopyResult;
|
||||
import org.whispersystems.textsecuregcm.controllers.ArchiveController;
|
||||
import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
|
||||
import org.whispersystems.textsecuregcm.metrics.BackupMetrics;
|
||||
import org.whispersystems.textsecuregcm.util.TestRandomUtil;
|
||||
@@ -89,14 +87,16 @@ class BackupsAnonymousGrpcServiceTest extends
|
||||
|
||||
@BeforeEach
|
||||
void setup() {
|
||||
when(backupManager.authenticateBackupUser(any(), any(), any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(
|
||||
backupUser(presentation.getBackupId(), BackupCredentialType.MESSAGES, BackupLevel.PAID)));
|
||||
try {
|
||||
when(backupManager.authenticateBackupUser(any(), any(), any()))
|
||||
.thenReturn(backupUser(presentation.getBackupId(), BackupCredentialType.MESSAGES, BackupLevel.PAID));
|
||||
} catch (BackupFailedZkAuthenticationException e) {
|
||||
Assertions.fail(e);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void setPublicKey() {
|
||||
when(backupManager.setPublicKey(any(), any(), any())).thenReturn(CompletableFuture.completedFuture(null));
|
||||
assertThatNoException().isThrownBy(() -> unauthenticatedServiceStub().setPublicKey(SetPublicKeyRequest.newBuilder()
|
||||
.setPublicKey(ByteString.copyFrom(ECKeyPair.generate().getPublicKey().serialize()))
|
||||
.setSignedPresentation(signedPresentation(presentation))
|
||||
@@ -105,7 +105,6 @@ class BackupsAnonymousGrpcServiceTest extends
|
||||
|
||||
@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
|
||||
@@ -130,7 +129,7 @@ class BackupsAnonymousGrpcServiceTest extends
|
||||
@Test
|
||||
void putMediaBatchSuccess() {
|
||||
final byte[][] mediaIds = {TestRandomUtil.nextBytes(15), TestRandomUtil.nextBytes(15)};
|
||||
when(backupManager.copyToBackup(any(), any()))
|
||||
when(backupManager.copyToBackup(any()))
|
||||
.thenReturn(Flux.just(
|
||||
new CopyResult(CopyResult.Outcome.SUCCESS, mediaIds[0], 1),
|
||||
new CopyResult(CopyResult.Outcome.SUCCESS, mediaIds[1], 1)));
|
||||
@@ -175,7 +174,7 @@ class BackupsAnonymousGrpcServiceTest extends
|
||||
CopyResult.Outcome.SOURCE_WRONG_LENGTH,
|
||||
CopyResult.Outcome.OUT_OF_QUOTA
|
||||
};
|
||||
when(backupManager.copyToBackup(any(), any()))
|
||||
when(backupManager.copyToBackup(any()))
|
||||
.thenReturn(Flux.fromStream(IntStream.range(0, 4)
|
||||
.mapToObj(i -> new CopyResult(
|
||||
outcomes[i],
|
||||
@@ -212,17 +211,17 @@ class BackupsAnonymousGrpcServiceTest extends
|
||||
}
|
||||
|
||||
@Test
|
||||
void getBackupInfo() {
|
||||
when(backupManager.backupInfo(any())).thenReturn(CompletableFuture.completedFuture(new BackupManager.BackupInfo(
|
||||
1, "myBackupDir", "myMediaDir", "filename", Optional.empty())));
|
||||
void getBackupInfo() throws BackupException {
|
||||
when(backupManager.backupInfo(any()))
|
||||
.thenReturn(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);
|
||||
assertThat(response.getBackupInfo().getBackupDir()).isEqualTo("myBackupDir");
|
||||
assertThat(response.getBackupInfo().getBackupName()).isEqualTo("filename");
|
||||
assertThat(response.getBackupInfo().getCdn()).isEqualTo(1);
|
||||
assertThat(response.getBackupInfo().getUsedSpace()).isEqualTo(0L);
|
||||
}
|
||||
|
||||
|
||||
@@ -230,7 +229,7 @@ class BackupsAnonymousGrpcServiceTest extends
|
||||
void list(
|
||||
@CartesianTest.Values(booleans = {true, false}) final boolean cursorProvided,
|
||||
@CartesianTest.Values(booleans = {true, false}) final boolean cursorReturned)
|
||||
throws VerificationFailedException {
|
||||
throws VerificationFailedException, BackupException {
|
||||
|
||||
final byte[] mediaId = TestRandomUtil.nextBytes(15);
|
||||
final Optional<String> expectedCursor = cursorProvided ? Optional.of("myCursor") : Optional.empty();
|
||||
@@ -239,9 +238,9 @@ class BackupsAnonymousGrpcServiceTest extends
|
||||
final int limit = 17;
|
||||
|
||||
when(backupManager.list(any(), eq(expectedCursor), eq(limit)))
|
||||
.thenReturn(CompletableFuture.completedFuture(new BackupManager.ListMediaResult(
|
||||
.thenReturn(new BackupManager.ListMediaResult(
|
||||
List.of(new BackupManager.StorageDescriptorWithLength(1, mediaId, 100)),
|
||||
returnedCursor)));
|
||||
returnedCursor));
|
||||
|
||||
final ListMediaRequest.Builder request = ListMediaRequest.newBuilder()
|
||||
.setSignedPresentation(signedPresentation(presentation))
|
||||
@@ -251,15 +250,16 @@ class BackupsAnonymousGrpcServiceTest extends
|
||||
}
|
||||
|
||||
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));
|
||||
assertThat(response.getListResult().getPageCount()).isEqualTo(1);
|
||||
assertThat(response.getListResult().getPage(0).getLength()).isEqualTo(100);
|
||||
assertThat(response.getListResult().getPage(0).getMediaId().toByteArray()).isEqualTo(mediaId);
|
||||
assertThat(response.getListResult().hasCursor() ? response.getListResult().getCursor() : null)
|
||||
.isEqualTo(returnedCursor.orElse(null));
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
void delete() {
|
||||
void delete() throws BackupException {
|
||||
final DeleteMediaRequest request = DeleteMediaRequest.newBuilder()
|
||||
.setSignedPresentation(signedPresentation(presentation))
|
||||
.addAllItems(IntStream.range(0, 100).mapToObj(i ->
|
||||
@@ -279,28 +279,25 @@ class BackupsAnonymousGrpcServiceTest extends
|
||||
}
|
||||
|
||||
@Test
|
||||
void mediaUploadForm() {
|
||||
void mediaUploadForm() throws RateLimitExceededException, BackupException {
|
||||
when(backupManager.createTemporaryAttachmentUploadDescriptor(any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(
|
||||
new BackupUploadDescriptor(3, "abc", Map.of("k", "v"), "example.org")));
|
||||
.thenReturn(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");
|
||||
assertThat(uploadForm.getUploadForm().getCdn()).isEqualTo(3);
|
||||
assertThat(uploadForm.getUploadForm().getKey()).isEqualTo("abc");
|
||||
assertThat(uploadForm.getUploadForm().getHeadersMap()).containsExactlyEntriesOf(Map.of("k", "v"));
|
||||
assertThat(uploadForm.getUploadForm().getSignedUploadLocation()).isEqualTo("example.org");
|
||||
|
||||
// rate limit
|
||||
Duration duration = Duration.ofSeconds(10);
|
||||
when(backupManager.createTemporaryAttachmentUploadDescriptor(any()))
|
||||
.thenReturn(CompletableFuture.failedFuture(new RateLimitExceededException(null)));
|
||||
assertThatExceptionOfType(StatusRuntimeException.class)
|
||||
.isThrownBy(() -> unauthenticatedServiceStub().getUploadForm(request))
|
||||
.extracting(StatusRuntimeException::getStatus)
|
||||
.isEqualTo(Status.RESOURCE_EXHAUSTED);
|
||||
.thenThrow(new RateLimitExceededException(duration));
|
||||
GrpcTestUtils.assertRateLimitExceeded(duration, () -> unauthenticatedServiceStub().getUploadForm(request));
|
||||
}
|
||||
|
||||
static Stream<Arguments> messagesUploadForm() {
|
||||
@@ -313,34 +310,29 @@ class BackupsAnonymousGrpcServiceTest extends
|
||||
|
||||
@ParameterizedTest
|
||||
@MethodSource
|
||||
public void messagesUploadForm(Optional<Long> uploadLength, boolean expectSuccess) {
|
||||
public void messagesUploadForm(Optional<Long> uploadLength, boolean allowedSize) throws BackupException {
|
||||
when(backupManager.createMessageBackupUploadDescriptor(any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(
|
||||
new BackupUploadDescriptor(3, "abc", Map.of("k", "v"), "example.org")));
|
||||
.thenReturn(new BackupUploadDescriptor(3, "abc", Map.of("k", "v"), "example.org"));
|
||||
final GetUploadFormRequest.MessagesUploadType.Builder builder = GetUploadFormRequest.MessagesUploadType.newBuilder();
|
||||
uploadLength.ifPresent(builder::setUploadLength);
|
||||
final GetUploadFormRequest request = GetUploadFormRequest.newBuilder()
|
||||
.setMessages(builder.build())
|
||||
.setSignedPresentation(signedPresentation(presentation))
|
||||
.build();
|
||||
if (expectSuccess) {
|
||||
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");
|
||||
final GetUploadFormResponse response = unauthenticatedServiceStub().getUploadForm(request);
|
||||
if (allowedSize) {
|
||||
assertThat(response.getUploadForm().getCdn()).isEqualTo(3);
|
||||
assertThat(response.getUploadForm().getKey()).isEqualTo("abc");
|
||||
assertThat(response.getUploadForm().getHeadersMap()).containsExactlyEntriesOf(Map.of("k", "v"));
|
||||
assertThat(response.getUploadForm().getSignedUploadLocation()).isEqualTo("example.org");
|
||||
} else {
|
||||
assertThatExceptionOfType(StatusRuntimeException.class)
|
||||
.isThrownBy(() -> unauthenticatedServiceStub().getUploadForm(request))
|
||||
.extracting(StatusRuntimeException::getStatus)
|
||||
.extracting(Status::getCode)
|
||||
.isEqualTo(Status.FAILED_PRECONDITION.getCode());
|
||||
assertThat(response.hasExceedsMaxUploadLength()).isTrue();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
void readAuth() {
|
||||
void readAuth() throws BackupException {
|
||||
when(backupManager.generateReadAuth(any(), eq(3))).thenReturn(Map.of("key", "value"));
|
||||
|
||||
final GetCdnCredentialsResponse response = unauthenticatedServiceStub().getCdnCredentials(
|
||||
@@ -348,7 +340,7 @@ class BackupsAnonymousGrpcServiceTest extends
|
||||
.setCdn(3)
|
||||
.setSignedPresentation(signedPresentation(presentation))
|
||||
.build());
|
||||
assertThat(response.getHeadersMap()).containsExactlyEntriesOf(Map.of("key", "value"));
|
||||
assertThat(response.getCdnCredentials().getHeadersMap()).containsExactlyEntriesOf(Map.of("key", "value"));
|
||||
}
|
||||
|
||||
private static AuthenticatedBackupUser backupUser(final byte[] backupId, final BackupCredentialType credentialType,
|
||||
|
||||
+49
-33
@@ -8,6 +8,7 @@ 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.doThrow;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
@@ -35,6 +36,7 @@ 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.RedeemReceiptResponse;
|
||||
import org.signal.chat.backup.SetBackupIdRequest;
|
||||
import org.signal.chat.common.ZkCredential;
|
||||
import org.signal.libsignal.zkgroup.InvalidInputException;
|
||||
@@ -53,6 +55,12 @@ import org.signal.libsignal.zkgroup.receipts.ServerZkReceiptOperations;
|
||||
import org.whispersystems.textsecuregcm.auth.RedemptionRange;
|
||||
import org.whispersystems.textsecuregcm.backup.BackupAuthManager;
|
||||
import org.whispersystems.textsecuregcm.backup.BackupAuthTestUtil;
|
||||
import org.whispersystems.textsecuregcm.backup.BackupBadReceiptException;
|
||||
import org.whispersystems.textsecuregcm.backup.BackupException;
|
||||
import org.whispersystems.textsecuregcm.backup.BackupInvalidArgumentException;
|
||||
import org.whispersystems.textsecuregcm.backup.BackupMissingIdCommitmentException;
|
||||
import org.whispersystems.textsecuregcm.backup.BackupNotFoundException;
|
||||
import org.whispersystems.textsecuregcm.backup.BackupPermissionException;
|
||||
import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
|
||||
import org.whispersystems.textsecuregcm.metrics.BackupMetrics;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
@@ -60,6 +68,7 @@ import org.whispersystems.textsecuregcm.storage.AccountsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.Device;
|
||||
import org.whispersystems.textsecuregcm.util.EnumMapUtil;
|
||||
import org.whispersystems.textsecuregcm.util.TestRandomUtil;
|
||||
import javax.annotation.Nullable;
|
||||
|
||||
class BackupsGrpcServiceTest extends SimpleBaseGrpcTest<BackupsGrpcService, BackupsGrpc.BackupsBlockingStub> {
|
||||
|
||||
@@ -90,15 +99,14 @@ class BackupsGrpcServiceTest extends SimpleBaseGrpcTest<BackupsGrpcService, Back
|
||||
when(device.isPrimary()).thenReturn(true);
|
||||
when(accountsManager.getByAccountIdentifierAsync(AUTHENTICATED_ACI))
|
||||
.thenReturn(CompletableFuture.completedFuture(Optional.of(account)));
|
||||
when(accountsManager.getByAccountIdentifier(AUTHENTICATED_ACI))
|
||||
.thenReturn(Optional.of(account));
|
||||
when(account.getDevice(AUTHENTICATED_DEVICE_ID)).thenReturn(Optional.of(device));
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
void setBackupId() {
|
||||
when(backupAuthManager.commitBackupId(any(), any(), any(), any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(null));
|
||||
|
||||
void setBackupId() throws RateLimitExceededException, BackupInvalidArgumentException, BackupPermissionException {
|
||||
authenticatedServiceStub().setBackupId(
|
||||
SetBackupIdRequest.newBuilder()
|
||||
.setMediaBackupAuthCredentialRequest(ByteString.copyFrom(mediaAuthCredRequest.serialize()))
|
||||
@@ -111,10 +119,8 @@ class BackupsGrpcServiceTest extends SimpleBaseGrpcTest<BackupsGrpcService, Back
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(booleans = {false, true})
|
||||
void setBackupIdPartial(boolean media) {
|
||||
when(backupAuthManager.commitBackupId(any(), any(), any(), any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(null));
|
||||
|
||||
void setBackupIdPartial(boolean media)
|
||||
throws RateLimitExceededException, BackupInvalidArgumentException, BackupPermissionException {
|
||||
final SetBackupIdRequest.Builder builder = SetBackupIdRequest.newBuilder();
|
||||
if (media) {
|
||||
builder.setMediaBackupAuthCredentialRequest(ByteString.copyFrom(mediaAuthCredRequest.serialize()));
|
||||
@@ -143,23 +149,16 @@ class BackupsGrpcServiceTest extends SimpleBaseGrpcTest<BackupsGrpcService, Back
|
||||
|
||||
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)
|
||||
);
|
||||
Arguments.of(new RateLimitExceededException(null), Status.RESOURCE_EXHAUSTED),
|
||||
Arguments.of(new BackupPermissionException("test"), Status.INVALID_ARGUMENT),
|
||||
Arguments.of(new BackupInvalidArgumentException("test"), Status.INVALID_ARGUMENT));
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@MethodSource
|
||||
void setBackupIdException(final Exception ex, final boolean sync, final Status expected) {
|
||||
if (sync) {
|
||||
when(backupAuthManager.commitBackupId(any(), any(), any(), any())).thenThrow(ex);
|
||||
} else {
|
||||
when(backupAuthManager.commitBackupId(any(), any(), any(), any()))
|
||||
.thenReturn(CompletableFuture.failedFuture(ex));
|
||||
}
|
||||
void setBackupIdException(final Exception ex, final Status expected)
|
||||
throws RateLimitExceededException, BackupInvalidArgumentException, BackupPermissionException {
|
||||
doThrow(ex).when(backupAuthManager).commitBackupId(any(), any(), any(), any());
|
||||
|
||||
GrpcTestUtils.assertStatusException(
|
||||
expected, () -> authenticatedServiceStub().setBackupId(SetBackupIdRequest.newBuilder()
|
||||
@@ -169,8 +168,18 @@ class BackupsGrpcServiceTest extends SimpleBaseGrpcTest<BackupsGrpcService, Back
|
||||
);
|
||||
}
|
||||
|
||||
@Test
|
||||
void redeemReceipt() throws InvalidInputException, VerificationFailedException {
|
||||
public static Stream<Arguments> redeemReceipt() {
|
||||
return Stream.of(
|
||||
Arguments.of(null, RedeemReceiptResponse.OutcomeCase.SUCCESS),
|
||||
Arguments.of(new BackupBadReceiptException("test"), RedeemReceiptResponse.OutcomeCase.INVALID_RECEIPT),
|
||||
Arguments.of(new BackupMissingIdCommitmentException(), RedeemReceiptResponse.OutcomeCase.ACCOUNT_MISSING_COMMITMENT));
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@MethodSource
|
||||
void redeemReceipt(@Nullable final BackupException exception, final RedeemReceiptResponse.OutcomeCase expectedOutcome)
|
||||
throws InvalidInputException, VerificationFailedException, BackupInvalidArgumentException, BackupMissingIdCommitmentException, BackupBadReceiptException {
|
||||
|
||||
final ServerSecretParams params = ServerSecretParams.generate();
|
||||
final ServerZkReceiptOperations serverOps = new ServerZkReceiptOperations(params);
|
||||
final ClientZkReceiptOperations clientOps = new ClientZkReceiptOperations(params.getPublicParams());
|
||||
@@ -180,18 +189,22 @@ class BackupsGrpcServiceTest extends SimpleBaseGrpcTest<BackupsGrpcService, Back
|
||||
final ReceiptCredential receiptCredential = clientOps.receiveReceiptCredential(rcrc, rcr);
|
||||
final ReceiptCredentialPresentation presentation = clientOps.createReceiptCredentialPresentation(receiptCredential);
|
||||
|
||||
when(backupAuthManager.redeemReceipt(any(), any())).thenReturn(CompletableFuture.completedFuture(null));
|
||||
if (exception != null) {
|
||||
doThrow(exception).when(backupAuthManager).redeemReceipt(any(), any());
|
||||
}
|
||||
|
||||
authenticatedServiceStub().redeemReceipt(RedeemReceiptRequest.newBuilder()
|
||||
.setPresentation(ByteString.copyFrom(presentation.serialize()))
|
||||
.build());
|
||||
final RedeemReceiptResponse redeemReceiptResponse = authenticatedServiceStub().redeemReceipt(
|
||||
RedeemReceiptRequest.newBuilder()
|
||||
.setPresentation(ByteString.copyFrom(presentation.serialize()))
|
||||
.build());
|
||||
assertThat(redeemReceiptResponse.getOutcomeCase()).isEqualTo(expectedOutcome);
|
||||
|
||||
verify(backupAuthManager).redeemReceipt(account, presentation);
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
void getCredentials() {
|
||||
void getCredentials() throws BackupNotFoundException {
|
||||
final Instant start = Instant.now().truncatedTo(ChronoUnit.DAYS);
|
||||
final Instant end = start.plus(Duration.ofDays(1));
|
||||
final RedemptionRange expectedRange = RedemptionRange.inclusive(Clock.systemUTC(), start, end);
|
||||
@@ -201,9 +214,12 @@ class BackupsGrpcServiceTest extends SimpleBaseGrpcTest<BackupsGrpcService, Back
|
||||
BackupLevel.PAID, backupAuthTestUtil.getRequest(messagesBackupKey, AUTHENTICATED_ACI), credentialType,
|
||||
start, end));
|
||||
|
||||
expectedCredentialsByType.forEach((credentialType, expectedCredentials) ->
|
||||
when(backupAuthManager.getBackupAuthCredentials(any(), eq(credentialType), eq(expectedRange)))
|
||||
.thenReturn(CompletableFuture.completedFuture(expectedCredentials)));
|
||||
for (Map.Entry<BackupCredentialType, List<BackupAuthManager.Credential>> entry : expectedCredentialsByType.entrySet()) {
|
||||
final BackupCredentialType credentialType = entry.getKey();
|
||||
final List<BackupAuthManager.Credential> expectedCredentials = entry.getValue();
|
||||
when(backupAuthManager.getBackupAuthCredentials(any(), eq(credentialType), eq(expectedRange)))
|
||||
.thenReturn(expectedCredentials);
|
||||
}
|
||||
|
||||
final GetBackupAuthCredentialsResponse credentialResponse = authenticatedServiceStub().getBackupAuthCredentials(
|
||||
GetBackupAuthCredentialsRequest.newBuilder()
|
||||
@@ -213,8 +229,8 @@ class BackupsGrpcServiceTest extends SimpleBaseGrpcTest<BackupsGrpcService, Back
|
||||
expectedCredentialsByType.forEach((credentialType, expectedCredentials) -> {
|
||||
|
||||
final Map<Long, ZkCredential> creds = switch (credentialType) {
|
||||
case MESSAGES -> credentialResponse.getMessageCredentialsMap();
|
||||
case MEDIA -> credentialResponse.getMediaCredentialsMap();
|
||||
case MESSAGES -> credentialResponse.getCredentials().getMessageCredentialsMap();
|
||||
case MEDIA -> credentialResponse.getCredentials().getMediaCredentialsMap();
|
||||
};
|
||||
assertThat(creds).hasSize(expectedCredentials.size()).containsKey(start.getEpochSecond());
|
||||
|
||||
|
||||
+172
@@ -0,0 +1,172 @@
|
||||
/*
|
||||
* Copyright 2025 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
package org.whispersystems.textsecuregcm.grpc;
|
||||
|
||||
import com.google.protobuf.Any;
|
||||
import com.google.rpc.ErrorInfo;
|
||||
import io.grpc.ManagedChannel;
|
||||
import io.grpc.Server;
|
||||
import io.grpc.Status;
|
||||
import io.grpc.StatusRuntimeException;
|
||||
import io.grpc.inprocess.InProcessChannelBuilder;
|
||||
import io.grpc.inprocess.InProcessServerBuilder;
|
||||
import io.grpc.protobuf.StatusProto;
|
||||
import java.io.IOException;
|
||||
import java.io.UncheckedIOException;
|
||||
import java.util.concurrent.CompletionException;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.signal.chat.rpc.EchoRequest;
|
||||
import org.signal.chat.rpc.EchoResponse;
|
||||
import org.signal.chat.rpc.EchoServiceGrpc;
|
||||
import org.signal.chat.rpc.ReactorEchoServiceGrpc;
|
||||
import org.signal.chat.rpc.SimpleEchoServiceGrpc;
|
||||
import reactor.core.publisher.Mono;
|
||||
|
||||
class ErrorMappingInterceptorTest {
|
||||
|
||||
private Server server;
|
||||
private ManagedChannel channel;
|
||||
|
||||
|
||||
@BeforeEach
|
||||
void setUp() throws Exception {
|
||||
channel = InProcessChannelBuilder.forName("ErrorMappingInterceptorTest")
|
||||
.directExecutor()
|
||||
.build();
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void tearDown() throws Exception {
|
||||
server.shutdownNow();
|
||||
channel.shutdownNow();
|
||||
server.awaitTermination(1, TimeUnit.SECONDS);
|
||||
channel.awaitTermination(1, TimeUnit.SECONDS);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void includeDetailsSimpleGrpc() throws Exception {
|
||||
final StatusRuntimeException e = StatusProto.toStatusRuntimeException(com.google.rpc.Status.newBuilder()
|
||||
.setCode(Status.Code.INVALID_ARGUMENT.value())
|
||||
.addDetails(Any.pack(ErrorInfo.newBuilder()
|
||||
.setDomain("test")
|
||||
.setReason("TEST")
|
||||
.build()))
|
||||
.build());
|
||||
|
||||
server = InProcessServerBuilder.forName("ErrorMappingInterceptorTest")
|
||||
.directExecutor()
|
||||
.addService(new SimpleEchoServiceErrorImpl(e))
|
||||
.intercept(new ErrorMappingInterceptor())
|
||||
.build()
|
||||
.start();
|
||||
|
||||
final EchoServiceGrpc.EchoServiceBlockingStub client = EchoServiceGrpc.newBlockingStub(channel);
|
||||
GrpcTestUtils.assertStatusException(Status.INVALID_ARGUMENT, "TEST", () ->
|
||||
client.echo(EchoRequest.getDefaultInstance()));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void includeDetailsReactiveGrpc() throws Exception {
|
||||
final StatusRuntimeException e = StatusProto.toStatusRuntimeException(com.google.rpc.Status.newBuilder()
|
||||
.setCode(Status.Code.INVALID_ARGUMENT.value())
|
||||
.addDetails(Any.pack(ErrorInfo.newBuilder()
|
||||
.setDomain("test")
|
||||
.setReason("TEST")
|
||||
.build()))
|
||||
.build());
|
||||
|
||||
server = InProcessServerBuilder.forName("ErrorMappingInterceptorTest")
|
||||
.directExecutor()
|
||||
.addService(new ReactorEchoServiceErrorImpl(e))
|
||||
.intercept(new ErrorMappingInterceptor())
|
||||
.build()
|
||||
.start();
|
||||
|
||||
final EchoServiceGrpc.EchoServiceBlockingStub client = EchoServiceGrpc.newBlockingStub(channel);
|
||||
GrpcTestUtils.assertStatusException(Status.INVALID_ARGUMENT, "TEST", () ->
|
||||
client.echo(EchoRequest.getDefaultInstance()));
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void mapIOExceptionsReactive() throws Exception {
|
||||
server = InProcessServerBuilder.forName("ErrorMappingInterceptorTest")
|
||||
.directExecutor()
|
||||
.addService(new ReactorEchoServiceErrorImpl(new IOException("test")))
|
||||
.intercept(new ErrorMappingInterceptor())
|
||||
.build()
|
||||
.start();
|
||||
|
||||
final EchoServiceGrpc.EchoServiceBlockingStub client = EchoServiceGrpc.newBlockingStub(channel);
|
||||
GrpcTestUtils.assertStatusException(Status.UNAVAILABLE, "UNAVAILABLE", () ->
|
||||
client.echo(EchoRequest.getDefaultInstance()));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void mapIOExceptionsSimple() throws Exception {
|
||||
server = InProcessServerBuilder.forName("ErrorMappingInterceptorTest")
|
||||
.directExecutor()
|
||||
.addService(new SimpleEchoServiceErrorImpl(new UncheckedIOException(new IOException("test"))))
|
||||
.intercept(new ErrorMappingInterceptor())
|
||||
.build()
|
||||
.start();
|
||||
|
||||
final EchoServiceGrpc.EchoServiceBlockingStub client = EchoServiceGrpc.newBlockingStub(channel);
|
||||
GrpcTestUtils.assertStatusException(Status.UNAVAILABLE, "UNAVAILABLE", () ->
|
||||
client.echo(EchoRequest.getDefaultInstance()));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void mapWrappedIOExceptionsSimple() throws Exception {
|
||||
server = InProcessServerBuilder.forName("ErrorMappingInterceptorTest")
|
||||
.directExecutor()
|
||||
.addService(new SimpleEchoServiceErrorImpl(new CompletionException(new UncheckedIOException(new IOException("test")))))
|
||||
.intercept(new ErrorMappingInterceptor())
|
||||
.build()
|
||||
.start();
|
||||
|
||||
final EchoServiceGrpc.EchoServiceBlockingStub client = EchoServiceGrpc.newBlockingStub(channel);
|
||||
GrpcTestUtils.assertStatusException(Status.UNAVAILABLE, "UNAVAILABLE", () ->
|
||||
client.echo(EchoRequest.getDefaultInstance()));
|
||||
}
|
||||
|
||||
|
||||
static class ReactorEchoServiceErrorImpl extends ReactorEchoServiceGrpc.EchoServiceImplBase {
|
||||
|
||||
private final Exception exception;
|
||||
|
||||
ReactorEchoServiceErrorImpl(final Exception exception) {
|
||||
this.exception = exception;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Mono<EchoResponse> echo(final EchoRequest echoRequest) {
|
||||
return Mono.error(exception);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Throwable onErrorMap(Throwable throwable) {
|
||||
return new IllegalArgumentException(throwable);
|
||||
}
|
||||
}
|
||||
|
||||
static class SimpleEchoServiceErrorImpl extends SimpleEchoServiceGrpc.EchoServiceImplBase {
|
||||
|
||||
private final RuntimeException exception;
|
||||
|
||||
SimpleEchoServiceErrorImpl(final RuntimeException exception) {
|
||||
this.exception = exception;
|
||||
}
|
||||
|
||||
@Override
|
||||
public EchoResponse echo(final EchoRequest echoRequest) {
|
||||
throw exception;
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
-8
@@ -122,14 +122,6 @@ public class ExternalServiceCredentialsGrpcServiceTest
|
||||
);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testUnauthenticatedCall() throws Exception {
|
||||
assertStatusUnauthenticated(() -> unauthenticatedServiceStub().getExternalServiceCredentials(
|
||||
GetExternalServiceCredentialsRequest.newBuilder()
|
||||
.setExternalService(ExternalServiceType.EXTERNAL_SERVICE_TYPE_DIRECTORY)
|
||||
.build()));
|
||||
}
|
||||
|
||||
/**
|
||||
* `ExternalServiceDefinitions` enum is supposed to have entries for all values in `ExternalServiceType`,
|
||||
* except for the `EXTERNAL_SERVICE_TYPE_UNSPECIFIED` and `UNRECOGNIZED`.
|
||||
|
||||
@@ -5,16 +5,24 @@
|
||||
|
||||
package org.whispersystems.textsecuregcm.grpc;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
import static org.mockito.Mockito.verifyNoInteractions;
|
||||
|
||||
import com.google.protobuf.Any;
|
||||
import com.google.protobuf.Message;
|
||||
import com.google.rpc.ErrorInfo;
|
||||
import com.google.rpc.RetryInfo;
|
||||
import io.grpc.BindableService;
|
||||
import io.grpc.ServerInterceptors;
|
||||
import io.grpc.Status;
|
||||
import io.grpc.StatusException;
|
||||
import io.grpc.StatusRuntimeException;
|
||||
import java.time.Duration;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
import io.grpc.protobuf.StatusProto;
|
||||
import org.junit.jupiter.api.Assertions;
|
||||
import org.junit.jupiter.api.function.Executable;
|
||||
import org.whispersystems.textsecuregcm.auth.grpc.MockAuthenticationInterceptor;
|
||||
@@ -51,6 +59,12 @@ public final class GrpcTestUtils {
|
||||
assertEquals(expected.getCode(), exception.getStatus().getCode());
|
||||
}
|
||||
|
||||
public static void assertStatusException(final Status expected, final String expectedReason, final Executable serviceCall) {
|
||||
final StatusRuntimeException exception = Assertions.assertThrows(StatusRuntimeException.class, serviceCall);
|
||||
assertEquals(expected.getCode(), exception.getStatus().getCode());
|
||||
assertEquals(expectedReason, extractErrorInfo(exception).getReason());
|
||||
}
|
||||
|
||||
public static void assertStatusInvalidArgument(final Executable serviceCall) {
|
||||
assertStatusException(Status.INVALID_ARGUMENT, serviceCall);
|
||||
}
|
||||
@@ -68,11 +82,31 @@ public final class GrpcTestUtils {
|
||||
final Executable serviceCall,
|
||||
final Object... mocksToCheckForNoInteraction) {
|
||||
final StatusRuntimeException exception = Assertions.assertThrows(StatusRuntimeException.class, serviceCall);
|
||||
assertEquals(Status.RESOURCE_EXHAUSTED, exception.getStatus());
|
||||
assertEquals(Status.RESOURCE_EXHAUSTED.getCode(), exception.getStatus().getCode());
|
||||
assertNotNull(exception.getTrailers());
|
||||
assertEquals(expectedRetryAfter, exception.getTrailers().get(RateLimitExceededException.RETRY_AFTER_DURATION_KEY));
|
||||
|
||||
final ErrorInfo errorInfo = extractErrorInfo(exception);
|
||||
final RetryInfo retryInfo = extractDetail(RetryInfo.class, exception);
|
||||
final Duration actual = Duration.ofSeconds(retryInfo.getRetryDelay().getSeconds(), retryInfo.getRetryDelay().getNanos());
|
||||
assertEquals(errorInfo.getDomain(), GrpcExceptions.DOMAIN);
|
||||
assertEquals(errorInfo.getReason(), "RESOURCE_EXHAUSTED");
|
||||
assertEquals(expectedRetryAfter, actual);
|
||||
|
||||
for (final Object mock: mocksToCheckForNoInteraction) {
|
||||
verifyNoInteractions(mock);
|
||||
}
|
||||
}
|
||||
|
||||
public static ErrorInfo extractErrorInfo(final StatusRuntimeException exception) {
|
||||
return extractDetail(ErrorInfo.class, exception);
|
||||
}
|
||||
|
||||
public static <T extends Message> T extractDetail(final Class<T> detailCls, final StatusRuntimeException exception) {
|
||||
final com.google.rpc.Status status = StatusProto.fromThrowable(exception);
|
||||
|
||||
return assertDoesNotThrow(() -> status.getDetailsList().stream()
|
||||
.filter(any -> any.is(detailCls)).findFirst()
|
||||
.orElseThrow(() -> new AssertionError("No error info found"))
|
||||
.unpack(detailCls));
|
||||
}
|
||||
}
|
||||
+144
-4
@@ -10,12 +10,17 @@ import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
import com.google.common.net.InetAddresses;
|
||||
import com.google.protobuf.Any;
|
||||
import com.google.protobuf.ByteString;
|
||||
import com.google.protobuf.Empty;
|
||||
import com.google.rpc.ErrorInfo;
|
||||
import io.grpc.ManagedChannel;
|
||||
import io.grpc.Server;
|
||||
import io.grpc.Status;
|
||||
import io.grpc.StatusException;
|
||||
import io.grpc.inprocess.InProcessChannelBuilder;
|
||||
import io.grpc.inprocess.InProcessServerBuilder;
|
||||
import io.grpc.protobuf.StatusProto;
|
||||
import io.grpc.stub.BlockingClientCall;
|
||||
import io.micrometer.core.instrument.Counter;
|
||||
import io.micrometer.core.instrument.Meter;
|
||||
@@ -24,34 +29,48 @@ import io.micrometer.core.instrument.Tags;
|
||||
import io.micrometer.core.instrument.Timer;
|
||||
import io.micrometer.core.instrument.simple.SimpleMeterRegistry;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.Flow;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.TimeoutException;
|
||||
import java.util.function.Supplier;
|
||||
import java.util.stream.Stream;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
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.MethodSource;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
import org.junitpioneer.jupiter.cartesian.CartesianTest;
|
||||
import org.signal.chat.rpc.EchoRequest;
|
||||
import org.signal.chat.rpc.EchoResponse;
|
||||
import org.signal.chat.rpc.EchoServiceGrpc;
|
||||
import org.signal.chat.rpc.SimpleTagTestServiceGrpc;
|
||||
import org.signal.chat.rpc.TagResponse;
|
||||
import org.signal.chat.rpc.TagTestServiceGrpc;
|
||||
import org.whispersystems.textsecuregcm.storage.ClientReleaseManager;
|
||||
import org.whispersystems.textsecuregcm.util.ua.UnrecognizedUserAgentException;
|
||||
import org.whispersystems.textsecuregcm.util.ua.UserAgent;
|
||||
import org.whispersystems.textsecuregcm.util.ua.UserAgentUtil;
|
||||
import reactor.adapter.JdkFlowAdapter;
|
||||
import reactor.core.publisher.Flux;
|
||||
import reactor.core.scheduler.Schedulers;
|
||||
|
||||
public class MetricServerInterceptorTest {
|
||||
|
||||
private static String USER_AGENT = "Signal-Android/4.53.7 (Android 8.1; libsignal)";
|
||||
private static final String USER_AGENT = "Signal-Android/4.53.7 (Android 8.1; libsignal)";
|
||||
|
||||
private Server server;
|
||||
private ManagedChannel channel;
|
||||
private SimpleMeterRegistry simpleMeterRegistry;
|
||||
private ClientReleaseManager clientReleaseManager;
|
||||
|
||||
private Supplier<TagResponse> tagResponseSupplier;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() throws Exception {
|
||||
simpleMeterRegistry = new SimpleMeterRegistry();
|
||||
clientReleaseManager = mock(ClientReleaseManager.class);
|
||||
tagResponseSupplier = mock(Supplier.class);
|
||||
final MockRequestAttributesInterceptor mockRequestAttributesInterceptor = new MockRequestAttributesInterceptor();
|
||||
mockRequestAttributesInterceptor.setRequestAttributes(
|
||||
new RequestAttributes(InetAddresses.forString("127.0.0.1"), USER_AGENT, null));
|
||||
@@ -59,9 +78,9 @@ public class MetricServerInterceptorTest {
|
||||
server = InProcessServerBuilder.forName("MetricServerInterceptorTest")
|
||||
.directExecutor()
|
||||
.addService(new EchoServiceImpl())
|
||||
.addService(new TagTestServiceImpl(tagResponseSupplier))
|
||||
.intercept(new MetricServerInterceptor(simpleMeterRegistry, clientReleaseManager))
|
||||
.intercept(mockRequestAttributesInterceptor)
|
||||
.intercept(mockRequestAttributesInterceptor)
|
||||
.build()
|
||||
.start();
|
||||
|
||||
@@ -111,7 +130,7 @@ public class MetricServerInterceptorTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
void streaming() throws StatusException, InterruptedException, TimeoutException {
|
||||
void streaming() throws StatusException, InterruptedException {
|
||||
final EchoServiceGrpc.EchoServiceBlockingV2Stub client = EchoServiceGrpc.newBlockingV2Stub(channel);
|
||||
final BlockingClientCall<EchoRequest, EchoResponse> echoStream = client.echoStream();
|
||||
echoStream.write(EchoRequest.newBuilder().setPayload(ByteString.copyFromUtf8("1")).build());
|
||||
@@ -152,6 +171,99 @@ public class MetricServerInterceptorTest {
|
||||
assertThat(expectedClientVersion).isEqualTo(actualClientVersion);
|
||||
}
|
||||
|
||||
static Stream<Arguments> testUnaryOkResponseReason() {
|
||||
return Stream.of(
|
||||
Arguments.argumentSet("Default reason", TagResponse.newBuilder().build(), "success"),
|
||||
Arguments.argumentSet("No reason", TagResponse.newBuilder().setNoReason(true).build(), "success"),
|
||||
Arguments.argumentSet("Explicitly set reason", TagResponse.newBuilder().setReason1(true).build(), "reason_1"),
|
||||
Arguments.argumentSet("Nested reason", TagResponse.newBuilder().setNestedReason(TagResponse.NestedReason.newBuilder().setReason(true)).build(), "nested_reason"));
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@MethodSource
|
||||
void testUnaryOkResponseReason(TagResponse response, String expectedReason) throws InterruptedException {
|
||||
final TagTestServiceGrpc.TagTestServiceBlockingStub tagTestServiceBlockingStub =
|
||||
TagTestServiceGrpc.newBlockingStub(channel);
|
||||
when(tagResponseSupplier.get()).thenReturn(response);
|
||||
tagTestServiceBlockingStub.tagEndpoint(Empty.getDefaultInstance());
|
||||
|
||||
final Counter rpcCount = find(Counter.class, MetricServerInterceptor.RPC_COUNTER_NAME);
|
||||
assertThat(rpcCount.count()).isCloseTo(1.0, offset(0.01));
|
||||
assertThat(rpcCount.getId().getTag("statusCode")).isEqualTo("OK");
|
||||
assertThat(rpcCount.getId().getTag("reason")).isEqualTo(expectedReason);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testConflictingReasons() {
|
||||
final TagTestServiceGrpc.TagTestServiceBlockingStub tagTestServiceBlockingStub =
|
||||
TagTestServiceGrpc.newBlockingStub(channel);
|
||||
when(tagResponseSupplier.get())
|
||||
.thenReturn(TagResponse.newBuilder().setReason1(true).setConflictingReason(true).build());
|
||||
tagTestServiceBlockingStub.tagEndpoint(Empty.getDefaultInstance());
|
||||
|
||||
// We make no promises if proto fields that have reason tags are present on a message, but this tests for the sane
|
||||
// behavior that at least one of these tags makes it into the metric.
|
||||
assertThat(find(Counter.class, MetricServerInterceptor.RPC_COUNTER_NAME).getId().getTag("reason"))
|
||||
.isIn("duplicate_reason", "reason_1");
|
||||
}
|
||||
|
||||
@CartesianTest
|
||||
public void testStatusErrorResponseReason(
|
||||
@CartesianTest.Enum(mode = CartesianTest.Enum.Mode.EXCLUDE, names = {"OK"}) Status.Code statusCode,
|
||||
@CartesianTest.Values(strings = {"test", "", "null"}) String reasonParam) {
|
||||
|
||||
final String reason, expectedReasonTag;
|
||||
if (reasonParam.equals("null")) {
|
||||
reason = null;
|
||||
expectedReasonTag = MetricServerInterceptor.DEFAULT_ERROR_REASON;
|
||||
} else {
|
||||
reason = reasonParam;
|
||||
expectedReasonTag = reasonParam;
|
||||
}
|
||||
|
||||
final TagTestServiceGrpc.TagTestServiceBlockingStub tagTestServiceBlockingStub =
|
||||
TagTestServiceGrpc.newBlockingStub(channel);
|
||||
|
||||
final com.google.rpc.Status.Builder builder = com.google.rpc.Status.newBuilder()
|
||||
.setCode(statusCode.value())
|
||||
.setMessage("test");
|
||||
if (reason != null) {
|
||||
builder.addDetails(Any.pack(ErrorInfo.newBuilder()
|
||||
.setDomain("domain")
|
||||
.setReason(reason)
|
||||
.build()));
|
||||
}
|
||||
|
||||
when(tagResponseSupplier.get()).thenThrow(StatusProto.toStatusRuntimeException(builder.build()));
|
||||
|
||||
GrpcTestUtils.assertStatusException(statusCode.toStatus(),
|
||||
() -> tagTestServiceBlockingStub.tagEndpoint(Empty.getDefaultInstance()));
|
||||
|
||||
final Counter rpcCount = find(Counter.class, MetricServerInterceptor.RPC_COUNTER_NAME);
|
||||
assertThat(rpcCount.count()).isCloseTo(1.0, offset(0.01));
|
||||
assertThat(rpcCount.getId().getTag("statusCode")).isEqualTo(statusCode.name());
|
||||
assertThat(rpcCount.getId().getTag("reason")).isEqualTo(expectedReasonTag);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testStreamingResponseReason() {
|
||||
final TagTestServiceGrpc.TagTestServiceBlockingStub tagTestServiceBlockingStub =
|
||||
TagTestServiceGrpc.newBlockingStub(channel);
|
||||
when(tagResponseSupplier.get())
|
||||
.thenReturn(TagResponse.newBuilder().setReason1(true).build())
|
||||
.thenReturn(TagResponse.newBuilder().setNoReason(true).build())
|
||||
.thenReturn(null);
|
||||
|
||||
tagTestServiceBlockingStub.streamingTagEndpoint(Empty.getDefaultInstance()).forEachRemaining(_ -> {});
|
||||
final Counter messageCounter = find(Counter.class, MetricServerInterceptor.RESPONSE_COUNTER_NAME);
|
||||
assertThat(messageCounter.count()).isCloseTo(2.0, offset(0.01));
|
||||
|
||||
final Counter rpcCount = find(Counter.class, MetricServerInterceptor.RPC_COUNTER_NAME);
|
||||
assertThat(rpcCount.count()).isCloseTo(1.0, offset(0.01));
|
||||
assertThat(rpcCount.getId().getTag("statusCode")).isEqualTo("OK");
|
||||
assertThat(rpcCount.getId().getTag("reason")).isEqualTo(MetricServerInterceptor.DEFAULT_SUCCESS_REASON);
|
||||
}
|
||||
|
||||
private <T extends Meter> T find(Class<T> cls, final String name) {
|
||||
final Meter meter = simpleMeterRegistry.getMeters().stream()
|
||||
.filter(m -> m.getId().getName().equals(name))
|
||||
@@ -162,4 +274,32 @@ public class MetricServerInterceptorTest {
|
||||
}
|
||||
throw new IllegalArgumentException("Meter " + name + " should be an instance of " + cls);
|
||||
}
|
||||
|
||||
class TagTestServiceImpl extends SimpleTagTestServiceGrpc.TagTestServiceImplBase {
|
||||
|
||||
private Supplier<TagResponse> tagResponseSupplier;
|
||||
TagTestServiceImpl(Supplier<TagResponse> tagResponseSupplier) {
|
||||
this.tagResponseSupplier = tagResponseSupplier;
|
||||
}
|
||||
|
||||
@Override
|
||||
public TagResponse tagEndpoint(final Empty request) {
|
||||
return tagResponseSupplier.get();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Flow.Publisher<TagResponse> streamingTagEndpoint(com.google.protobuf.Empty request) {
|
||||
return JdkFlowAdapter.publisherToFlowPublisher(Flux.<TagResponse>create(sink -> {
|
||||
while (!sink.isCancelled()) {
|
||||
TagResponse item = tagResponseSupplier.get();
|
||||
if (item == null) {
|
||||
sink.complete();
|
||||
break;
|
||||
}
|
||||
sink.next(item);
|
||||
}
|
||||
})
|
||||
.subscribeOn(Schedulers.boundedElastic()));
|
||||
}
|
||||
}
|
||||
}
|
||||
-6
@@ -63,10 +63,4 @@ class PaymentsGrpcServiceTest extends SimpleBaseGrpcTest<PaymentsGrpcService, Pa
|
||||
assertStatusException(Status.UNAVAILABLE, () -> authenticatedServiceStub().getCurrencyConversions(
|
||||
GetCurrencyConversionsRequest.newBuilder().build()));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testUnauthenticated() throws Exception {
|
||||
assertStatusException(Status.UNAUTHENTICATED, () -> unauthenticatedServiceStub().getCurrencyConversions(
|
||||
GetCurrencyConversionsRequest.newBuilder().build()));
|
||||
}
|
||||
}
|
||||
+4
-4
@@ -4,9 +4,6 @@
|
||||
*/
|
||||
package org.whispersystems.textsecuregcm.grpc;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
import io.grpc.ManagedChannel;
|
||||
import io.grpc.Metadata;
|
||||
import io.grpc.Server;
|
||||
@@ -30,9 +27,12 @@ import org.signal.chat.rpc.GetRequestAttributesRequest;
|
||||
import org.signal.chat.rpc.GetRequestAttributesResponse;
|
||||
import org.signal.chat.rpc.RequestAttributesGrpc;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
public class RequestAttributesInterceptorTest {
|
||||
|
||||
private static String USER_AGENT = "Signal-Android/4.53.7 (Android 8.1; libsignal)";
|
||||
private static final String USER_AGENT = "Signal-Android/4.53.7 (Android 8.1; libsignal)";
|
||||
private Server server;
|
||||
private AtomicBoolean removeUserAgent;
|
||||
|
||||
|
||||
+132
-48
@@ -47,7 +47,7 @@ import org.whispersystems.textsecuregcm.util.ResilienceUtil;
|
||||
class FaultTolerantHttpClientTest {
|
||||
|
||||
@RegisterExtension
|
||||
private final WireMockExtension wireMock = WireMockExtension.newInstance()
|
||||
private static final WireMockExtension wireMock = WireMockExtension.newInstance()
|
||||
.options(wireMockConfig().dynamicPort().dynamicHttpsPort())
|
||||
.build();
|
||||
|
||||
@@ -60,32 +60,34 @@ class FaultTolerantHttpClientTest {
|
||||
retryExecutor = Executors.newSingleThreadScheduledExecutor();
|
||||
}
|
||||
|
||||
@SuppressWarnings("ResultOfMethodCallIgnored")
|
||||
@AfterEach
|
||||
void tearDown() throws InterruptedException {
|
||||
httpExecutor.shutdown();
|
||||
httpExecutor.awaitTermination(1, TimeUnit.SECONDS);
|
||||
|
||||
retryExecutor.shutdown();
|
||||
retryExecutor.awaitTermination(1, TimeUnit.SECONDS);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testSimpleGet() {
|
||||
void testSimpleGetAsync() {
|
||||
wireMock.stubFor(get(urlEqualTo("/ping"))
|
||||
.willReturn(aResponse()
|
||||
.withHeader("Content-Type", "text/plain")
|
||||
.withBody("Pong!")));
|
||||
|
||||
FaultTolerantHttpClient client = FaultTolerantHttpClient.newBuilder("testSimpleGet", httpExecutor)
|
||||
final FaultTolerantHttpClient client = FaultTolerantHttpClient.newBuilder("testSimpleGet", httpExecutor)
|
||||
.withRetry(null, retryExecutor)
|
||||
.withVersion(HttpClient.Version.HTTP_2)
|
||||
.build();
|
||||
|
||||
HttpRequest request = HttpRequest.newBuilder()
|
||||
.uri(URI.create("http://localhost:" + wireMock.getPort() + "/ping"))
|
||||
.GET()
|
||||
.build();
|
||||
final HttpRequest request = HttpRequest.newBuilder()
|
||||
.uri(URI.create("http://localhost:" + wireMock.getPort() + "/ping"))
|
||||
.GET()
|
||||
.build();
|
||||
|
||||
HttpResponse<String> response = client.sendAsync(request, HttpResponse.BodyHandlers.ofString()).join();
|
||||
final HttpResponse<String> response = client.sendAsync(request, HttpResponse.BodyHandlers.ofString()).join();
|
||||
|
||||
assertThat(response.statusCode()).isEqualTo(200);
|
||||
assertThat(response.body()).isEqualTo("Pong!");
|
||||
@@ -94,24 +96,49 @@ class FaultTolerantHttpClientTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
void testRetryGet() {
|
||||
wireMock.stubFor(get(urlEqualTo("/failure"))
|
||||
.willReturn(aResponse()
|
||||
.withStatus(500)
|
||||
.withHeader("Content-Type", "text/plain")
|
||||
.withBody("Pong!")));
|
||||
void testSimpleGetSync() throws IOException, InterruptedException {
|
||||
wireMock.stubFor(get(urlEqualTo("/ping"))
|
||||
.willReturn(aResponse()
|
||||
.withHeader("Content-Type", "text/plain")
|
||||
.withBody("Pong!")));
|
||||
|
||||
FaultTolerantHttpClient client = FaultTolerantHttpClient.newBuilder("testRetryGet", httpExecutor)
|
||||
final FaultTolerantHttpClient client = FaultTolerantHttpClient.newBuilder("testSimpleGet", httpExecutor)
|
||||
.withRetry(null, retryExecutor)
|
||||
.withVersion(HttpClient.Version.HTTP_2)
|
||||
.build();
|
||||
|
||||
HttpRequest request = HttpRequest.newBuilder()
|
||||
.uri(URI.create("http://localhost:" + wireMock.getPort() + "/failure"))
|
||||
.GET()
|
||||
.build();
|
||||
final HttpRequest request = HttpRequest.newBuilder()
|
||||
.uri(URI.create("http://localhost:" + wireMock.getPort() + "/ping"))
|
||||
.GET()
|
||||
.build();
|
||||
|
||||
HttpResponse<String> response = client.sendAsync(request, HttpResponse.BodyHandlers.ofString()).join();
|
||||
final HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
|
||||
|
||||
assertThat(response.statusCode()).isEqualTo(200);
|
||||
assertThat(response.body()).isEqualTo("Pong!");
|
||||
|
||||
wireMock.verify(1, getRequestedFor(urlEqualTo("/ping")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testRetryGetAsync() {
|
||||
wireMock.stubFor(get(urlEqualTo("/failure"))
|
||||
.willReturn(aResponse()
|
||||
.withStatus(500)
|
||||
.withHeader("Content-Type", "text/plain")
|
||||
.withBody("Pong!")));
|
||||
|
||||
final FaultTolerantHttpClient client = FaultTolerantHttpClient.newBuilder("testRetryGet", httpExecutor)
|
||||
.withRetry(null, retryExecutor)
|
||||
.withVersion(HttpClient.Version.HTTP_2)
|
||||
.build();
|
||||
|
||||
final HttpRequest request = HttpRequest.newBuilder()
|
||||
.uri(URI.create("http://localhost:" + wireMock.getPort() + "/failure"))
|
||||
.GET()
|
||||
.build();
|
||||
|
||||
final HttpResponse<String> response = client.sendAsync(request, HttpResponse.BodyHandlers.ofString()).join();
|
||||
|
||||
assertThat(response.statusCode()).isEqualTo(500);
|
||||
assertThat(response.body()).isEqualTo("Pong!");
|
||||
@@ -120,7 +147,33 @@ class FaultTolerantHttpClientTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
void testRetryGetOnException() {
|
||||
void testRetryGetSync() throws IOException, InterruptedException {
|
||||
wireMock.stubFor(get(urlEqualTo("/failure"))
|
||||
.willReturn(aResponse()
|
||||
.withStatus(500)
|
||||
.withHeader("Content-Type", "text/plain")
|
||||
.withBody("Pong!")));
|
||||
|
||||
final FaultTolerantHttpClient client = FaultTolerantHttpClient.newBuilder("testRetryGet", httpExecutor)
|
||||
.withRetry(null, retryExecutor)
|
||||
.withVersion(HttpClient.Version.HTTP_2)
|
||||
.build();
|
||||
|
||||
final HttpRequest request = HttpRequest.newBuilder()
|
||||
.uri(URI.create("http://localhost:" + wireMock.getPort() + "/failure"))
|
||||
.GET()
|
||||
.build();
|
||||
|
||||
final HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
|
||||
|
||||
assertThat(response.statusCode()).isEqualTo(500);
|
||||
assertThat(response.body()).isEqualTo("Pong!");
|
||||
|
||||
wireMock.verify(3, getRequestedFor(urlEqualTo("/failure")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testRetryGetAsyncOnException() {
|
||||
final HttpClient mockHttpClient = mock(HttpClient.class);
|
||||
|
||||
final Retry retry = Retry.of("test", new RetryConfiguration().toRetryConfigBuilder()
|
||||
@@ -137,20 +190,47 @@ class FaultTolerantHttpClientTest {
|
||||
when(mockHttpClient.sendAsync(any(), any()))
|
||||
.thenReturn(CompletableFuture.failedFuture(new IOException("test exception")));
|
||||
|
||||
HttpRequest request = HttpRequest.newBuilder()
|
||||
final HttpRequest request = HttpRequest.newBuilder()
|
||||
.uri(URI.create("http://localhost:1234/failure"))
|
||||
.GET()
|
||||
.build();
|
||||
|
||||
try {
|
||||
client.sendAsync(request, HttpResponse.BodyHandlers.ofString()).join();
|
||||
throw new AssertionError("Should have failed!");
|
||||
} catch (CompletionException e) {
|
||||
assertThat(e.getCause()).isInstanceOf(IOException.class);
|
||||
}
|
||||
assertThatThrownBy(() -> client.sendAsync(request, HttpResponse.BodyHandlers.ofString()).join())
|
||||
.isInstanceOf(CompletionException.class)
|
||||
.hasCauseInstanceOf(IOException.class);
|
||||
|
||||
verify(mockHttpClient, times(3)).sendAsync(any(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testRetryGetSyncOnException() throws IOException, InterruptedException {
|
||||
final HttpClient mockHttpClient = mock(HttpClient.class);
|
||||
|
||||
final Retry retry = Retry.of("test", new RetryConfiguration().toRetryConfigBuilder()
|
||||
.retryOnException(throwable -> throwable instanceof IOException)
|
||||
.build());
|
||||
|
||||
final FaultTolerantHttpClient client = new FaultTolerantHttpClient(
|
||||
List.of(mockHttpClient),
|
||||
Duration.ofSeconds(1),
|
||||
retryExecutor,
|
||||
retry,
|
||||
CircuitBreaker.ofDefaults("test"));
|
||||
|
||||
when(mockHttpClient.send(any(), any()))
|
||||
.thenThrow(IOException.class);
|
||||
|
||||
final HttpRequest request = HttpRequest.newBuilder()
|
||||
.uri(URI.create("http://localhost:1234/failure"))
|
||||
.GET()
|
||||
.build();
|
||||
|
||||
assertThatThrownBy(() -> client.send(request, HttpResponse.BodyHandlers.ofString()))
|
||||
.isInstanceOf(IOException.class);
|
||||
|
||||
verify(mockHttpClient, times(3)).send(any(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testMultipleClients() throws IOException, InterruptedException {
|
||||
final HttpClient mockHttpClient1 = mock(HttpClient.class);
|
||||
@@ -177,28 +257,31 @@ class FaultTolerantHttpClientTest {
|
||||
.uri(URI.create("http://localhost:" + wireMock.getPort() + "/ping"))
|
||||
.GET()
|
||||
.build();
|
||||
final HttpResponse response = HttpClient.newHttpClient().send(request, HttpResponse.BodyHandlers.discarding());
|
||||
|
||||
final AtomicInteger client1Calls = new AtomicInteger(0);
|
||||
final AtomicInteger client2Calls = new AtomicInteger(0);
|
||||
when(mockHttpClient1.sendAsync(any(), any()))
|
||||
.thenAnswer(args -> {
|
||||
client1Calls.incrementAndGet();
|
||||
return CompletableFuture.completedFuture(response);
|
||||
});
|
||||
when(mockHttpClient2.sendAsync(any(), any()))
|
||||
.thenAnswer(args -> {
|
||||
client2Calls.incrementAndGet();
|
||||
return CompletableFuture.completedFuture(response);
|
||||
});
|
||||
try (final HttpClient httpClient = HttpClient.newHttpClient()) {
|
||||
final HttpResponse<Void> response = httpClient.send(request, HttpResponse.BodyHandlers.discarding());
|
||||
|
||||
final int numCalls = 100;
|
||||
for (int i = 0; i < numCalls; i++) {
|
||||
client.sendAsync(request, HttpResponse.BodyHandlers.ofString()).join();
|
||||
final AtomicInteger client1Calls = new AtomicInteger(0);
|
||||
final AtomicInteger client2Calls = new AtomicInteger(0);
|
||||
when(mockHttpClient1.sendAsync(any(), any()))
|
||||
.thenAnswer(_ -> {
|
||||
client1Calls.incrementAndGet();
|
||||
return CompletableFuture.completedFuture(response);
|
||||
});
|
||||
when(mockHttpClient2.sendAsync(any(), any()))
|
||||
.thenAnswer(_ -> {
|
||||
client2Calls.incrementAndGet();
|
||||
return CompletableFuture.completedFuture(response);
|
||||
});
|
||||
|
||||
final int numCalls = 100;
|
||||
for (int i = 0; i < numCalls; i++) {
|
||||
client.sendAsync(request, HttpResponse.BodyHandlers.ofString()).join();
|
||||
}
|
||||
assertThat(client2Calls.get()).isGreaterThan(0);
|
||||
assertThat(client1Calls.get()).isGreaterThan(0);
|
||||
assertThat(client1Calls.get() + client2Calls.get()).isEqualTo(numCalls);
|
||||
}
|
||||
assertThat(client2Calls.get()).isGreaterThan(0);
|
||||
assertThat(client1Calls.get()).isGreaterThan(0);
|
||||
assertThat(client1Calls.get() + client2Calls.get()).isEqualTo(numCalls);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -215,7 +298,8 @@ class FaultTolerantHttpClientTest {
|
||||
ResilienceUtil.getCircuitBreakerRegistry()
|
||||
.addConfiguration(circuitBreakerConfigurationName, circuitBreakerConfiguration.toCircuitBreakerConfig());
|
||||
|
||||
final FaultTolerantHttpClient client = FaultTolerantHttpClient.newBuilder("testNetworkFailureCircuitBreaker", httpExecutor)
|
||||
final FaultTolerantHttpClient client = FaultTolerantHttpClient.newBuilder("testNetworkFailureCircuitBreaker",
|
||||
httpExecutor)
|
||||
.withCircuitBreaker(circuitBreakerConfigurationName)
|
||||
.withRetry(null, retryExecutor)
|
||||
.withVersion(HttpClient.Version.HTTP_2)
|
||||
|
||||
+3
-2
@@ -22,6 +22,7 @@ import java.util.Collections;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
import io.micrometer.core.instrument.Tags;
|
||||
import org.eclipse.jetty.http.HttpURI;
|
||||
import org.eclipse.jetty.server.Request;
|
||||
import org.eclipse.jetty.server.Response;
|
||||
@@ -55,7 +56,7 @@ class MetricsHttpChannelListenerTest {
|
||||
when(meterRegistry.counter(eq(MetricsHttpChannelListener.REQUEST_COUNTER_NAME), any(Iterable.class)))
|
||||
.thenReturn(requestCounter);
|
||||
|
||||
when(meterRegistry.counter(eq(MetricsHttpChannelListener.REQUESTS_BY_VERSION_COUNTER_NAME), any(Iterable.class)))
|
||||
when(meterRegistry.counter(eq(MetricsHttpChannelListener.REQUESTS_BY_VERSION_COUNTER_NAME), any(Tags.class)))
|
||||
.thenReturn(requestsByVersionCounter);
|
||||
|
||||
when(meterRegistry.counter(eq(MetricsHttpChannelListener.RESPONSE_BYTES_COUNTER_NAME), any(Iterable.class)))
|
||||
@@ -152,7 +153,7 @@ class MetricsHttpChannelListenerTest {
|
||||
listener.onComplete(request);
|
||||
|
||||
if (versionActive) {
|
||||
final ArgumentCaptor<Iterable<Tag>> tagCaptor = ArgumentCaptor.forClass(Iterable.class);
|
||||
final ArgumentCaptor<Tags> tagCaptor = ArgumentCaptor.forClass(Tags.class);
|
||||
verify(meterRegistry).counter(eq(MetricsHttpChannelListener.REQUESTS_BY_VERSION_COUNTER_NAME),
|
||||
tagCaptor.capture());
|
||||
final Set<Tag> tags = new HashSet<>();
|
||||
|
||||
+2
-1
@@ -24,6 +24,7 @@ import io.dropwizard.jersey.jackson.JacksonMessageBodyProvider;
|
||||
import io.micrometer.core.instrument.Counter;
|
||||
import io.micrometer.core.instrument.MeterRegistry;
|
||||
import io.micrometer.core.instrument.Tag;
|
||||
import io.micrometer.core.instrument.Tags;
|
||||
import jakarta.ws.rs.GET;
|
||||
import jakarta.ws.rs.Path;
|
||||
import java.io.IOException;
|
||||
@@ -122,7 +123,7 @@ class MetricsRequestEventListenerTest {
|
||||
.thenReturn(responseBytesCounter);
|
||||
when(meterRegistry.counter(eq(MetricsRequestEventListener.REQUEST_BYTES_COUNTER_NAME), any(Iterable.class)))
|
||||
.thenReturn(requestBytesCounter);
|
||||
when(meterRegistry.counter(eq(MetricsRequestEventListener.REQUESTS_BY_VERSION_COUNTER_NAME), any(Iterable.class)))
|
||||
when(meterRegistry.counter(eq(MetricsRequestEventListener.REQUESTS_BY_VERSION_COUNTER_NAME), any(Tags.class)))
|
||||
.thenReturn(requestsByVersionCounter);
|
||||
|
||||
listener.onEvent(event);
|
||||
|
||||
@@ -14,6 +14,7 @@ import static org.mockito.ArgumentMatchers.anyByte;
|
||||
import static org.mockito.ArgumentMatchers.anyLong;
|
||||
import static org.mockito.Mockito.doThrow;
|
||||
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;
|
||||
@@ -47,6 +48,7 @@ import org.whispersystems.textsecuregcm.identity.IdentityType;
|
||||
import org.whispersystems.textsecuregcm.identity.PniServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.identity.ServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.metrics.UserAgentTagUtil;
|
||||
import org.whispersystems.textsecuregcm.spam.MessageDeliveryListener;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.Device;
|
||||
import org.whispersystems.textsecuregcm.storage.MessagesManager;
|
||||
@@ -58,14 +60,18 @@ class MessageSenderTest {
|
||||
|
||||
private MessagesManager messagesManager;
|
||||
private PushNotificationManager pushNotificationManager;
|
||||
private MessageDeliveryListener messageDeliveryListener;
|
||||
|
||||
private MessageSender messageSender;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
messagesManager = mock(MessagesManager.class);
|
||||
pushNotificationManager = mock(PushNotificationManager.class);
|
||||
messageDeliveryListener = mock(MessageDeliveryListener.class);
|
||||
|
||||
messageSender = new MessageSender(messagesManager, pushNotificationManager);
|
||||
messageSender.addMessageDeliveryListener(messageDeliveryListener);
|
||||
}
|
||||
|
||||
|
||||
@@ -124,6 +130,15 @@ class MessageSenderTest {
|
||||
} else {
|
||||
verifyNoInteractions(pushNotificationManager);
|
||||
}
|
||||
|
||||
verify(messageDeliveryListener).handleMessageDelivered(account,
|
||||
deviceId,
|
||||
ephemeral,
|
||||
urgent,
|
||||
false,
|
||||
true,
|
||||
false,
|
||||
false);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -156,6 +171,15 @@ class MessageSenderTest {
|
||||
|
||||
assertEquals(new MismatchedDevices(Collections.emptySet(), Collections.emptySet(), Set.of(deviceId)),
|
||||
mismatchedDevicesException.getMismatchedDevices());
|
||||
|
||||
verify(messageDeliveryListener, never()).handleMessageDelivered(any(),
|
||||
anyByte(),
|
||||
anyBoolean(),
|
||||
anyBoolean(),
|
||||
anyBoolean(),
|
||||
anyBoolean(),
|
||||
anyBoolean(),
|
||||
anyBoolean());
|
||||
}
|
||||
|
||||
@CartesianTest
|
||||
@@ -215,6 +239,15 @@ class MessageSenderTest {
|
||||
} else {
|
||||
verifyNoInteractions(pushNotificationManager);
|
||||
}
|
||||
|
||||
verify(messageDeliveryListener).handleMessageDelivered(account,
|
||||
deviceId,
|
||||
ephemeral,
|
||||
urgent,
|
||||
false,
|
||||
true,
|
||||
true,
|
||||
false);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -259,6 +292,15 @@ class MessageSenderTest {
|
||||
|
||||
assertEquals(Map.of(serviceIdentifier, new MismatchedDevices(Collections.emptySet(), Collections.emptySet(), Set.of(deviceId))),
|
||||
mismatchedDevicesException.getMismatchedDevicesByServiceIdentifier());
|
||||
|
||||
verify(messageDeliveryListener, never()).handleMessageDelivered(any(),
|
||||
anyByte(),
|
||||
anyBoolean(),
|
||||
anyBoolean(),
|
||||
anyBoolean(),
|
||||
anyBoolean(),
|
||||
anyBoolean(),
|
||||
anyBoolean());
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
|
||||
Loaded 100 of 108 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user