Compare commits

...
Author SHA1 Message Date
Chris Eager 5ec8628b51 Update to the latest version of the spam filter 2026-02-04 15:59:34 -06:00
Jon Chambers ad21f002ab Add a counter to verify that it's safe to remove legacy combined UAK credentials 2026-02-04 15:50:59 -06:00
Jon Chambers 1e5fcbdd20 Add a utility method for getting UA tags from request contexts 2026-02-04 15:50:59 -06:00
Ravi Khadiwala d34fc29ba2 Add null checks in IncomingMessageList 2026-02-04 15:50:45 -06:00
Chris Eager e0bf1df16f Update to the latest version of the spam filter 2026-02-04 14:19:23 -06:00
Chris Eager 9a1c450458 Make VerificationSession.sessionId not-null 2026-02-04 12:07:44 -06:00
Chris Eager e5209d84bf Update to the latest version of the spam filter 2026-02-04 10:21:45 -06:00
Chris Eager 969788b267 Include sessionId in VerificationSession record 2026-02-04 10:06:25 -06:00
Chris Eager d0bbaaea52 Update to the latest version of the spam filter 2026-01-30 13:13:26 -06:00
Chris Eager b01ef94c69 Update to the latest version of the spam filter 2026-01-30 11:52:34 -06:00
Jonathan Klabunde Tomer 040f3190cb directly subscribe to item publisher in account crawlers 2026-01-30 10:16:26 -06:00
Chris Eager 77bf44fda5 Remove deprecated /v2/accounts/phone_number_identity_key_distribution 2026-01-30 10:13:41 -06:00
Ravi Khadiwala 185654fc10 Use userAgent instead of signalAgent as metrics platform tag 2026-01-30 10:13:21 -06:00
Ravi Khadiwala 159e1f13f0 Fix credential age calculation 2026-01-30 10:13:21 -06:00
Jon Chambers 61ab765391 Require that LinkDeviceRequest has non-null account attributes 2026-01-30 10:13:11 -06:00
Jon Chambers 63c39645d2 Add a (failing!) test for attempting to link a device with null account attributes 2026-01-30 10:13:11 -06:00
Chris Eager cf518ce910 Update to the latest version of the spam filter 2026-01-30 09:44:20 -06:00
Ravi Khadiwala e14dbfc9ad Fix merge conflict in HlrLookupResult 2026-01-29 11:24:18 -06:00
Ravi Khadiwala 734d369fb1 Update to the latest version of the spam filter 2026-01-29 11:17:08 -06:00
ravi-signal ee81faa82d Add an allow-list for gRPC methods 2026-01-29 11:15:04 -06:00
Jon Chambers c0d0d5f5da Extract "is ported" data from HLR Lookup responses 2026-01-29 12:14:26 -05:00
Jon Chambers ff8194ae5f Add "is ported" to CarrierData 2026-01-29 12:14:26 -05:00
Jon Chambers c69abb5200 Instrument credits spent 2026-01-29 12:14:00 -05:00
Ravi Khadiwala fb1c20582e Instrument /v2/svr/auth/check credential age 2026-01-28 17:44:11 -05:00
Ravi Khadiwala 0357b25f92 Update to the latest version of the spam filter 2026-01-28 16:42:23 -06:00
Ravi Khadiwala d197e22e0a Fix argument to updateWithRetries updater 2026-01-28 17:39:32 -05:00
ravi-signal e6116044f8 Instrument registration recovery password modifications 2026-01-28 16:37:50 -06:00
ravi-signal 2a7e99e9f0 Update credentials and calling gRPC services to new error model 2026-01-28 16:36:12 -06:00
Ravi Khadiwala 8023a9346f Convert call quality gRPC service to new error model 2026-01-28 17:35:11 -05:00
Ravi Khadiwala 517c5b8056 Call CallQualitySurveryManager#validateRequest 2026-01-28 17:35:11 -05:00
dependabot[bot] a6a089e93f Bump actions/setup-java in the minor-actions-dependencies group
Bumps the minor-actions-dependencies group with 1 update: [actions/setup-java](https://github.com/actions/setup-java).


Updates `actions/setup-java` from 5.0.0 to 5.2.0
- [Release notes](https://github.com/actions/setup-java/releases)
- [Commits](https://github.com/actions/setup-java/compare/dded0888837ed1f317902acf8a20df0ad188d165...be666c2fcd27ec809703dec50e508c2fdc7f6654)

---
updated-dependencies:
- dependency-name: actions/setup-java
  dependency-version: 5.2.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: minor-actions-dependencies
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-01-26 13:48:55 -05:00
dependabot[bot] 6c2999dd55 Bump actions/checkout from 5.0.0 to 6.0.2
Bumps [actions/checkout](https://github.com/actions/checkout) from 5.0.0 to 6.0.2.
- [Release notes](https://github.com/actions/checkout/releases)
- [Changelog](https://github.com/actions/checkout/blob/main/CHANGELOG.md)
- [Commits](https://github.com/actions/checkout/compare/08c6903cd8c0fde910a37f88322edcfb5dd907a8...de0fac2e4500dabe0009e67214ff5f5447ce83dd)

---
updated-dependencies:
- dependency-name: actions/checkout
  dependency-version: 6.0.2
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-01-26 13:05:12 -05:00
dependabot[bot] 14862c58c8 Bump aws-actions/configure-aws-credentials from 4.2.1 to 5.1.1
Bumps [aws-actions/configure-aws-credentials](https://github.com/aws-actions/configure-aws-credentials) from 4.2.1 to 5.1.1.
- [Release notes](https://github.com/aws-actions/configure-aws-credentials/releases)
- [Changelog](https://github.com/aws-actions/configure-aws-credentials/blob/main/CHANGELOG.md)
- [Commits](https://github.com/aws-actions/configure-aws-credentials/compare/b47578312673ae6fa5b5096b330d9fbac3d116df...61815dcd50bd041e203e49132bacad1fd04d2708)

---
updated-dependencies:
- dependency-name: aws-actions/configure-aws-credentials
  dependency-version: 5.1.1
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-01-26 13:05:02 -05:00
Ravi Khadiwala 645161cc09 add dependabot.yml 2026-01-26 11:36:30 -05:00
Jon Chambers 065e730200 Update to the latest version of the spam filter 2026-01-23 16:37:38 -05:00
Ravi Khadiwala 7e7bef32cc Convert service protos to line comments 2026-01-23 16:37:01 -05:00
ravi-signal 5b1d4ce95e Convert backup services to use new error model 2026-01-23 14:25:15 -06:00
Ravi Khadiwala 12d9637f21 Update to the latest version of the spam filter 2026-01-23 14:24:17 -06:00
ravi-signal 924ab88e93 Update dependencies 2026-01-23 13:32:20 -06:00
92 changed files with 2530 additions and 2438 deletions

No files matched your search

+20
View File
@@ -0,0 +1,20 @@
version: 2
updates:
- package-ecosystem: github-actions
directory: /
schedule:
interval: monthly
groups:
minor-actions-dependencies:
# GitHub Actions: Only group minor and patch updates (we want to carefully review major updates)
update-types: [ minor, patch ]
- package-ecosystem: maven
directory: /
schedule:
interval: monthly
groups:
minor-java-dependencies:
# Java: Only group minor and patch updates (we want to carefully review major updates)
update-types: [ minor, patch ]
+2 -2
View File
@@ -11,8 +11,8 @@ jobs:
contents: write
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@08c6903cd8c0fde910a37f88322edcfb5dd907a8 # v5.0.0
- uses: actions/setup-java@dded0888837ed1f317902acf8a20df0ad188d165 # v5.0.0
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
- uses: actions/setup-java@be666c2fcd27ec809703dec50e508c2fdc7f6654 # v5.2.0
with:
distribution: 'temurin'
java-version-file: .java-version
+3 -3
View File
@@ -18,13 +18,13 @@ jobs:
id-token: write
contents: read
steps:
- uses: actions/checkout@08c6903cd8c0fde910a37f88322edcfb5dd907a8 # v5.0.0
- uses: actions/setup-java@dded0888837ed1f317902acf8a20df0ad188d165 # v5.0.0
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
- uses: actions/setup-java@be666c2fcd27ec809703dec50e508c2fdc7f6654 # v5.2.0
with:
distribution: 'temurin'
java-version-file: .java-version
cache: 'maven'
- uses: aws-actions/configure-aws-credentials@b47578312673ae6fa5b5096b330d9fbac3d116df # v5.0.0
- uses: aws-actions/configure-aws-credentials@61815dcd50bd041e203e49132bacad1fd04d2708 # v5.0.0
name: Configure AWS credentials from Test account
with:
role-to-assume: ${{ vars.AWS_ROLE }}
+2 -2
View File
@@ -25,9 +25,9 @@ jobs:
options: --name foundationdb1
steps:
- uses: actions/checkout@08c6903cd8c0fde910a37f88322edcfb5dd907a8 # v5.0.0
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
- name: Set up JDK
uses: actions/setup-java@dded0888837ed1f317902acf8a20df0ad188d165 # v5.0.0
uses: actions/setup-java@be666c2fcd27ec809703dec50e508c2fdc7f6654 # v5.2.0
with:
distribution: 'temurin'
java-version-file: .java-version
@@ -18,6 +18,7 @@ import org.whispersystems.textsecuregcm.storage.RegistrationRecoveryPasswords;
import org.whispersystems.textsecuregcm.storage.RegistrationRecoveryPasswordsManager;
import org.whispersystems.textsecuregcm.storage.VerificationSessionManager;
import org.whispersystems.textsecuregcm.storage.VerificationSessions;
import org.whispersystems.textsecuregcm.util.Util;
import software.amazon.awssdk.auth.credentials.AwsCredentialsProvider;
import software.amazon.awssdk.auth.credentials.DefaultCredentialsProvider;
import software.amazon.awssdk.services.dynamodb.DynamoDbAsyncClient;
@@ -62,7 +63,8 @@ public class IntegrationTools {
public CompletableFuture<Void> populateRecoveryPassword(final String phoneNumber, final byte[] password) {
return phoneNumberIdentifiers
.getPhoneNumberIdentifier(phoneNumber)
.thenCompose(pni -> registrationRecoveryPasswordsManager.store(pni, password));
.thenCompose(pni -> registrationRecoveryPasswordsManager.store(pni, password))
.thenRun(Util.NOOP);
}
public CompletableFuture<Optional<String>> peekVerificationSessionPushChallenge(final String sessionId) {
+17 -11
View File
@@ -46,9 +46,9 @@
<properties>
<aws.sdk2.version>2.41.11</aws.sdk2.version>
<braintree.version>3.44.0</braintree.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,37 +57,38 @@
<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.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>
<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 -->
@@ -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>
+4 -23
View File
@@ -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>
@@ -31,6 +31,7 @@ import org.whispersystems.textsecuregcm.configuration.DeviceCheckConfiguration;
import org.whispersystems.textsecuregcm.configuration.DirectoryV2Configuration;
import org.whispersystems.textsecuregcm.configuration.DynamoDbClientFactory;
import org.whispersystems.textsecuregcm.configuration.DynamoDbTables;
import org.whispersystems.textsecuregcm.configuration.GrpcAllowListConfiguration;
import org.whispersystems.textsecuregcm.configuration.ExternalRequestFilterConfiguration;
import org.whispersystems.textsecuregcm.configuration.FaultTolerantRedisClientFactory;
import org.whispersystems.textsecuregcm.configuration.FaultTolerantRedisClusterFactory;
@@ -348,6 +349,11 @@ public class WhisperServerConfiguration extends Configuration {
@JsonProperty
private GrpcConfiguration grpc;
@NotNull
@Valid
@JsonProperty
private GrpcAllowListConfiguration grpcAllowList = new GrpcAllowListConfiguration();
@Valid
@NotNull
@JsonProperty
@@ -589,6 +595,10 @@ public class WhisperServerConfiguration extends Configuration {
return grpc;
}
public GrpcAllowListConfiguration getGrpcAllowList() {
return grpcAllowList;
}
public S3ObjectMonitorFactory getAsnTableConfiguration() {
return asnTable;
}
@@ -143,6 +143,7 @@ import org.whispersystems.textsecuregcm.filters.TimestampResponseFilter;
import org.whispersystems.textsecuregcm.grpc.AccountsAnonymousGrpcService;
import org.whispersystems.textsecuregcm.grpc.AccountsGrpcService;
import org.whispersystems.textsecuregcm.grpc.CallQualitySurveyGrpcService;
import org.whispersystems.textsecuregcm.grpc.GrpcAllowListInterceptor;
import org.whispersystems.textsecuregcm.grpc.ErrorMappingInterceptor;
import org.whispersystems.textsecuregcm.grpc.ExternalServiceCredentialsAnonymousGrpcService;
import org.whispersystems.textsecuregcm.grpc.ExternalServiceCredentialsGrpcService;
@@ -166,6 +167,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,7 +210,6 @@ 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;
@@ -876,6 +877,8 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
final MetricServerInterceptor metricServerInterceptor = new MetricServerInterceptor(Metrics.globalRegistry, clientReleaseManager);
final ErrorMappingInterceptor errorMappingInterceptor = new ErrorMappingInterceptor();
final GrpcAllowListInterceptor grpcAllowListInterceptor =
new GrpcAllowListInterceptor(config.getGrpcAllowList().enableAll(), config.getGrpcAllowList().enabledServices(), config.getGrpcAllowList().enabledMethods());
final RequestAttributesInterceptor requestAttributesInterceptor = new RequestAttributesInterceptor();
final ValidatingInterceptor validatingInterceptor = new ValidatingInterceptor();
@@ -896,6 +899,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
// Note: interceptors run in the reverse order they are added; the remote deprecation filter
// depends on the user-agent context so it has to come first here!
validatingInterceptor,
grpcAllowListInterceptor,
metricServerInterceptor,
errorMappingInterceptor,
remoteDeprecationFilter,
@@ -915,6 +919,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
// depends on the user-agent context so it has to come first here!
grpcExternalRequestFilter,
validatingInterceptor,
grpcAllowListInterceptor,
metricServerInterceptor,
errorMappingInterceptor,
remoteDeprecationFilter,
@@ -1200,6 +1205,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
new ObsoletePhoneNumberFormatExceptionMapper(),
new RegistrationServiceSenderExceptionMapper(),
new SubscriptionExceptionMapper(),
new BackupExceptionMapper(),
new JsonMappingExceptionMapper()
).forEach(exceptionMapper -> {
environment.jersey().register(exceptionMapper);
@@ -192,17 +192,9 @@ public class ExternalServiceCredentialsGenerator {
: Optional.empty();
}
/**
* Given an instance of {@link ExternalServiceCredentials} object and the max allowed age for those credentials,
* checks if credentials are valid and not expired.
* @param credentials an instance of {@link ExternalServiceCredentials}
* @param maxAgeSeconds age in seconds
* @return An optional with a timestamp (seconds) of when the credentials were generated,
* or an empty optional if the password doesn't match the username for any reason (including malformed data)
*/
public Optional<Long> validateAndGetTimestamp(final ExternalServiceCredentials credentials, final long maxAgeSeconds) {
return validateAndGetTimestamp(credentials)
.filter(ts -> currentTimeSeconds() - ts <= maxAgeSeconds);
@VisibleForTesting
boolean isCredentialExpired(final long credentialTimestamp, final long maxAgeSeconds) {
return currentTimeSeconds() - credentialTimestamp > maxAgeSeconds;
}
private boolean shouldDeriveUsername() {
@@ -15,12 +15,27 @@ public class ExternalServiceCredentialsSelector {
private ExternalServiceCredentialsSelector() {}
public record CredentialInfo(String token, boolean valid, ExternalServiceCredentials credentials, long timestamp) {
public enum CredentialStatus {
// The token passes verification, is not expired, and is the most recent token available
VALID,
// The token was malformed or the signature was invalid
FAILED_VERIFICATION,
// The credential was correctly signed, but exceeded the maximum credential age
EXPIRED,
// There was a more recent credential available with the same username
REPLACED
}
public record CredentialInfo(String token, ExternalServiceCredentials credentials, long timestamp, CredentialStatus status) {
/**
* @return a copy of this record with valid=false
* @return a copy of this record that indicates it has been replaced with a more up-to-date token
*/
private CredentialInfo invalidate() {
return new CredentialInfo(token, false, credentials, timestamp);
private CredentialInfo replaced() {
return new CredentialInfo(token, credentials, timestamp, CredentialStatus.REPLACED);
}
public boolean valid() {
return status == CredentialStatus.VALID;
}
}
@@ -47,13 +62,18 @@ public class ExternalServiceCredentialsSelector {
// (note that password part may also contain ':' characters)
final String[] parts = token.split(":", 2);
if (parts.length != 2) {
results.add(new CredentialInfo(token, false, null, 0L));
results.add(new CredentialInfo(token, null, 0L, CredentialStatus.FAILED_VERIFICATION));
continue;
}
final ExternalServiceCredentials credentials = new ExternalServiceCredentials(parts[0], parts[1]);
final Optional<Long> maybeTimestamp = credentialsGenerator.validateAndGetTimestamp(credentials, maxAgeSeconds);
final Optional<Long> maybeTimestamp = credentialsGenerator.validateAndGetTimestamp(credentials);
if (maybeTimestamp.isEmpty()) {
results.add(new CredentialInfo(token, false, null, 0L));
results.add(new CredentialInfo(token, credentials, 0L, CredentialStatus.FAILED_VERIFICATION));
continue;
}
final long credentialTs = maybeTimestamp.get();
if (credentialsGenerator.isCredentialExpired(credentialTs, maxAgeSeconds)) {
results.add(new CredentialInfo(token, credentials, credentialTs, CredentialStatus.EXPIRED));
continue;
}
@@ -62,17 +82,17 @@ public class ExternalServiceCredentialsSelector {
final long timestamp = maybeTimestamp.get();
final CredentialInfo best = bestForUsername.get(credentials.username());
if (best == null) {
bestForUsername.put(credentials.username(), new CredentialInfo(token, true, credentials, timestamp));
bestForUsername.put(credentials.username(), new CredentialInfo(token, credentials, timestamp, CredentialStatus.VALID));
continue;
}
if (best.timestamp() < timestamp) {
// we found a better credential for the username
bestForUsername.put(credentials.username(), new CredentialInfo(token, true, credentials, timestamp));
bestForUsername.put(credentials.username(), new CredentialInfo(token, credentials, timestamp, CredentialStatus.VALID));
// mark the previous best as an invalid credential, since we have a better credential now
results.add(best.invalidate());
results.add(best.replaced());
} else {
// the credential we already had was more recent, this one can be marked invalid
results.add(new CredentialInfo(token, false, null, 0L));
results.add(new CredentialInfo(token, null, 0L, CredentialStatus.REPLACED));
}
}
@@ -153,7 +153,7 @@ public class RegistrationLockVerificationManager {
// This allows users to re-register via registration recovery password
// instead of always being forced to fall back to SMS verification.
if (!phoneVerificationType.equals(PhoneVerificationRequest.VerificationType.RECOVERY_PASSWORD) || clientRegistrationLock != null) {
registrationRecoveryPasswordsManager.remove(updatedAccount.getIdentifier(IdentityType.PNI));
registrationRecoveryPasswordsManager.remove(updatedAccount.getIdentifier(IdentityType.PNI)).join();
}
final List<Byte> deviceIds = updatedAccount.getDevices().stream().map(Device::getId).toList();
@@ -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;
@@ -98,15 +99,14 @@ public class BackupAuthManager {
final Account account,
final Device device,
final Optional<BackupAuthCredentialRequest> messagesBackupCredentialRequest,
final Optional<BackupAuthCredentialRequest> mediaBackupCredentialRequest) throws RateLimitExceededException {
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)
@@ -191,7 +191,7 @@ public class BackupAuthManager {
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)) {
@@ -206,7 +206,7 @@ public class BackupAuthManager {
// 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);
@@ -224,10 +224,7 @@ public class BackupAuthManager {
})
.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));
}
}
@@ -239,41 +236,34 @@ public class BackupAuthManager {
*/
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();
}
boolean receiptAllowed = redeemedReceiptsManager
.put(receiptSerial, receiptExpiration.getEpochSecond(), receiptLevel, account.getUuid())
.join();
if (!receiptAllowed) {
throw Status.INVALID_ARGUMENT
.withDescription("receipt serial is already redeemed")
.asRuntimeException();
throw new BackupBadReceiptException("receipt serial is already redeemed");
}
extendBackupVoucher(account, new Account.BackupVoucher(receiptLevel, receiptExpiration));
}
@@ -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);
}
}
@@ -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);
}
}
@@ -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);
}
}
@@ -7,8 +7,6 @@ package org.whispersystems.textsecuregcm.backup;
import com.google.common.annotations.VisibleForTesting;
import io.dropwizard.util.DataSize;
import io.grpc.Status;
import io.grpc.StatusRuntimeException;
import io.micrometer.core.instrument.DistributionSummary;
import io.micrometer.core.instrument.Metrics;
import io.micrometer.core.instrument.Tag;
@@ -128,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 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
@@ -141,16 +140,14 @@ public class BackupManager {
verifyPresentation(presentation).verifySignature(signature, publicKey);
ExceptionUtils.unwrapSupply(
PublicKeyConflictException.class,
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");
});
}
@@ -161,9 +158,11 @@ 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 BackupUploadDescriptor createMessageBackupUploadDescriptor(
final AuthenticatedBackupUser backupUser) {
final AuthenticatedBackupUser backupUser) throws BackupPermissionException, BackupWrongCredentialTypeException {
checkBackupLevel(backupUser, BackupLevel.FREE);
checkBackupCredentialType(backupUser, BackupCredentialType.MESSAGES);
@@ -173,7 +172,7 @@ public class BackupManager {
}
public BackupUploadDescriptor createTemporaryAttachmentUploadDescriptor(final AuthenticatedBackupUser backupUser)
throws RateLimitExceededException {
throws RateLimitExceededException, BackupPermissionException, BackupWrongCredentialTypeException {
checkBackupLevel(backupUser, BackupLevel.PAID);
checkBackupCredentialType(backupUser, BackupCredentialType.MEDIA);
@@ -189,8 +188,9 @@ public class BackupManager {
* 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 void ttlRefresh(final AuthenticatedBackupUser backupUser) {
public void ttlRefresh(final AuthenticatedBackupUser backupUser) throws BackupPermissionException {
checkBackupLevel(backupUser, BackupLevel.FREE);
// update message backup TTL
final StoredBackupAttributes storedBackupAttributes = backupsDb.ttlRefresh(backupUser).join();
@@ -229,10 +229,15 @@ 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 BackupInfo backupInfo(final AuthenticatedBackupUser backupUser) {
public BackupInfo backupInfo(final AuthenticatedBackupUser backupUser)
throws BackupNotFoundException, BackupPermissionException {
checkBackupLevel(backupUser, BackupLevel.FREE);
final BackupsDb.BackupDescription backupDescription = backupsDb.describeBackup(backupUser).join();
final BackupsDb.BackupDescription backupDescription = ExceptionUtils.unwrapSupply(
BackupNotFoundException.class,
() -> backupsDb.describeBackup(backupUser).join());
return new BackupInfo(
backupDescription.cdn(),
backupUser.backupDir(),
@@ -253,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) {
@@ -315,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) {}
@@ -413,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());
}
@@ -427,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);
@@ -458,11 +468,12 @@ 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 ListMediaResult list(
final AuthenticatedBackupUser backupUser,
final Optional<String> cursor,
final int limit) {
final int limit) throws BackupPermissionException {
checkBackupLevel(backupUser, BackupLevel.FREE);
final RemoteStorageManager.ListResult result =
remoteStorageManager.list(cdnMediaDirectory(backupUser), cursor, limit).toCompletableFuture().join();
@@ -478,7 +489,7 @@ public class BackupManager {
result.cursor());
}
public void deleteEntireBackup(final AuthenticatedBackupUser backupUser) {
public void deleteEntireBackup(final AuthenticatedBackupUser backupUser) throws BackupPermissionException {
checkBackupLevel(backupUser, BackupLevel.FREE);
final int deletionConcurrency =
@@ -504,15 +515,14 @@ public class BackupManager {
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,65 +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 AuthenticatedBackupUser authenticateBackupUser(
final BackupAuthCredentialPresentation presentation,
final byte[] signature,
final String userAgentString) {
return ExceptionUtils.unwrapSupply(
StatusRuntimeException.class,
() -> authenticateBackupUserAsync(presentation, signature, userAgentString).join());
}
final String userAgentString) throws BackupFailedZkAuthenticationException {
/**
* Authenticate the ZK anonymous backup credential's presentation
* <p>
* This validates:
* <li> The presentation was for a credential issued by the server </li>
* <li> The credential is in its redemption window </li>
* <li> The backup-id matches a previously committed blinded backup-id and server issued receipt level </li>
* <li> The signature of the credential matches an existing publicKey associated with this backup-id </li>
*
* @param presentation A {@link BackupAuthCredentialPresentation}
* @param signature An XEd25519 signature of the presentation bytes
* @return A future that completes with the authenticated backup-id and backup-tier encoded in the presentation
*/
public CompletableFuture<AuthenticatedBackupUser> authenticateBackupUserAsync(
final BackupAuthCredentialPresentation presentation,
final byte[] signature,
final String userAgentString) {
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);
}
/**
@@ -754,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;
}
/**
@@ -763,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) {
@@ -771,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)) {
@@ -782,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());
};
@@ -795,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");
}
}
@@ -816,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");
}
}
@@ -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();
}
}
@@ -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);
}
}
@@ -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);
}
}
@@ -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 {
}
@@ -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);
@@ -1,6 +0,0 @@
package org.whispersystems.textsecuregcm.backup;
import java.io.IOException;
public class PublicKeyConflictException extends IOException {
}
@@ -0,0 +1,37 @@
/*
* Copyright 2026 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.configuration;
import java.util.Collections;
import java.util.List;
/// Configure which gRPC methods are enabled
///
/// @param enableAll enable all gRPC methods
/// @param enabledServices A list of fully qualified service names for which all RPCs should be enabled. For example,
/// `org.signal.chat.account.AccountsAnonymous` would enable all RPCs on that service, regardless
/// of whether the RPCs on that service appear in `enabledMethods`
/// @param enabledMethods A list of fully qualified method names of RPCs that should be enabled. For example,
/// `org.signal.chat.account.AccountsAnonymous/LookupUsernameHash` would enable the
/// `LookupUsernameHash` RPC method
public record GrpcAllowListConfiguration(
boolean enableAll,
List<String> enabledServices,
List<String> enabledMethods) {
public GrpcAllowListConfiguration {
if (enabledServices == null) {
enabledServices = Collections.emptyList();
}
if (enabledMethods == null) {
enabledMethods = Collections.emptyList();
}
}
public GrpcAllowListConfiguration() {
// By default, no GRPC methods are accessible
this(false, Collections.emptyList(), Collections.emptyList());
}
}
@@ -5,6 +5,9 @@
package org.whispersystems.textsecuregcm.controllers;
import io.dropwizard.auth.Auth;
import io.micrometer.core.instrument.Metrics;
import io.micrometer.core.instrument.Tag;
import io.micrometer.core.instrument.Tags;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.media.Schema;
@@ -25,6 +28,7 @@ import jakarta.ws.rs.PathParam;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.QueryParam;
import jakarta.ws.rs.WebApplicationException;
import jakarta.ws.rs.core.HttpHeaders;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
import jakarta.ws.rs.core.Response.Status;
@@ -56,6 +60,7 @@ import org.whispersystems.textsecuregcm.identity.IdentityType;
import org.whispersystems.textsecuregcm.identity.ServiceIdentifier;
import org.whispersystems.textsecuregcm.limits.RateLimitedByIp;
import org.whispersystems.textsecuregcm.limits.RateLimiters;
import org.whispersystems.textsecuregcm.metrics.UserAgentTagUtil;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.AccountsManager;
import org.whispersystems.textsecuregcm.storage.Device;
@@ -67,6 +72,8 @@ import org.whispersystems.textsecuregcm.util.HeaderUtils;
import org.whispersystems.textsecuregcm.util.UsernameHashZkProofVerifier;
import org.whispersystems.textsecuregcm.util.Util;
import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
@SuppressWarnings("OptionalUsedAsFieldOrParameterType")
@Path("/v1/accounts")
@io.swagger.v3.oas.annotations.tags.Tag(name = "Account")
@@ -75,6 +82,10 @@ public class AccountController {
public static final int USERNAME_HASH_LENGTH = 32;
public static final int MAXIMUM_USERNAME_CIPHERTEXT_LENGTH = 128;
private static final String RECOVERY_PASSWORD_SET_COUNTER_NAME =
name(AccountController.class, "recoveryPasswordSet");
private final AccountsManager accounts;
private final RateLimiters rateLimiters;
private final RegistrationRecoveryPasswordsManager registrationRecoveryPasswordsManager;
@@ -239,7 +250,8 @@ public class AccountController {
@Produces(MediaType.APPLICATION_JSON)
public void setAccountAttributes(
@Auth AuthenticatedDevice auth,
@HeaderParam(HeaderUtils.X_SIGNAL_AGENT) String userAgent,
@HeaderParam(HttpHeaders.USER_AGENT) String userAgent,
@HeaderParam(HeaderUtils.X_SIGNAL_AGENT) String signalAgent,
@NotNull @Valid AccountAttributes attributes) {
final Account account = accounts.getByAccountIdentifier(auth.accountIdentifier())
.orElseThrow(() -> new WebApplicationException(Status.UNAUTHORIZED));
@@ -250,8 +262,8 @@ public class AccountController {
d.setName(attributes.getName());
d.setLastSeen(Util.todayInMillis());
d.setCapabilities(attributes.getCapabilities());
if (StringUtils.isNotBlank(userAgent)) {
d.setUserAgent(userAgent);
if (StringUtils.isNotBlank(signalAgent)) {
d.setUserAgent(signalAgent);
}
});
@@ -262,8 +274,15 @@ public class AccountController {
});
// if registration recovery password was sent to us, store it (or refresh its expiration)
attributes.recoveryPassword().ifPresent(registrationRecoveryPassword ->
registrationRecoveryPasswordsManager.store(updatedAccount.getIdentifier(IdentityType.PNI), registrationRecoveryPassword));
attributes.recoveryPassword().ifPresent(registrationRecoveryPassword -> {
final boolean rrpCreated = registrationRecoveryPasswordsManager
.store(updatedAccount.getIdentifier(IdentityType.PNI), registrationRecoveryPassword)
.join();
Metrics.counter(RECOVERY_PASSWORD_SET_COUNTER_NAME, Tags.of(
UserAgentTagUtil.getPlatformTag(userAgent),
Tag.of("outcome", rrpCreated ? "created" : "updated")))
.increment();
});
}
@GET
@@ -35,7 +35,6 @@ import jakarta.ws.rs.core.Response;
import java.time.Instant;
import java.util.Optional;
import java.util.UUID;
import javax.annotation.Nullable;
import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
import org.whispersystems.textsecuregcm.auth.ChangesPhoneNumber;
import org.whispersystems.textsecuregcm.auth.PhoneVerificationTokenManager;
@@ -45,7 +44,6 @@ import org.whispersystems.textsecuregcm.entities.AccountIdentityResponse;
import org.whispersystems.textsecuregcm.entities.ChangeNumberRequest;
import org.whispersystems.textsecuregcm.entities.MismatchedDevicesResponse;
import org.whispersystems.textsecuregcm.entities.PhoneNumberDiscoverabilityRequest;
import org.whispersystems.textsecuregcm.entities.PhoneNumberIdentityKeyDistributionRequest;
import org.whispersystems.textsecuregcm.entities.PhoneVerificationRequest;
import org.whispersystems.textsecuregcm.entities.RegistrationLockFailure;
import org.whispersystems.textsecuregcm.entities.StaleDevicesResponse;
@@ -171,35 +169,6 @@ public class AccountControllerV2 {
}
}
// TODO Remove entirely on or after 2025-10-08
@Deprecated(forRemoval = true)
@PUT
@Path("/phone_number_identity_key_distribution")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@Operation(summary = "Set phone-number identity keys",
description = "Updates key material for the phone-number identity for all devices and sends a synchronization message to companion devices")
@ApiResponse(responseCode = "200", description = "Indicates the transaction was successful and returns basic information about this account.", useReturnTypeSchema = true)
@ApiResponse(responseCode = "401", description = "Account authentication check failed.")
@ApiResponse(responseCode = "403", description = "This endpoint can only be invoked from the account's primary device.")
@ApiResponse(responseCode = "422", description = "The request body failed validation.")
public AccountIdentityResponse distributePhoneNumberIdentityKeys(
@Auth final AuthenticatedDevice authenticatedDevice,
@HeaderParam(HttpHeaders.USER_AGENT) @Nullable final String userAgentString,
@NotNull @Valid final PhoneNumberIdentityKeyDistributionRequest request) {
if (authenticatedDevice.deviceId() != Device.PRIMARY_ID) {
throw new ForbiddenException();
}
if (!request.isSignatureValidOnEachSignedPreKey(userAgentString)) {
throw new WebApplicationException("Invalid signature", 422);
}
return AccountIdentityResponseBuilder.fromAccount(accountsManager.getByAccountIdentifier(authenticatedDevice.accountIdentifier())
.orElseThrow(() -> new WebApplicationException(Response.Status.UNAUTHORIZED)));
}
@PUT
@Path("/phone_number_discoverability")
@Consumes(MediaType.APPLICATION_JSON)
@@ -67,8 +67,15 @@ 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;
@@ -150,7 +157,8 @@ public class ArchiveController {
@ManagedAsync
public void setBackupId(
@Auth final AuthenticatedDevice authenticatedDevice,
@Valid @NotNull final SetBackupIdRequest setBackupIdRequest) throws RateLimitExceededException {
@Valid @NotNull final SetBackupIdRequest setBackupIdRequest)
throws RateLimitExceededException, BackupInvalidArgumentException, BackupPermissionException {
final Account account = accountsManager.getByAccountIdentifier(authenticatedDevice.accountIdentifier())
.orElseThrow(() -> new WebApplicationException(Response.Status.UNAUTHORIZED));
@@ -230,14 +238,16 @@ public class ArchiveController {
@ApiResponse(responseCode = "409", description = "The target account does not have a backup-id commitment")
@ApiResponse(responseCode = "429", description = "Rate limited.")
@ManagedAsync
public void redeemReceipt(
public Response redeemReceipt(
@Auth final AuthenticatedDevice authenticatedDevice,
@Valid @NotNull final RedeemBackupReceiptRequest redeemBackupReceiptRequest) {
@Valid @NotNull final RedeemBackupReceiptRequest redeemBackupReceiptRequest)
throws BackupInvalidArgumentException, BackupMissingIdCommitmentException, BackupBadReceiptException {
final Account account = accountsManager.getByAccountIdentifier(authenticatedDevice.accountIdentifier())
.orElseThrow(() -> new WebApplicationException(Response.Status.UNAUTHORIZED));
.orElseThrow(() -> new WebApplicationException(Response.Status.UNAUTHORIZED));
backupAuthManager.redeemReceipt(account, redeemBackupReceiptRequest.receiptCredentialPresentation());
return Response.noContent().build();
}
public record BackupAuthCredentialsResponse(
@@ -300,7 +310,7 @@ public class ArchiveController {
@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 HashMap<>();
@@ -391,6 +401,7 @@ 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
@ManagedAsync
@@ -406,7 +417,8 @@ 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");
}
@@ -436,7 +448,8 @@ 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");
}
@@ -487,7 +500,8 @@ 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");
}
@@ -536,7 +550,8 @@ 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");
}
@@ -578,7 +593,8 @@ 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");
}
@@ -630,7 +646,7 @@ public class ArchiveController {
@Parameter(description = BackupAuthCredentialPresentationSignature.DESCRIPTION, schema = @Schema(implementation = String.class))
@NotNull
@HeaderParam(X_SIGNAL_ZK_AUTH_SIGNATURE) final BackupAuthCredentialPresentationSignature signature)
throws RateLimitExceededException {
throws RateLimitExceededException, BackupFailedZkAuthenticationException, BackupWrongCredentialTypeException, BackupPermissionException {
if (account.isPresent()) {
throw new BadRequestException("must not use authenticated connection for anonymous operations");
}
@@ -723,15 +739,17 @@ 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");
}
final AuthenticatedBackupUser backupUser =
backupManager.authenticateBackupUser(presentation.presentation, signature.signature, userAgent);
final CopyResult copyResult =
backupManager.copyToBackup(backupUser, List.of(copyMediaRequest.toCopyParameters())).next()
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));
@@ -824,7 +842,8 @@ 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");
@@ -832,7 +851,8 @@ public class ArchiveController {
final Stream<CopyParameters> copyParams = copyMediaRequest.items().stream().map(CopyMediaRequest::toCopyParameters);
final AuthenticatedBackupUser backupUser =
backupManager.authenticateBackupUser(presentation.presentation, signature.signature, userAgent);
final List<CopyMediaBatchResponse.Entry> copyResults = backupManager.copyToBackup(backupUser, copyParams.toList())
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().block();
@@ -861,7 +881,8 @@ 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");
}
@@ -934,7 +955,8 @@ 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");
}
@@ -987,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");
}
@@ -1020,7 +1043,8 @@ 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");
}
@@ -29,6 +29,7 @@ import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
import org.whispersystems.textsecuregcm.filters.RemoteAddressFilter;
import org.whispersystems.textsecuregcm.limits.RateLimitedByIp;
import org.whispersystems.textsecuregcm.limits.RateLimiters;
import org.whispersystems.textsecuregcm.metrics.CallQualityInvalidArgumentsException;
import org.whispersystems.textsecuregcm.metrics.CallQualitySurveyManager;
@Path("/v1/call_quality_survey")
@@ -73,7 +74,7 @@ public class CallQualitySurveyController {
try {
callQualitySurveyManager.submitCallQualitySurvey(submitCallQualitySurveyRequest, remoteAddress, userAgentString);
} catch (final IllegalArgumentException e) {
} catch (final CallQualityInvalidArgumentsException e) {
throw new WebApplicationException(e.getMessage(), 422);
}
}
@@ -159,6 +159,9 @@ public class MessageController {
private static final String INCORRECT_SYNC_MESSAGE_REGISTRATION_IDS_COUNTER_NAME =
MetricsUtil.name(MessageController.class, "incorrectSyncMessageRegistrationIds");
private static final String LEGACY_COMBINED_UAK_COUNTER_NAME =
MetricsUtil.name(MessageController.class, "legacyCombinedUak");
// The Signal desktop client (really, JavaScript in general) can handle message timestamps at most 100,000,000 days
// past the epoch; please see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date#the_epoch_timestamps_and_invalid_date
// for additional details.
@@ -584,6 +587,8 @@ public class MessageController {
// Group send endorsements are checked before we even attempt to resolve any accounts, since
// the lists of service IDs in the envelope are all that we need to check against
checkGroupSendToken(multiRecipientMessage.getRecipients().keySet(), groupSendTokenHeader);
} else {
Metrics.counter(LEGACY_COMBINED_UAK_COUNTER_NAME, Tags.of(UserAgentTagUtil.getPlatformTag(context))).increment();
}
// At this point, the caller has at least superficially provided the information needed to send a multi-recipient
@@ -7,22 +7,29 @@ package org.whispersystems.textsecuregcm.controllers;
import com.google.common.annotations.VisibleForTesting;
import io.dropwizard.auth.Auth;
import io.micrometer.core.instrument.DistributionSummary;
import io.micrometer.core.instrument.Metrics;
import io.micrometer.core.instrument.Tag;
import io.micrometer.core.instrument.Tags;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import jakarta.validation.constraints.NotNull;
import jakarta.ws.rs.Consumes;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.HeaderParam;
import jakarta.ws.rs.POST;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.core.HttpHeaders;
import jakarta.ws.rs.core.MediaType;
import java.time.Clock;
import java.time.Duration;
import java.time.Instant;
import java.util.Comparator;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
import org.whispersystems.textsecuregcm.auth.ExternalServiceCredentials;
@@ -33,15 +40,20 @@ import org.whispersystems.textsecuregcm.entities.AuthCheckRequest;
import org.whispersystems.textsecuregcm.entities.AuthCheckResponseV2;
import org.whispersystems.textsecuregcm.limits.RateLimitedByIp;
import org.whispersystems.textsecuregcm.limits.RateLimiters;
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
import org.whispersystems.textsecuregcm.metrics.UserAgentTagUtil;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.AccountsManager;
@Path("/v2/{name: backup|svr}")
@Tag(name = "Secure Value Recovery")
@io.swagger.v3.oas.annotations.tags.Tag(name = "Secure Value Recovery")
@Schema(description = "Note: /v2/backup is deprecated. Use /v2/svr instead.")
public class SecureValueRecovery2Controller {
private static final String CREDENTIAL_AGE_DISTRIBUTION_NAME =
MetricsUtil.name(SecureValueRecovery2Controller.class, "credentialAge");
private static final long MAX_AGE_SECONDS = TimeUnit.DAYS.toSeconds(30);
public static final Duration MAX_AGE = Duration.ofDays(30);
public static ExternalServiceCredentialsGenerator credentialsGenerator(final SecureValueRecoveryConfiguration cfg) {
return credentialsGenerator(cfg, Clock.systemUTC());
@@ -101,11 +113,13 @@ public class SecureValueRecovery2Controller {
@ApiResponse(responseCode = "200", description = "`JSON` with the check results.", useReturnTypeSchema = true)
@ApiResponse(responseCode = "422", description = "Provided list of SVR2 credentials could not be parsed")
@ApiResponse(responseCode = "400", description = "`POST` request body is not a valid `JSON`")
public AuthCheckResponseV2 authCheck(@NotNull @Valid final AuthCheckRequest request) {
public AuthCheckResponseV2 authCheck(
@HeaderParam(HttpHeaders.USER_AGENT) final String userAgent,
@NotNull @Valid final AuthCheckRequest request) {
final List<ExternalServiceCredentialsSelector.CredentialInfo> credentials = ExternalServiceCredentialsSelector.check(
request.tokens(),
backupServiceCredentialGenerator,
MAX_AGE_SECONDS);
MAX_AGE.getSeconds());
// the username associated with the provided number
final Optional<String> matchingUsername = accountsManager
@@ -114,6 +128,22 @@ public class SecureValueRecovery2Controller {
.map(backupServiceCredentialGenerator::generateForUuid)
.map(ExternalServiceCredentials::username);
// Instrument how expired or not the best credential is
credentials.stream()
.filter(info -> switch (info.status()) {
case VALID, EXPIRED -> true;
default -> false;
})
// Look only at credentials that match the current account for the e164
.filter(info -> matchingUsername.filter(info.credentials().username()::equals).isPresent())
// Instrument the matching credential with the most recent timestamp
.max(Comparator.comparing(ExternalServiceCredentialsSelector.CredentialInfo::timestamp))
.ifPresent(info -> DistributionSummary.builder(CREDENTIAL_AGE_DISTRIBUTION_NAME)
.baseUnit("days")
.tags(Tags.of(UserAgentTagUtil.getPlatformTag(userAgent), Tag.of("valid", Boolean.toString(info.valid()))))
.register(Metrics.globalRegistry)
.record(Duration.between(Instant.ofEpochSecond(info.timestamp()), Instant.now()).toDays()));
return new AuthCheckResponseV2(credentials.stream().collect(Collectors.toMap(
ExternalServiceCredentialsSelector.CredentialInfo::token,
info -> {
@@ -50,6 +50,7 @@ import java.security.MessageDigest;
import java.security.SecureRandom;
import java.time.Clock;
import java.time.Duration;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Base64;
import java.util.Collections;
@@ -76,6 +77,7 @@ import org.whispersystems.textsecuregcm.entities.VerificationSessionResponse;
import org.whispersystems.textsecuregcm.filters.RemoteAddressFilter;
import org.whispersystems.textsecuregcm.limits.RateLimiters;
import org.whispersystems.textsecuregcm.mappers.RegistrationServiceSenderExceptionMapper;
import org.whispersystems.textsecuregcm.metrics.DevicePlatformUtil;
import org.whispersystems.textsecuregcm.metrics.UserAgentTagUtil;
import org.whispersystems.textsecuregcm.push.PushNotification;
import org.whispersystems.textsecuregcm.push.PushNotificationManager;
@@ -89,6 +91,7 @@ import org.whispersystems.textsecuregcm.registration.TransportNotAllowedExceptio
import org.whispersystems.textsecuregcm.registration.VerificationSession;
import org.whispersystems.textsecuregcm.spam.RegistrationFraudChecker;
import org.whispersystems.textsecuregcm.spam.RegistrationFraudChecker.VerificationCheck;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.AccountsManager;
import org.whispersystems.textsecuregcm.storage.DynamicConfigurationManager;
import org.whispersystems.textsecuregcm.storage.PhoneNumberIdentifiers;
@@ -101,6 +104,7 @@ import org.whispersystems.textsecuregcm.util.ExceptionUtils;
import org.whispersystems.textsecuregcm.util.ObsoletePhoneNumberFormatException;
import org.whispersystems.textsecuregcm.util.Pair;
import org.whispersystems.textsecuregcm.util.Util;
import org.whispersystems.textsecuregcm.util.ua.ClientPlatform;
@Path("/v1/verification")
@io.swagger.v3.oas.annotations.tags.Tag(name = "Verification")
@@ -123,6 +127,10 @@ public class VerificationController {
private static final String VERIFICATION_TRANSPORT_TAG_NAME = "transport";
private static final String VERIFIED_COUNTER_NAME = name(VerificationController.class, "verified");
private static final String SUCCESS_TAG_NAME = "success";
private static final String RECOVERY_PASSWORD_REMOVED_TAG_NAME = "recoveryPasswordRemoved";
private static final String REREGISTRATION_TAG_NAME = "reregistration";
private static final String EXISTING_ACCOUNT_PLATFORM = "existingAccountPlatform";
private static final String EXISTING_ACCOUNT_RECENTLY_SEEN_TAG_NAME = "existingAccountRecentlySeen";
private final RegistrationServiceClient registrationServiceClient;
private final VerificationSessionManager verificationSessionManager;
@@ -229,7 +237,8 @@ public class VerificationController {
throw new ServerErrorException(Response.Status.INTERNAL_SERVER_ERROR, e);
}
VerificationSession verificationSession = new VerificationSession(null,
VerificationSession verificationSession = new VerificationSession(registrationServiceSession.encodedSessionId(),
null,
maybeCarrierData.orElse(null),
new ArrayList<>(),
Collections.emptyList(),
@@ -245,7 +254,7 @@ public class VerificationController {
// if a push challenge sent in `handlePushToken` doesn't arrive in time
verificationSession.requestedInformation().add(VerificationSession.Information.CAPTCHA);
storeVerificationSession(registrationServiceSession, verificationSession);
storeVerificationSession(verificationSession);
return buildResponse(registrationServiceSession, verificationSession);
}
@@ -318,22 +327,20 @@ public class VerificationController {
} finally {
// Each of the handle* methods may update requestedInformation, submittedInformation, and allowedToRequestCode,
// and we want to be sure to store a changes, even if a later method throws
updateStoredVerificationSession(registrationServiceSession, verificationSession);
updateStoredVerificationSession(verificationSession);
}
return buildResponse(registrationServiceSession, verificationSession);
}
private void storeVerificationSession(final RegistrationServiceSession registrationServiceSession,
final VerificationSession verificationSession) {
verificationSessionManager.insert(registrationServiceSession.encodedSessionId(), verificationSession)
private void storeVerificationSession(final VerificationSession verificationSession) {
verificationSessionManager.insert(verificationSession)
.orTimeout(DYNAMODB_TIMEOUT.toSeconds(), TimeUnit.SECONDS)
.join();
}
private void updateStoredVerificationSession(final RegistrationServiceSession registrationServiceSession,
final VerificationSession verificationSession) {
verificationSessionManager.update(registrationServiceSession.encodedSessionId(), verificationSession)
private void updateStoredVerificationSession(final VerificationSession verificationSession) {
verificationSessionManager.update(verificationSession)
.orTimeout(DYNAMODB_TIMEOUT.toSeconds(), TimeUnit.SECONDS)
.join();
}
@@ -354,7 +361,8 @@ public class VerificationController {
requestedInformation.add(VerificationSession.Information.PUSH_CHALLENGE);
requestedInformation.addAll(verificationSession.requestedInformation());
verificationSession = new VerificationSession(generatePushChallenge(),
verificationSession = new VerificationSession(verificationSession.sessionId(),
generatePushChallenge(),
verificationSession.carrierData(),
requestedInformation,
verificationSession.submittedInformation(),
@@ -428,7 +436,8 @@ public class VerificationController {
|| requestedInformation.remove(VerificationSession.Information.PUSH_CHALLENGE))
&& requestedInformation.isEmpty();
verificationSession = new VerificationSession(verificationSession.pushChallenge(),
verificationSession = new VerificationSession(verificationSession.sessionId(),
verificationSession.pushChallenge(),
verificationSession.carrierData(),
requestedInformation,
submittedInformation,
@@ -501,7 +510,8 @@ public class VerificationController {
|| requestedInformation.remove(VerificationSession.Information.CAPTCHA))
&& requestedInformation.isEmpty();
verificationSession = new VerificationSession(verificationSession.pushChallenge(),
verificationSession = new VerificationSession(verificationSession.sessionId(),
verificationSession.pushChallenge(),
verificationSession.carrierData(),
requestedInformation,
submittedInformation,
@@ -770,16 +780,43 @@ public class VerificationController {
}
}
boolean existingRRP = false;
if (resultSession.verified()) {
registrationRecoveryPasswordsManager.remove(phoneNumberIdentifiers.getPhoneNumberIdentifier(registrationServiceSession.number()).join());
existingRRP = registrationRecoveryPasswordsManager.remove(phoneNumberIdentifiers.getPhoneNumberIdentifier(registrationServiceSession.number()).join()).join();
}
Metrics.counter(VERIFIED_COUNTER_NAME, Tags.of(
UserAgentTagUtil.getPlatformTag(userAgent),
Tag.of(COUNTRY_CODE_TAG_NAME, Util.getCountryCode(registrationServiceSession.number())),
Tag.of(REGION_CODE_TAG_NAME, Util.getRegion(registrationServiceSession.number())),
Tag.of(SUCCESS_TAG_NAME, Boolean.toString(resultSession.verified()))))
.increment();
Optional<Account> maybeExistingAccount;
try {
maybeExistingAccount = accountsManager.getByE164(registrationServiceSession.number());
} catch (RuntimeException e) {
// Only for metrics, so it's ok if we fail to lookup the account
maybeExistingAccount = Optional.empty();
}
Tags tags = Tags.of(
UserAgentTagUtil.getPlatformTag(userAgent),
Tag.of(COUNTRY_CODE_TAG_NAME, Util.getCountryCode(registrationServiceSession.number())),
Tag.of(REGION_CODE_TAG_NAME, Util.getRegion(registrationServiceSession.number())),
Tag.of(SUCCESS_TAG_NAME, Boolean.toString(resultSession.verified())),
Tag.of(RECOVERY_PASSWORD_REMOVED_TAG_NAME, Boolean.toString(existingRRP)),
Tag.of(REREGISTRATION_TAG_NAME, Boolean.toString(maybeExistingAccount.isPresent())));
if (maybeExistingAccount.isPresent()) {
final Account existingAccount = maybeExistingAccount.get();
final Duration timeSinceLastSeen =
Duration.between(Instant.ofEpochMilli(existingAccount.getLastSeen()), clock.instant());
// Clients may reuse recent SVR2 credentials to authenticate via recovery password instead of SMS verification.
// If this is a re-registering account, check if the client could possibly have an unexpired SVR2 credential.
final boolean recentlySeen = timeSinceLastSeen.compareTo(SecureValueRecovery2Controller.MAX_AGE) < 0;
final String existingPlatform = DevicePlatformUtil
.getDevicePlatform(existingAccount.getPrimaryDevice())
.map(ClientPlatform::name).orElse("unknown");
tags = tags
.and(EXISTING_ACCOUNT_PLATFORM, existingPlatform)
.and(EXISTING_ACCOUNT_RECENTLY_SEEN_TAG_NAME, Boolean.toString(recentlySeen));
}
Metrics.counter(VERIFIED_COUNTER_NAME, tags).increment();
return buildResponse(resultSession, verificationSession);
}
@@ -836,7 +873,7 @@ public class VerificationController {
}
/**
* @throws NotFoundException if the session is has no record
* @throws NotFoundException if the session has no record
*/
private VerificationSession retrieveVerificationSession(final RegistrationServiceSession registrationServiceSession) {
@@ -49,6 +49,9 @@ public record IncomingMessageList(@NotNull
@AssertTrue
@Schema(hidden = true)
public boolean isNotDuplicateRecipients() {
if (messages == null) {
return false;
}
final boolean valid = messages.stream()
.filter(Objects::nonNull)
.map(IncomingMessage::destinationDeviceId).distinct().count() == messages.size();
@@ -17,6 +17,7 @@ public record LinkDeviceRequest(@Schema(requiredMode = Schema.RequiredMode.REQUI
@NotBlank
String verificationCode,
@NotNull
@Valid
AccountAttributes accountAttributes,
@@ -44,7 +45,7 @@ public record LinkDeviceRequest(@Schema(requiredMode = Schema.RequiredMode.REQUI
@AssertTrue
@Schema(hidden = true)
public boolean isExactlyOneMessageDeliveryChannel() {
if (accountAttributes.getFetchesMessages()) {
if (accountAttributes != null && accountAttributes.getFetchesMessages()) {
return deviceActivationRequest().apnToken().isEmpty() && deviceActivationRequest().gcmToken().isEmpty();
} else {
return deviceActivationRequest().apnToken().isPresent() ^ deviceActivationRequest().gcmToken().isPresent();
@@ -5,14 +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 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;
@@ -31,14 +30,21 @@ 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.RateLimitExceededException;
@@ -59,45 +65,75 @@ public class BackupsAnonymousGrpcService extends SimpleBackupsAnonymousGrpc.Back
}
@Override
public GetCdnCredentialsResponse getCdnCredentials(final GetCdnCredentialsRequest request) {
final AuthenticatedBackupUser backupUser = authenticateBackupUser(request.getSignedPresentation());
return GetCdnCredentialsResponse.newBuilder()
.putAllHeaders(backupManager.generateReadAuth(backupUser, request.getCdn()))
.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 GetSvrBCredentialsResponse getSvrBCredentials(final GetSvrBCredentialsRequest request) {
final AuthenticatedBackupUser backupUser = authenticateBackupUser(request.getSignedPresentation());
final ExternalServiceCredentials credentials = backupManager.generateSvrbAuth(backupUser);
return 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 GetBackupInfoResponse getBackupInfo(final GetBackupInfoRequest request) {
final AuthenticatedBackupUser backupUser = authenticateBackupUser(request.getSignedPresentation());
final BackupManager.BackupInfo info = backupManager.backupInfo(backupUser);
return 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 RefreshResponse refresh(final RefreshRequest request) {
final AuthenticatedBackupUser backupUser = authenticateBackupUser(request.getSignedPresentation());
backupManager.ttlRefresh(backupUser);
return 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 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,
@@ -110,45 +146,67 @@ public class BackupsAnonymousGrpcService extends SimpleBackupsAnonymousGrpc.Back
@Override
public GetUploadFormResponse getUploadForm(final GetUploadFormRequest request) throws RateLimitExceededException {
final AuthenticatedBackupUser backupUser = authenticateBackupUser(request.getSignedPresentation());
final BackupUploadDescriptor uploadDescriptor = switch (request.getUploadTypeCase()) {
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) {
throw Status.FAILED_PRECONDITION
.withDescription("Exceeds max upload length")
.asRuntimeException();
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();
}
yield backupManager.createMessageBackupUploadDescriptor(backupUser);
}
case MEDIA -> backupManager.createTemporaryAttachmentUploadDescriptor(backupUser);
case UPLOADTYPE_NOT_SET -> throw Status.INVALID_ARGUMENT
.withDescription("Must set upload_type")
.asRuntimeException();
};
return GetUploadFormResponse.newBuilder()
.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();
}
case UPLOADTYPE_NOT_SET -> throw GrpcExceptions.fieldViolation("upload_type", "Must set upload_type");
}
return builder.build();
}
@Override
public Flow.Publisher<CopyMediaResponse> copyMedia(final CopyMediaRequest request) {
final Flux<CopyMediaResponse> flux = Mono
.fromFuture(() -> authenticateBackupUserAsync(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))))
@@ -167,79 +225,107 @@ public class BackupsAnonymousGrpcService extends SimpleBackupsAnonymousGrpc.Back
.setSourceNotFound(CopyMediaResponse.SourceNotFound.getDefaultInstance());
};
return builder.build();
});
return JdkFlowAdapter.publisherToFlowPublisher(flux);
}));
}
@Override
public ListMediaResponse listMedia(final ListMediaRequest request) {
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.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());
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();
}
builder
.setBackupDir(backupUser.backupDir())
.setMediaDir(backupUser.mediaDir());
listResult.cursor().ifPresent(builder::setCursor);
return builder.build();
}
@Override
public DeleteAllResponse deleteAll(final DeleteAllRequest request) {
final AuthenticatedBackupUser backupUser = authenticateBackupUser(request.getSignedPresentation());
backupManager.deleteEntireBackup(backupUser);
return 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 Flow.Publisher<DeleteMediaResponse> deleteMedia(final DeleteMediaRequest request) {
return JdkFlowAdapter.publisherToFlowPublisher(Mono
.fromFuture(() -> authenticateBackupUserAsync(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 CompletableFuture<AuthenticatedBackupUser> authenticateBackupUserAsync(final SignedPresentation 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 AuthenticatedBackupUser authenticateBackupUser(final SignedPresentation signedPresentation)
throws BackupFailedZkAuthenticationException {
if (signedPresentation == null) {
throw Status.UNAUTHENTICATED.asRuntimeException();
throw GrpcExceptions.badAuthentication("Missing required signedPresentation");
}
try {
return backupManager.authenticateBackupUserAsync(
return backupManager.authenticateBackupUser(
new BackupAuthCredentialPresentation(signedPresentation.getPresentation().toByteArray()),
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");
}
}
private AuthenticatedBackupUser authenticateBackupUser(final SignedPresentation signedPresentation) {
return authenticateBackupUserAsync(signedPresentation).join();
}
/**
* Convert an int from a proto uint32 to a signed positive integer, throwing if the value exceeds
* {@link Integer#MAX_VALUE}. To convert to a long, see {@link Integer#toUnsignedLong(int)}
*/
private static int fromUnsignedExact(final int i) {
if (i < 0) {
throw Status.INVALID_ARGUMENT.withDescription("Invalid size").asRuntimeException();
throw GrpcExceptions.invalidArguments("integer length too large");
}
return i;
}
@@ -253,7 +339,7 @@ public class BackupsAnonymousGrpcService extends SimpleBackupsAnonymousGrpc.Back
try {
return deserializer.deserialize(bytes);
} catch (InvalidInputException | InvalidKeyException e) {
throw Status.INVALID_ARGUMENT.withDescription("Invalid serialization").asRuntimeException();
throw GrpcExceptions.invalidArguments("invalid serialization");
}
}
@@ -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;
@@ -20,6 +21,7 @@ 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,6 +30,12 @@ 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;
@@ -48,7 +56,8 @@ public class BackupsGrpcService extends SimpleBackupsGrpc.BackupsImplBase {
}
@Override
public SetBackupIdResponse setBackupId(SetBackupIdRequest request) throws RateLimitExceededException {
public SetBackupIdResponse setBackupId(SetBackupIdRequest request)
throws RateLimitExceededException, BackupInvalidArgumentException, BackupPermissionException {
final Optional<BackupAuthCredentialRequest> messagesCredentialRequest = deserializeWithEmptyPresenceCheck(
BackupAuthCredentialRequest::new,
@@ -67,13 +76,21 @@ public class BackupsGrpcService extends SimpleBackupsGrpc.BackupsImplBase {
return SetBackupIdResponse.getDefaultInstance();
}
public RedeemReceiptResponse redeemReceipt(RedeemReceiptRequest request) {
public RedeemReceiptResponse redeemReceipt(RedeemReceiptRequest request) throws BackupInvalidArgumentException {
final ReceiptCredentialPresentation receiptCredentialPresentation = deserialize(
ReceiptCredentialPresentation::new,
request.getPresentation().toByteArray());
final Account account = authenticatedAccount();
backupAuthManager.redeemReceipt(account, receiptCredentialPresentation);
return RedeemReceiptResponse.getDefaultInstance();
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
@@ -88,34 +105,51 @@ public class BackupsGrpcService extends SimpleBackupsGrpc.BackupsImplBase {
throw Status.INVALID_ARGUMENT.withDescription(e.getMessage()).asRuntimeException();
}
final Account account = authenticatedAccount();
final List<BackupAuthManager.Credential> messageCredentials =
backupAuthManager.getBackupAuthCredentials(
account,
BackupCredentialType.MESSAGES,
redemptionRange);
backupMetrics.updateGetCredentialCounter(platformTag, BackupCredentialType.MESSAGES, messageCredentials.size());
try {
final List<BackupAuthManager.Credential> messageCredentials =
backupAuthManager.getBackupAuthCredentials(
account,
BackupCredentialType.MESSAGES,
redemptionRange);
backupMetrics.updateGetCredentialCounter(platformTag, BackupCredentialType.MESSAGES, messageCredentials.size());
final List<BackupAuthManager.Credential> mediaCredentials =
backupAuthManager.getBackupAuthCredentials(
account,
BackupCredentialType.MEDIA,
redemptionRange);
backupMetrics.updateGetCredentialCounter(platformTag, BackupCredentialType.MEDIA, mediaCredentials.size());
final List<BackupAuthManager.Credential> mediaCredentials =
backupAuthManager.getBackupAuthCredentials(
account,
BackupCredentialType.MEDIA,
redemptionRange);
backupMetrics.updateGetCredentialCounter(platformTag, BackupCredentialType.MEDIA, mediaCredentials.size());
return GetBackupAuthCredentialsResponse.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(mediaCredentials.stream().collect(Collectors.toMap(
c -> c.redemptionTime().getEpochSecond(),
c -> ZkCredential.newBuilder()
.setCredential(ByteString.copyFrom(c.credential().serialize()))
.setRedemptionTime(c.redemptionTime().getEpochSecond())
.build())))
.build();
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(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();
} catch (BackupNotFoundException _) {
// Return an empty response to indicate that the authenticated account had no associated blinded backup-id
return GetBackupAuthCredentialsResponse.getDefaultInstance();
}
}
@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() {
@@ -12,6 +12,7 @@ import org.signal.chat.calling.quality.SubmitCallQualitySurveyRequest;
import org.signal.chat.calling.quality.SubmitCallQualitySurveyResponse;
import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
import org.whispersystems.textsecuregcm.limits.RateLimiters;
import org.whispersystems.textsecuregcm.metrics.CallQualityInvalidArgumentsException;
import org.whispersystems.textsecuregcm.metrics.CallQualitySurveyManager;
public class CallQualitySurveyGrpcService extends SimpleCallQualityGrpc.CallQualityImplBase {
@@ -38,8 +39,10 @@ public class CallQualitySurveyGrpcService extends SimpleCallQualityGrpc.CallQual
callQualitySurveyManager.submitCallQualitySurvey(request,
remoteAddress,
RequestAttributesUtil.getUserAgent().orElse(null));
} catch (final IllegalArgumentException e) {
throw Status.INVALID_ARGUMENT.withDescription(e.getMessage()).asRuntimeException();
} catch (final CallQualityInvalidArgumentsException e) {
throw e.getField()
.map(fieldName -> GrpcExceptions.fieldViolation(fieldName, e.getMessage()))
.orElseGet(() -> GrpcExceptions.invalidArguments(e.getMessage()));
}
return SubmitCallQualitySurveyResponse.getDefaultInstance();
@@ -15,19 +15,16 @@ import java.util.concurrent.TimeUnit;
import org.signal.chat.credentials.AuthCheckResult;
import org.signal.chat.credentials.CheckSvrCredentialsRequest;
import org.signal.chat.credentials.CheckSvrCredentialsResponse;
import org.signal.chat.credentials.ReactorExternalServiceCredentialsAnonymousGrpc;
import org.signal.chat.credentials.SimpleExternalServiceCredentialsAnonymousGrpc;
import org.whispersystems.textsecuregcm.WhisperServerConfiguration;
import org.whispersystems.textsecuregcm.auth.ExternalServiceCredentials;
import org.whispersystems.textsecuregcm.auth.ExternalServiceCredentialsGenerator;
import org.whispersystems.textsecuregcm.auth.ExternalServiceCredentialsSelector;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.AccountsManager;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import reactor.util.function.Tuples;
public class ExternalServiceCredentialsAnonymousGrpcService extends
ReactorExternalServiceCredentialsAnonymousGrpc.ExternalServiceCredentialsAnonymousImplBase {
SimpleExternalServiceCredentialsAnonymousGrpc.ExternalServiceCredentialsAnonymousImplBase {
private static final long MAX_SVR_PASSWORD_AGE_SECONDS = TimeUnit.DAYS.toSeconds(30);
@@ -54,36 +51,34 @@ public class ExternalServiceCredentialsAnonymousGrpcService extends
}
@Override
public Mono<CheckSvrCredentialsResponse> checkSvrCredentials(final CheckSvrCredentialsRequest request) {
public CheckSvrCredentialsResponse checkSvrCredentials(final CheckSvrCredentialsRequest request) {
final List<String> tokens = request.getPasswordsList();
if (tokens.size() > 10) {
throw GrpcExceptions.fieldViolation("passwordsList", "At most 10 passwords may be provided");
}
final List<ExternalServiceCredentialsSelector.CredentialInfo> credentials = ExternalServiceCredentialsSelector.check(
tokens,
svrCredentialsGenerator,
MAX_SVR_PASSWORD_AGE_SECONDS);
return Mono.fromFuture(() -> accountsManager.getByE164Async(request.getNumber()))
// the username associated with the provided number
.map(maybeAccount -> maybeAccount.map(Account::getUuid)
.map(svrCredentialsGenerator::generateForUuid)
.map(ExternalServiceCredentials::username))
.flatMapMany(maybeMatchingUsername -> Flux.fromIterable(credentials)
.map(credential -> Tuples.of(maybeMatchingUsername, credential)))
.reduce(CheckSvrCredentialsResponse.newBuilder(), ((builder, usernameAndCredentialInfo) -> {
final Optional<String> matchingUsername = usernameAndCredentialInfo.getT1();
final ExternalServiceCredentialsSelector.CredentialInfo credentialInfo = usernameAndCredentialInfo.getT2();
final AuthCheckResult authCheckResult;
if (!credentialInfo.valid()) {
authCheckResult = AuthCheckResult.AUTH_CHECK_RESULT_INVALID;
} else {
final String username = credentialInfo.credentials().username();
// does this credential match the account id for the e164 provided in the request?
authCheckResult = matchingUsername.map(username::equals).orElse(false)
? AuthCheckResult.AUTH_CHECK_RESULT_MATCH
: AuthCheckResult.AUTH_CHECK_RESULT_NO_MATCH;
}
return builder.putMatches(credentialInfo.token(), authCheckResult);
}))
.map(CheckSvrCredentialsResponse.Builder::build);
// the username associated with the provided number
final Optional<String> maybeUsername = accountsManager.getByE164(request.getNumber())
.map(Account::getUuid)
.map(svrCredentialsGenerator::generateForUuid)
.map(ExternalServiceCredentials::username);
final CheckSvrCredentialsResponse.Builder builder = CheckSvrCredentialsResponse.newBuilder();
for (ExternalServiceCredentialsSelector.CredentialInfo credentialInfo : credentials) {
final AuthCheckResult authCheckResult;
if (!credentialInfo.valid()) {
authCheckResult = AuthCheckResult.AUTH_CHECK_RESULT_INVALID;
} else {
final String username = credentialInfo.credentials().username();
// does this credential match the account id for the e164 provided in the request?
authCheckResult = maybeUsername.map(username::equals).orElse(false)
? AuthCheckResult.AUTH_CHECK_RESULT_MATCH
: AuthCheckResult.AUTH_CHECK_RESULT_NO_MATCH;
}
builder.putMatches(credentialInfo.token(), authCheckResult);
}
return builder.build();
}
}
@@ -8,22 +8,21 @@ package org.whispersystems.textsecuregcm.grpc;
import static java.util.Objects.requireNonNull;
import com.google.common.annotations.VisibleForTesting;
import io.grpc.Status;
import java.time.Clock;
import java.util.Map;
import org.signal.chat.credentials.ExternalServiceType;
import org.signal.chat.credentials.GetExternalServiceCredentialsRequest;
import org.signal.chat.credentials.GetExternalServiceCredentialsResponse;
import org.signal.chat.credentials.ReactorExternalServiceCredentialsGrpc;
import org.signal.chat.credentials.SimpleExternalServiceCredentialsGrpc;
import org.whispersystems.textsecuregcm.WhisperServerConfiguration;
import org.whispersystems.textsecuregcm.auth.ExternalServiceCredentials;
import org.whispersystems.textsecuregcm.auth.ExternalServiceCredentialsGenerator;
import org.whispersystems.textsecuregcm.auth.grpc.AuthenticatedDevice;
import org.whispersystems.textsecuregcm.auth.grpc.AuthenticationUtil;
import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
import org.whispersystems.textsecuregcm.limits.RateLimiters;
import reactor.core.publisher.Mono;
public class ExternalServiceCredentialsGrpcService extends ReactorExternalServiceCredentialsGrpc.ExternalServiceCredentialsImplBase {
public class ExternalServiceCredentialsGrpcService extends SimpleExternalServiceCredentialsGrpc.ExternalServiceCredentialsImplBase {
private final Map<ExternalServiceType, ExternalServiceCredentialsGenerator> credentialsGeneratorByType;
@@ -48,21 +47,20 @@ public class ExternalServiceCredentialsGrpcService extends ReactorExternalServic
}
@Override
public Mono<GetExternalServiceCredentialsResponse> getExternalServiceCredentials(final GetExternalServiceCredentialsRequest request) {
public GetExternalServiceCredentialsResponse getExternalServiceCredentials(final GetExternalServiceCredentialsRequest request)
throws RateLimitExceededException {
final ExternalServiceCredentialsGenerator credentialsGenerator = this.credentialsGeneratorByType
.get(request.getExternalService());
if (credentialsGenerator == null) {
return Mono.error(Status.INVALID_ARGUMENT.asException());
throw GrpcExceptions.fieldViolation("externalService", "Invalid external service type");
}
final AuthenticatedDevice authenticatedDevice = AuthenticationUtil.requireAuthenticatedDevice();
return rateLimiters.forDescriptor(RateLimiters.For.EXTERNAL_SERVICE_CREDENTIALS).validateReactive(authenticatedDevice.accountIdentifier())
.then(Mono.fromSupplier(() -> {
final ExternalServiceCredentials externalServiceCredentials = credentialsGenerator
.generateForUuid(authenticatedDevice.accountIdentifier());
return GetExternalServiceCredentialsResponse.newBuilder()
.setUsername(externalServiceCredentials.username())
.setPassword(externalServiceCredentials.password())
.build();
}));
rateLimiters.forDescriptor(RateLimiters.For.EXTERNAL_SERVICE_CREDENTIALS).validate(authenticatedDevice.accountIdentifier());
final ExternalServiceCredentials externalServiceCredentials = credentialsGenerator
.generateForUuid(authenticatedDevice.accountIdentifier());
return GetExternalServiceCredentialsResponse.newBuilder()
.setUsername(externalServiceCredentials.username())
.setPassword(externalServiceCredentials.password())
.build();
}
}
@@ -0,0 +1,42 @@
/*
* Copyright 2026 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.grpc;
import io.grpc.Metadata;
import io.grpc.MethodDescriptor;
import io.grpc.ServerCall;
import io.grpc.ServerCallHandler;
import io.grpc.ServerInterceptor;
import io.grpc.Status;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class GrpcAllowListInterceptor implements ServerInterceptor {
private final boolean enableAll;
private final Set<String> enabledServices;
private final Set<String> enabledMethods;
public GrpcAllowListInterceptor(
final boolean enableAll,
final List<String> enabledServices,
final List<String> enabledMethods) {
this.enableAll = enableAll;
this.enabledServices = new HashSet<>(enabledServices);
this.enabledMethods = new HashSet<>(enabledMethods);
}
@Override
public <ReqT, RespT> ServerCall.Listener<ReqT> interceptCall(final ServerCall<ReqT, RespT> serverCall,
final Metadata metadata, final ServerCallHandler<ReqT, RespT> next) {
final MethodDescriptor<ReqT, RespT> methodDescriptor = serverCall.getMethodDescriptor();
if (!enableAll && !enabledServices.contains(methodDescriptor.getServiceName()) && !enabledMethods.contains(methodDescriptor.getFullMethodName())) {
return ServerInterceptorUtil.closeWithStatus(serverCall, Status.UNIMPLEMENTED);
}
return next.startCall(serverCall, metadata);
}
}
@@ -79,6 +79,20 @@ public class GrpcExceptions {
.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.
@@ -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();
}
}
@@ -0,0 +1,25 @@
/*
* Copyright 2026 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.metrics;
import javax.annotation.Nullable;
import java.util.Optional;
public class CallQualityInvalidArgumentsException extends Exception {
private final @Nullable String field;
public CallQualityInvalidArgumentsException(final String message) {
this(message, null);
}
public CallQualityInvalidArgumentsException(final String message, final String field) {
super(message);
this.field = field;
}
public Optional<String> getField() {
return Optional.ofNullable(field);
}
}
@@ -49,7 +49,9 @@ public class CallQualitySurveyManager {
public void submitCallQualitySurvey(final SubmitCallQualitySurveyRequest submitCallQualitySurveyRequest,
final String remoteAddress,
final String userAgentString) {
final String userAgentString) throws CallQualityInvalidArgumentsException {
validateRequest(submitCallQualitySurveyRequest);
final CallQualitySurveyResponsePubSubMessage.Builder pubSubMessageBuilder =
CallQualitySurveyResponsePubSubMessage.newBuilder()
@@ -150,21 +152,21 @@ public class CallQualitySurveyManager {
}
@VisibleForTesting
static void validateRequest(final SubmitCallQualitySurveyRequest request) {
static void validateRequest(final SubmitCallQualitySurveyRequest request) throws CallQualityInvalidArgumentsException {
if (request.getStartTimestamp() == 0) {
throw new IllegalArgumentException("Start timestamp not specified");
throw new CallQualityInvalidArgumentsException("Start timestamp not specified", "startTimestamp");
}
if (request.getEndTimestamp() == 0) {
throw new IllegalArgumentException("End timestamp not specified");
throw new CallQualityInvalidArgumentsException("End timestamp not specified", "endTimestamp");
}
if (StringUtils.isBlank(request.getCallType())) {
throw new IllegalArgumentException("Call type not specified");
throw new CallQualityInvalidArgumentsException("Call type not specified", "callType");
}
if (StringUtils.isBlank(request.getCallEndReason())) {
throw new IllegalArgumentException("Call end reason not specified");
throw new CallQualityInvalidArgumentsException("Call end reason not specified", "callEndReason");
}
}
}
@@ -9,6 +9,8 @@ import io.micrometer.core.instrument.Tag;
import java.util.List;
import java.util.Optional;
import java.util.UUID;
import jakarta.ws.rs.container.ContainerRequestContext;
import jakarta.ws.rs.core.HttpHeaders;
import org.apache.commons.lang3.StringUtils;
import org.whispersystems.textsecuregcm.WhisperServerVersion;
import org.whispersystems.textsecuregcm.storage.ClientReleaseManager;
@@ -32,6 +34,10 @@ public class UserAgentTagUtil {
private UserAgentTagUtil() {
}
public static Tag getPlatformTag(final ContainerRequestContext containerRequestContext) {
return getPlatformTag(containerRequestContext.getHeaderString(HttpHeaders.USER_AGENT));
}
public static Tag getPlatformTag(final String userAgentString) {
if (SERVER_UA.equals(userAgentString)) {
@@ -18,6 +18,7 @@ import org.whispersystems.textsecuregcm.telephony.CarrierData;
* requesting codes from Registration Service, in order to get a verified session to be provided to
* {@link org.whispersystems.textsecuregcm.controllers.RegistrationController}.
*
* @param sessionId the session ID returned by Registration Service
* @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
@@ -36,6 +37,7 @@ import org.whispersystems.textsecuregcm.telephony.CarrierData;
* @see org.whispersystems.textsecuregcm.entities.VerificationSessionResponse
*/
public record VerificationSession(
String sessionId,
@Nullable String pushChallenge,
@Nullable CarrierData carrierData,
List<Information> requestedInformation,
@@ -1253,11 +1253,7 @@ public class Accounts {
.totalSegments(segments)
.build());
// Subscribe to the publisher of responses (i.e. `scanPublisher`) rather than the publisher of items
// (i.e. `scanPublisher.items()`) to work around https://github.com/aws/aws-sdk-java-v2/issues/6411
return Flux.from(scanPublisher)
.flatMap(scanResponse -> Flux.fromIterable(scanResponse.items()))
.map(Accounts::fromItem);
return Flux.from(scanPublisher.items()).map(Accounts::fromItem);
})
.sequential();
}
@@ -109,11 +109,12 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
private static final Timer redisUuidGetTimer = Metrics.timer(name(AccountsManager.class, "redisUuidGet"));
private static final Timer redisDeleteTimer = Metrics.timer(name(AccountsManager.class, "redisDelete"));
private static final String CREATE_COUNTER_NAME = name(AccountsManager.class, "createCounter");
private static final String DELETE_COUNTER_NAME = name(AccountsManager.class, "deleteCounter");
private static final String COUNTRY_CODE_TAG_NAME = "country";
private static final String DELETION_REASON_TAG_NAME = "reason";
private static final String REGISTRATION_ID_BASED_TRANSFER_ARCHIVE_KEY_COUNTER_NAME = name(AccountsManager.class,"registrationIdRedisKeyCounter");
private static final String CREATE_COUNTER_NAME = name(AccountsManager.class, "createCounter");
private static final String DELETE_COUNTER_NAME = name(AccountsManager.class, "deleteCounter");
private static final String COUNTRY_CODE_TAG_NAME = "country";
private static final String DELETION_REASON_TAG_NAME = "reason";
private static final String REGISTRATION_ID_BASED_TRANSFER_ARCHIVE_KEY_COUNTER_NAME =
name(AccountsManager.class, "registrationIdRedisKeyCounter");
private static final String RETRY_NAME = ResilienceUtil.name(AccountsManager.class);
@@ -172,7 +173,6 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
.writer(SystemMapper.excludingField(Account.class, List.of("uuid")));
private static final Duration MESSAGE_POLL_INTERVAL = Duration.ofSeconds(1);
private static final Duration MAX_SERVER_CLOCK_DRIFT = Duration.ofSeconds(5);
// An account that's used at least daily will get reset in the cache at least once per day when its "last seen"
// timestamp updates; expiring entries after two days will help clear out "zombie" cache entries that are read
@@ -421,23 +421,28 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
redisSet(account);
final boolean rrpCreated = accountAttributes.recoveryPassword().map(registrationRecoveryPassword ->
registrationRecoveryPasswordsManager
.store(account.getIdentifier(IdentityType.PNI), registrationRecoveryPassword)
.join())
.orElse(false);
Tags tags = Tags.of(UserAgentTagUtil.getPlatformTag(userAgent),
Tag.of("type", accountCreationType),
Tag.of("hasPushToken", String.valueOf(
primaryDeviceSpec.apnRegistrationId().isPresent() || primaryDeviceSpec.gcmRegistrationId()
.isPresent())),
Tag.of("pushTokenType", pushTokenType));
Tag.of("pushTokenType", pushTokenType),
Tag.of("hasRecoveryPassword", String.valueOf(accountAttributes.recoveryPassword().isPresent())));
if (StringUtils.isNotBlank(previousPushTokenType)) {
tags = tags.and(Tag.of("previousPushTokenType", previousPushTokenType));
}
if (accountAttributes.recoveryPassword().isPresent()) {
tags = tags.and(Tag.of("recoveryPasswordOutcome", rrpCreated ? "created" : "updated"));
}
Metrics.counter(CREATE_COUNTER_NAME, tags).increment();
accountAttributes.recoveryPassword().ifPresent(registrationRecoveryPassword ->
registrationRecoveryPasswordsManager.store(account.getIdentifier(IdentityType.PNI),
registrationRecoveryPassword));
return account;
}
@@ -762,7 +767,7 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
return updateWithRetries(
account,
a -> {
setPniKeys(account, pniIdentityKey, pniRegistrationIds);
setPniKeys(a, pniIdentityKey, pniRegistrationIds);
return true;
},
a -> accounts.changeNumber(a, targetNumber, targetPhoneNumberIdentifier, maybeDisplacedUuid, keyWriteItems),
@@ -1028,7 +1033,7 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
MAX_UPDATE_ATTEMPTS);
})
.thenCompose(updatedAccount -> redisSetAsync(updatedAccount).thenApply(ignored -> updatedAccount))
.whenComplete((ignored, throwable) -> timerSample.stop(updateTimer));
.whenComplete((_, _) -> timerSample.stop(updateTimer));
}
private Account updateWithRetries(Account account,
@@ -1329,7 +1334,7 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
return resolveFromRedis.get()
.thenCompose(maybeAccountFromRedis -> maybeAccountFromRedis
.map(accountFromRedis -> CompletableFuture.completedFuture(maybeAccountFromRedis))
.map(_ -> CompletableFuture.completedFuture(maybeAccountFromRedis))
.orElseGet(() -> resolveFromAccounts.get()
.thenCompose(maybeAccountFromAccounts -> maybeAccountFromAccounts
.map(account -> redisSetAsync(account)
@@ -1339,7 +1344,7 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
}))
.thenApply(ignored -> maybeAccountFromAccounts))
.orElseGet(() -> CompletableFuture.completedFuture(maybeAccountFromAccounts)))))
.whenComplete((ignored, throwable) -> sample.stop(overallTimer));
.whenComplete((_, _) -> sample.stop(overallTimer));
}
private Optional<Account> redisGetBySecondaryKey(final String secondaryKey, final Timer timer) {
@@ -1373,7 +1378,7 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
logger.warn("Failed to retrieve account from Redis", throwable);
return Optional.empty();
})
.whenComplete((ignored, throwable) -> sample.stop(timer))
.whenComplete((_, _) -> sample.stop(timer))
.toCompletableFuture();
}
@@ -1640,7 +1645,7 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
final CompletableFuture<Optional<T>> future = new CompletableFuture<>();
future.completeOnTimeout(Optional.empty(), TimeUnit.MILLISECONDS.convert(timeout), TimeUnit.MILLISECONDS)
.whenComplete((maybeBackup, throwable) -> futureMap.remove(mapKey, future));
.whenComplete((_, _) -> futureMap.remove(mapKey, future));
{
final CompletableFuture<Optional<T>> displacedFuture = futureMap.put(mapKey, future);
@@ -22,6 +22,7 @@ import software.amazon.awssdk.services.dynamodb.model.AttributeValue;
import software.amazon.awssdk.services.dynamodb.model.DeleteItemRequest;
import software.amazon.awssdk.services.dynamodb.model.GetItemRequest;
import software.amazon.awssdk.services.dynamodb.model.PutItemRequest;
import software.amazon.awssdk.services.dynamodb.model.ReturnValue;
public class RegistrationRecoveryPasswords {
@@ -62,26 +63,36 @@ public class RegistrationRecoveryPasswords {
.map(RegistrationRecoveryPasswords::saltedTokenHashFromItem));
}
public CompletableFuture<Void> addOrReplace(final UUID phoneNumberIdentifier, final SaltedTokenHash data) {
/// Add a PNI -> RRP mapping, or replace the current one if it already exists
///
/// @param phoneNumberIdentifier The PNI to associate the salted RRP with
/// @param data The salted registration recovery password
/// @return true if a new mapping was added, false if an existing mapping was updated
public CompletableFuture<Boolean> addOrReplace(final UUID phoneNumberIdentifier, final SaltedTokenHash data) {
final long expirationSeconds = expirationSeconds();
return asyncClient.putItem(PutItemRequest.builder()
.tableName(tableName)
.returnValues(ReturnValue.ALL_OLD)
.item(Map.of(
KEY_PNI, AttributeValues.fromString(phoneNumberIdentifier.toString()),
ATTR_EXP, AttributeValues.fromLong(expirationSeconds),
ATTR_SALT, AttributeValues.fromString(data.salt()),
ATTR_HASH, AttributeValues.fromString(data.hash())))
.build())
.thenRun(Util.NOOP);
.thenApply(response -> response.attributes() == null || response.attributes().isEmpty());
}
public CompletableFuture<Void> removeEntry(final UUID phoneNumberIdentifier) {
/// Remove the entry associated with the provided PNI
///
/// @return true if an entry was removed, false if no entry existed
public CompletableFuture<Boolean> removeEntry(final UUID phoneNumberIdentifier) {
return asyncClient.deleteItem(DeleteItemRequest.builder()
.tableName(tableName)
.returnValues(ReturnValue.ALL_OLD)
.key(Map.of(KEY_PNI, AttributeValues.fromString(phoneNumberIdentifier.toString())))
.build())
.thenRun(Util.NOOP);
.thenApply(response -> response.attributes() != null && !response.attributes().isEmpty());
}
@VisibleForTesting
@@ -30,7 +30,7 @@ public class RegistrationRecoveryPasswordsManager {
public CompletableFuture<Boolean> verify(final UUID phoneNumberIdentifier, final byte[] password) {
return registrationRecoveryPasswords.lookup(phoneNumberIdentifier)
.thenApply(maybeHash -> maybeHash.filter(hash -> hash.verify(bytesToString(password))))
.whenComplete((result, error) -> {
.whenComplete((_, error) -> {
if (error != null) {
logger.warn("Failed to lookup Registration Recovery Password", error);
}
@@ -38,25 +38,22 @@ public class RegistrationRecoveryPasswordsManager {
.thenApply(Optional::isPresent);
}
public CompletableFuture<Void> store(final UUID phoneNumberIdentifier, final byte[] password) {
public CompletableFuture<Boolean> store(final UUID phoneNumberIdentifier, final byte[] password) {
final String token = bytesToString(password);
final SaltedTokenHash tokenHash = SaltedTokenHash.generateFor(token);
return registrationRecoveryPasswords.addOrReplace(phoneNumberIdentifier, tokenHash)
.whenComplete((result, error) -> {
.whenComplete((_, error) -> {
if (error != null) {
logger.warn("Failed to store Registration Recovery Password", error);
}
});
}
public CompletableFuture<Void> remove(final UUID phoneNumberIdentifier) {
public CompletableFuture<Boolean> remove(final UUID phoneNumberIdentifier) {
return registrationRecoveryPasswords.removeEntry(phoneNumberIdentifier)
.whenComplete((ignored, error) -> {
if (error instanceof ResourceNotFoundException) {
// These will naturally happen if a recovery password is already deleted. Since we can remove
// the recovery password through many flows, we avoid creating log messages for these exceptions
} else if (error != null) {
.whenComplete((_, error) -> {
if (error != null) {
logger.warn("Failed to remove Registration Recovery Password", error);
}
});
@@ -17,12 +17,12 @@ public class VerificationSessionManager {
this.verificationSessions = verificationSessions;
}
public CompletableFuture<Void> insert(final String encodedSessionId, final VerificationSession verificationSession) {
return verificationSessions.insert(encodedSessionId, verificationSession);
public CompletableFuture<Void> insert(final VerificationSession verificationSession) {
return verificationSessions.insert(verificationSession.sessionId(), verificationSession);
}
public CompletableFuture<Void> update(final String encodedSessionId, final VerificationSession verificationSession) {
return verificationSessions.update(encodedSessionId, verificationSession);
public CompletableFuture<Void> update(final VerificationSession verificationSession) {
return verificationSessions.update(verificationSession.sessionId(), verificationSession);
}
public CompletableFuture<Optional<VerificationSession>> findForId(final String encodedSessionId) {
@@ -10,12 +10,18 @@ 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) {
/// @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
/// @param isPorted indicates whether the number has been ported from its original network to another network; may be
/// empty if not known
public record CarrierData(String carrierName,
LineType lineType,
Optional<String> mcc,
Optional<String> mnc,
Optional<Boolean> isPorted) {
public enum LineType {
MOBILE,
@@ -20,6 +20,8 @@ import java.util.concurrent.Executor;
import java.util.concurrent.ScheduledExecutorService;
import javax.annotation.Nullable;
import io.micrometer.core.instrument.Metrics;
import io.micrometer.core.instrument.Tag;
import io.micrometer.core.instrument.Tags;
import org.apache.commons.lang3.StringUtils;
import org.whispersystems.textsecuregcm.http.FaultTolerantHttpClient;
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
@@ -42,6 +44,9 @@ public class HlrLookupCarrierDataProvider implements CarrierDataProvider {
private static final ObjectMapper OBJECT_MAPPER = SystemMapper.jsonMapper();
private static final String REQUEST_COUNTER_NAME = MetricsUtil.name(HlrLookupCarrierDataProvider.class, "request");
private static final String RESULT_COUNTER_NAME = MetricsUtil.name(HlrLookupCarrierDataProvider.class, "result");
private static final String CREDITS_SPENT_TAG_NAME = "creditsSpent";
public HlrLookupCarrierDataProvider(final String apiKey,
final String apiSecret,
@@ -126,15 +131,32 @@ public class HlrLookupCarrierDataProvider implements CarrierDataProvider {
final HlrLookupResult result = response.results().getFirst();
if (!result.error().equals("NONE")) {
Metrics.counter(RESULT_COUNTER_NAME, Tags.of(
Tag.of("error", result.error()),
getCreditsSpentTag(result)))
.increment();
throw new CarrierDataException("Received a per-number error: " + result.error());
}
Metrics.counter(RESULT_COUNTER_NAME, Tags.of(getCreditsSpentTag(result)))
.increment();
return getNetworkDetails(result)
.map(networkDetails -> new CarrierData(
networkDetails.name(),
lineType(result.telephoneNumberType()),
mccFromMccMnc(networkDetails.mccmnc()),
mncFromMccMnc(networkDetails.mccmnc())));
mncFromMccMnc(networkDetails.mccmnc()),
isPorted(result.isPorted())));
}
private static Tag getCreditsSpentTag(final HlrLookupResult hlrLookupResult) {
// HLR Lookup's docs at https://www.hlrlookup.com/knowledge/full-api-result suggest:
//
// > Please parse the full float to 1 decimal place to allow for future changes (e.g. service which consumes 1.5 or
// > 0.5 credits).
return Tag.of(CREDITS_SPENT_TAG_NAME, "%.1f".formatted(hlrLookupResult.creditsSpent()));
}
@VisibleForTesting
@@ -153,15 +175,12 @@ public class HlrLookupCarrierDataProvider implements CarrierDataProvider {
@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;
case null -> CarrierData.LineType.UNKNOWN;
default -> CarrierData.LineType.OTHER;
};
}
@@ -177,6 +196,15 @@ public class HlrLookupCarrierDataProvider implements CarrierDataProvider {
return Optional.empty();
}
@VisibleForTesting
static Optional<Boolean> isPorted(@Nullable final String isPorted) {
return switch (isPorted) {
case "YES" -> Optional.of(true);
case "NO" -> Optional.of(false);
case null, default -> Optional.empty();
};
}
@VisibleForTesting
static HlrLookupResponse parseResponse(final String responseJson) throws JsonProcessingException {
return OBJECT_MAPPER.readValue(responseJson, HlrLookupResponse.class);
@@ -10,9 +10,11 @@ import com.fasterxml.jackson.databind.annotation.JsonNaming;
@JsonNaming(PropertyNamingStrategies.SnakeCaseStrategy.class)
record HlrLookupResult(String error,
float creditsSpent,
String originalNetwork,
NetworkDetails originalNetworkDetails,
String currentNetwork,
NetworkDetails currentNetworkDetails,
String telephoneNumberType) {
String telephoneNumberType,
String isPorted) {
}
@@ -7,103 +7,69 @@ 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`.
*/
// 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`).
*/
// 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.
*/
// 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.
*/
// 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.
*/
// 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) {}
}
@@ -111,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;
}
@@ -124,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;
}
@@ -140,9 +102,7 @@ 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;
}
@@ -150,66 +110,46 @@ 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;
/**
* Indicates that, of all of the candidate hashes provided, none were
* available. Callers may generate a new set of hashes and and retry.
*/
// 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 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 {
message ConfirmedUsernameHash {
/**
* The newly-confirmed username hash.
*/
// The newly-confirmed username hash.
bytes username_hash = 1;
/**
* The server-generated username link handle for the newly-confirmed username.
*/
// 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.
*/
// The details of the successfully confirmed username.
ConfirmedUsernameHash confirmed_username_hash = 1;
/**
* The provided hash was not reserved for the account.
*/
// 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.
*/
// The reservation has lapsed and the requested username has been claimed by
// another caller.
UsernameNotAvailable username_not_available = 3;
}
}
@@ -221,30 +161,22 @@ 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 {
oneof response {
/**
* A new link handle for the given username ciphertext.
*/
// A new link handle for the given username ciphertext.
bytes username_link_handle = 1;
/**
* The authenticated account did not have a username set.
*/
// The authenticated account did not have a username set.
errors.FailedPrecondition no_username_set = 2;
}
@@ -257,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;
}
@@ -277,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;
}
@@ -289,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;
}
@@ -299,60 +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 {
oneof response {
/**
* The service identifier associated with the provided username hash.
*/
// The service identifier associated with the provided username hash.
common.ServiceIdentifier service_identifier = 1;
/**
* No account was found for the provided username hash.
*/
// 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 {
oneof response {
/**
* The ciphertext of the username identified by the provided link handle.
*/
// The ciphertext of the username identified by the provided link handle.
bytes username_ciphertext = 1;
/**
* No username was found for the provided link handle.
*/
// 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"];
}
}
@@ -13,11 +13,6 @@ package org.signal.chat.calling.quality;
service CallQuality {
// Submits a call quality survey response.
//
// This RPC may fail with a `RESOURCE_EXHAUSTED` status if a rate limit for
// submitting survey responses has been exceeded, in which case a
// `retry-after` header containing an ISO 8601 duration string will be present
// in the response trailers.
rpc SubmitCallQualitySurvey(SubmitCallQualitySurveyRequest) returns (SubmitCallQualitySurveyResponse) {}
}
@@ -9,38 +9,23 @@ 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.
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;
}
@@ -9,40 +9,20 @@ 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.
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.
rpc CheckSvrCredentials(CheckSvrCredentialsRequest)
returns (CheckSvrCredentialsResponse) {}
}
@@ -56,60 +36,43 @@ 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. Up to 10 credentials
// can be checked.
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;
}
}
@@ -9,20 +9,19 @@ option java_multiple_files = true;
package org.signal.chat.errors;
/**
* Response message that indicates a particular resource was not found.
*/
// 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.
*/
// 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.
*/
// 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;
}
+100 -176
View File
@@ -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;
}
@@ -12,29 +12,27 @@ 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.
*/
// 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;
}
@@ -148,8 +148,10 @@ class ExternalServiceCredentialsGeneratorTest {
final long elapsedSeconds = 10000;
clock.incrementSeconds(elapsedSeconds);
assertEquals(standardGenerator.validateAndGetTimestamp(standardCredentials, elapsedSeconds + 1).orElseThrow(), TIME_SECONDS);
assertTrue(standardGenerator.validateAndGetTimestamp(standardCredentials, elapsedSeconds - 1).isEmpty());
final Long timestamp = standardGenerator.validateAndGetTimestamp(standardCredentials).orElseThrow();
assertFalse(standardGenerator.isCredentialExpired(timestamp, elapsedSeconds + 1));
assertTrue(standardGenerator.isCredentialExpired(timestamp, elapsedSeconds - 1));
}
@Test
@@ -22,6 +22,7 @@ import static org.mockito.Mockito.when;
import jakarta.ws.rs.WebApplicationException;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.function.Consumer;
import java.util.stream.Stream;
import javax.annotation.Nullable;
@@ -94,6 +95,8 @@ class RegistrationLockVerificationManagerTest {
when(account.hasLockedCredentials()).thenReturn(alreadyLocked);
doThrow(new NotPushRegisteredException()).when(pushNotificationManager).sendAttemptLoginNotification(any(), any());
when(registrationRecoveryPasswordsManager.remove(any())).thenReturn(CompletableFuture.completedFuture(true));
final Pair<Class<? extends Exception>, Consumer<Exception>> exceptionType = switch (error) {
case MISMATCH -> {
when(existingRegistrationLock.verify(clientRegistrationLock)).thenReturn(false);
@@ -6,7 +6,6 @@
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;
@@ -21,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;
@@ -107,7 +104,7 @@ public class BackupAuthManagerTest {
}
@Test
void commitBackupId() throws RateLimitExceededException {
void commitBackupId() throws RateLimitExceededException, BackupInvalidArgumentException, BackupPermissionException {
final BackupAuthManager authManager = create();
final Account account = mock(Account.class);
@@ -158,15 +155,13 @@ public class BackupAuthManagerTest {
linkedDevice(),
Optional.of(backupAuthTestUtil.getRequest(messagesBackupKey, aci)),
Optional.of(backupAuthTestUtil.getRequest(mediaBackupKey, aci)));
assertThatExceptionOfType(StatusRuntimeException.class)
.isThrownBy(commit)
.extracting(ex -> ex.getStatus().getCode())
.isEqualTo(Status.Code.PERMISSION_DENIED);
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) {
@@ -196,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();
@@ -217,16 +212,14 @@ public class BackupAuthManagerTest {
final Account account = new MockAccountBuilder().build();
assertThatExceptionOfType(StatusRuntimeException.class)
.isThrownBy(() ->
authManager.getBackupAuthCredentials(account, credentialType, range(Duration.ofDays(1))))
.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) {
@@ -259,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));
@@ -292,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));
@@ -335,7 +328,8 @@ 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()
@@ -358,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)))
.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));
@@ -396,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)))
.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);
}
@@ -410,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)))
.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);
}
@@ -423,10 +410,8 @@ 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))
.extracting(ex -> ex.getStatus().getCode())
.isEqualTo(Status.Code.INVALID_ARGUMENT);
assertThatExceptionOfType(BackupBadReceiptException.class)
.isThrownBy(() -> authManager.redeemReceipt(mock(Account.class), invalid));
verifyNoInteractions(accountsManager);
verifyNoInteractions(redeemedReceiptsManager);
}
@@ -444,10 +429,8 @@ public class BackupAuthManagerTest {
when(redeemedReceiptsManager.put(any(), eq(expirationTime.getEpochSecond()), eq(201L), eq(aci)))
.thenReturn(CompletableFuture.completedFuture(false));
assertThatExceptionOfType(StatusRuntimeException.class)
.isThrownBy(() -> authManager.redeemReceipt(account, receiptPresentation(201, expirationTime)))
.extracting(ex -> ex.getStatus().getCode())
.isEqualTo(Status.Code.INVALID_ARGUMENT);
assertThatExceptionOfType(BackupBadReceiptException.class)
.isThrownBy(() -> authManager.redeemReceipt(account, receiptPresentation(201, expirationTime)));
verifyNoInteractions(accountsManager);
}
@@ -544,10 +527,8 @@ public class BackupAuthManagerTest {
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) {
assertThatExceptionOfType(RateLimitExceededException.class).isThrownBy(commit);
} else {
@@ -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);
try {
return issuer.getBackupAuthCredentials(account, credentialType, redemptionRange);
} catch (BackupNotFoundException e) {
return Assertions.fail("Backup credential request not found even though we set one");
}
}
}
@@ -24,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;
@@ -184,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);
}
@@ -212,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);
}
@@ -224,7 +214,7 @@ 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);
@@ -253,9 +243,8 @@ public class BackupManagerTest {
final AuthenticatedBackupUser backupUser = backupUser(TestRandomUtil.nextBytes(16), BackupCredentialType.MEDIA, backupLevel);
assertThatExceptionOfType(StatusRuntimeException.class)
.isThrownBy(() -> backupManager.createMessageBackupUploadDescriptor(backupUser))
.matches(exception -> exception.getStatus().getCode() == Status.UNAUTHENTICATED.getCode());
assertThatExceptionOfType(BackupWrongCredentialTypeException.class)
.isThrownBy(() -> backupManager.createMessageBackupUploadDescriptor(backupUser));
}
@Test
@@ -270,26 +259,20 @@ public class BackupManagerTest {
@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));
@@ -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));
@@ -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(
@@ -365,14 +345,11 @@ public class BackupManagerTest {
keyPair.getPrivateKey().calculateSignature(presentation.serialize()),
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
assertThatExceptionOfType(StatusRuntimeException.class)
.isThrownBy(() -> backupManager.authenticateBackupUser(presentation, signature, null))
.extracting(StatusRuntimeException::getStatus)
.extracting(Status::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);
@@ -404,18 +378,15 @@ public class BackupManagerTest {
backupManager.setPublicKey(presentation, signature1, keyPair1.getPublicKey());
// shouldn't be able to set a different public key
assertThatExceptionOfType(StatusRuntimeException.class).isThrownBy(() ->
backupManager.setPublicKey(presentation, signature2, keyPair2.getPublicKey()))
.extracting(StatusRuntimeException::getStatus)
.extracting(Status::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());
}
@Test
public void signatureValidation() throws VerificationFailedException {
public void signatureValidation() throws VerificationFailedException, BackupException {
final BackupAuthCredentialPresentation presentation = backupAuthTestUtil.getPresentation(
BackupLevel.FREE, backupKey, aci);
@@ -427,19 +398,14 @@ 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());
// shouldn't be able to authenticate with an invalid signature
assertThatExceptionOfType(StatusRuntimeException.class)
.isThrownBy(() -> backupManager.authenticateBackupUser(presentation, wrongSignature, null))
.extracting(StatusRuntimeException::getStatus)
.extracting(Status::getCode)
.isEqualTo(Status.UNAUTHENTICATED.getCode());
assertThatExceptionOfType(BackupFailedZkAuthenticationException.class)
.isThrownBy(() -> backupManager.authenticateBackupUser(presentation, wrongSignature, null));
// correct signature
final AuthenticatedBackupUser user = backupManager.authenticateBackupUser(presentation, signature, null);
@@ -448,7 +414,7 @@ public class BackupManagerTest {
}
@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)));
@@ -468,15 +434,12 @@ public class BackupManagerTest {
// 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());
@@ -724,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));
@@ -762,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(
@@ -786,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
@@ -797,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);
@@ -849,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<>();
@@ -887,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(
@@ -907,7 +862,7 @@ 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();
@@ -943,7 +898,7 @@ public class BackupManagerTest {
}
@Test
public void listExpiredBackupsByTier() {
public void listExpiredBackupsByTier() throws BackupException {
final byte[] backupId = TestRandomUtil.nextBytes(16);
// refreshed media timestamp at t=5
@@ -971,7 +926,7 @@ 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);
@@ -1005,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());
@@ -1017,7 +970,7 @@ 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);
@@ -1055,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);
@@ -1072,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();
}
}
@@ -802,6 +802,8 @@ class AccountControllerTest {
void testAccountsAttributesUpdateRecoveryPassword() {
final byte[] recoveryPassword = TestRandomUtil.nextBytes(32);
when(registrationRecoveryPasswordsManager.store(any(), any()))
.thenReturn(CompletableFuture.completedFuture(true));
try (final Response response = resources.getJerseyTest()
.target("/v1/accounts/attributes/")
.request()
@@ -17,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;
@@ -34,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;
@@ -68,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;
@@ -97,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())
@@ -165,7 +170,7 @@ public class ArchiveControllerTest {
}
@Test
public void setBackupId() throws RateLimitExceededException {
public void setBackupId() throws RateLimitExceededException, BackupInvalidArgumentException, BackupPermissionException {
final Response response = resources.getJerseyTest()
.target("v1/archives/backupid")
.request()
@@ -183,7 +188,8 @@ public class ArchiveControllerTest {
}
@Test
public void setBackupIdPartial() throws RateLimitExceededException {
public void setBackupIdPartial()
throws RateLimitExceededException, BackupInvalidArgumentException, BackupPermissionException {
final Response response = resources.getJerseyTest()
.target("v1/archives/backupid")
.request()
@@ -302,13 +308,15 @@ public class ArchiveControllerTest {
public static Stream<Arguments> setBackupIdException() {
return Stream.of(
Arguments.of(new RateLimitExceededException(null), 429),
Arguments.of(Status.INVALID_ARGUMENT.withDescription("test").asRuntimeException(), 400)
Arguments.of(new BackupInvalidArgumentException("test"), 400),
Arguments.of(new BackupPermissionException("test"), 403)
);
}
@ParameterizedTest
@MethodSource
public void setBackupIdException(final Exception ex, final int expectedStatus) throws RateLimitExceededException {
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")
@@ -322,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);
@@ -331,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(expectedCredentials));
.thenReturn(expectedCredentials);
}
final ArchiveController.BackupAuthCredentialsResponse credentialResponse = resources.getJerseyTest()
.target("v1/archives/auth")
@@ -385,7 +396,7 @@ 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()))
@@ -405,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(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)));
@@ -449,7 +460,7 @@ public class ArchiveControllerTest {
}
@Test
public void putMediaBatchPartialFailure() throws VerificationFailedException {
public void putMediaBatchPartialFailure() throws VerificationFailedException, BackupException {
final BackupAuthCredentialPresentation presentation = backupAuthTestUtil.getPresentation(
BackupLevel.PAID, messagesBackupKey, aci);
@@ -457,7 +468,7 @@ public class ArchiveControllerTest {
.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),
@@ -508,7 +519,7 @@ 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()))
@@ -541,7 +552,7 @@ 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()))
@@ -576,7 +587,7 @@ 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()))
@@ -612,7 +623,7 @@ 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()))
@@ -641,7 +652,7 @@ public class ArchiveControllerTest {
}
@Test
public void mediaUploadForm() throws VerificationFailedException, RateLimitExceededException {
public void mediaUploadForm() throws VerificationFailedException, BackupException, RateLimitExceededException {
final BackupAuthCredentialPresentation presentation =
backupAuthTestUtil.getPresentation(BackupLevel.PAID, messagesBackupKey, aci);
when(backupManager.authenticateBackupUser(any(), any(), any()))
@@ -671,7 +682,7 @@ 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()))
@@ -689,7 +700,7 @@ 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()))
@@ -706,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()
@@ -728,7 +739,7 @@ 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()))
@@ -743,7 +754,7 @@ 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()))
@@ -30,6 +30,7 @@ import org.junit.jupiter.params.provider.MethodSource;
import org.signal.chat.calling.quality.SubmitCallQualitySurveyRequest;
import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
import org.whispersystems.textsecuregcm.mappers.RateLimitExceededExceptionMapper;
import org.whispersystems.textsecuregcm.metrics.CallQualityInvalidArgumentsException;
import org.whispersystems.textsecuregcm.metrics.CallQualitySurveyManager;
import org.whispersystems.textsecuregcm.tests.util.AuthHelper;
import org.whispersystems.textsecuregcm.util.SystemMapper;
@@ -60,7 +61,7 @@ class CallQualitySurveyControllerTest {
}
@Test
void submitCallQualitySurvey() {
void submitCallQualitySurvey() throws CallQualityInvalidArgumentsException {
final SubmitCallQualitySurveyRequest request = SubmitCallQualitySurveyRequest.getDefaultInstance();
try (final Response response = RESOURCE_EXTENSION.getJerseyTest()
@@ -75,7 +76,7 @@ class CallQualitySurveyControllerTest {
}
@Test
void submitCallQualitySurveyAuthenticated() {
void submitCallQualitySurveyAuthenticated() throws CallQualityInvalidArgumentsException {
final SubmitCallQualitySurveyRequest request = SubmitCallQualitySurveyRequest.getDefaultInstance();
try (final Response response = RESOURCE_EXTENSION.getJerseyTest()
@@ -91,10 +92,10 @@ class CallQualitySurveyControllerTest {
}
@Test
void submitCallQualitySurveyInvalidArgument() {
void submitCallQualitySurveyInvalidArgument() throws CallQualityInvalidArgumentsException {
final SubmitCallQualitySurveyRequest request = SubmitCallQualitySurveyRequest.getDefaultInstance();
doThrow(new IllegalArgumentException())
doThrow(new CallQualityInvalidArgumentsException("test"))
.when(CALL_QUALITY_SURVEY_MANAGER).submitCallQualitySurvey(request, REMOTE_ADDRESS, USER_AGENT);
try (final Response response = RESOURCE_EXTENSION.getJerseyTest()
@@ -791,6 +791,44 @@ class DeviceControllerTest {
);
}
@Test
void linkDeviceNullAccountAttributes() {
when(accountsManager.getByAccountIdentifier(AuthHelper.VALID_UUID)).thenReturn(Optional.of(account));
final Device existingDevice = mock(Device.class);
when(existingDevice.getId()).thenReturn(Device.PRIMARY_ID);
when(account.getDevices()).thenReturn(List.of(existingDevice));
final ECSignedPreKey aciSignedPreKey;
final ECSignedPreKey pniSignedPreKey;
final KEMSignedPreKey aciPqLastResortPreKey;
final KEMSignedPreKey pniPqLastResortPreKey;
final ECKeyPair aciIdentityKeyPair = ECKeyPair.generate();
final ECKeyPair pniIdentityKeyPair = ECKeyPair.generate();
aciSignedPreKey = KeysHelper.signedECPreKey(1, aciIdentityKeyPair);
pniSignedPreKey = KeysHelper.signedECPreKey(2, pniIdentityKeyPair);
aciPqLastResortPreKey = KeysHelper.signedKEMPreKey(3, aciIdentityKeyPair);
pniPqLastResortPreKey = KeysHelper.signedKEMPreKey(4, pniIdentityKeyPair);
when(account.getIdentityKey(IdentityType.ACI)).thenReturn(new IdentityKey(aciIdentityKeyPair.getPublicKey()));
when(account.getIdentityKey(IdentityType.PNI)).thenReturn(new IdentityKey(pniIdentityKeyPair.getPublicKey()));
final LinkDeviceRequest request = new LinkDeviceRequest("link-device-token",
null,
new DeviceActivationRequest(aciSignedPreKey, pniSignedPreKey, aciPqLastResortPreKey, pniPqLastResortPreKey, Optional.empty(), Optional.of(new GcmRegistrationId("gcm-id"))));
try (final Response response = resources.getJerseyTest()
.target("/v1/devices/link")
.request()
.header("Authorization", AuthHelper.getProvisioningAuthHeader(AuthHelper.VALID_NUMBER, "password1"))
.put(Entity.entity(request, MediaType.APPLICATION_JSON_TYPE))) {
assertEquals(422, response.getStatus());
}
}
private static ECSignedPreKey ecSignedPreKeyWithBadSignature(final ECSignedPreKey signedPreKey) {
return new ECSignedPreKey(signedPreKey.keyId(),
signedPreKey.publicKey(),
@@ -231,7 +231,7 @@ class VerificationControllerTest {
CompletableFuture.completedFuture(
new RegistrationServiceSession(SESSION_ID, requestedNumber, false, null, null, null,
SESSION_EXPIRATION_SECONDS)));
when(verificationSessionManager.insert(any(), any()))
when(verificationSessionManager.insert(any()))
.thenReturn(CompletableFuture.completedFuture(null));
final Invocation.Builder request = resources.getJerseyTest()
@@ -272,7 +272,7 @@ class VerificationControllerTest {
CompletableFuture.completedFuture(
new RegistrationServiceSession(SESSION_ID, NUMBER, false, null, null, null,
SESSION_EXPIRATION_SECONDS)));
when(verificationSessionManager.insert(any(), any()))
when(verificationSessionManager.insert(any()))
.thenReturn(CompletableFuture.completedFuture(null));
final Invocation.Builder request = resources.getJerseyTest()
@@ -293,7 +293,7 @@ class VerificationControllerTest {
CompletableFuture.completedFuture(
new RegistrationServiceSession(SESSION_ID, NUMBER, false, null, null, null,
SESSION_EXPIRATION_SECONDS)));
when(verificationSessionManager.insert(any(), any()))
when(verificationSessionManager.insert(any()))
.thenReturn(CompletableFuture.completedFuture(null));
final Invocation.Builder request = resources.getJerseyTest()
@@ -328,7 +328,7 @@ class VerificationControllerTest {
new RegistrationServiceSession(SESSION_ID, NUMBER, false, null, null, null,
SESSION_EXPIRATION_SECONDS)));
when(verificationSessionManager.insert(any(), any()))
when(verificationSessionManager.insert(any()))
.thenReturn(CompletableFuture.completedFuture(null));
when(accountsManager.getByE164(NUMBER))
@@ -393,10 +393,10 @@ class VerificationControllerTest {
when(verificationSessionManager.findForId(any()))
.thenReturn(CompletableFuture.completedFuture(
Optional.of(
new VerificationSession(null, null, List.of(VerificationSession.Information.CAPTCHA), Collections.emptyList(),
new VerificationSession(encodedSessionId, null, null, List.of(VerificationSession.Information.CAPTCHA), Collections.emptyList(),
null, null, false, clock.millis(), clock.millis(), registrationServiceSession.expiration()))));
when(verificationSessionManager.update(any(), any()))
when(verificationSessionManager.update(any()))
.thenReturn(CompletableFuture.completedFuture(null));
final Invocation.Builder request = resources.getJerseyTest()
@@ -408,7 +408,7 @@ class VerificationControllerTest {
final ArgumentCaptor<VerificationSession> verificationSessionArgumentCaptor = ArgumentCaptor.forClass(
VerificationSession.class);
verify(verificationSessionManager).update(any(), verificationSessionArgumentCaptor.capture());
verify(verificationSessionManager).update(verificationSessionArgumentCaptor.capture());
final VerificationSession updatedSession = verificationSessionArgumentCaptor.getValue();
assertEquals(List.of(VerificationSession.Information.PUSH_CHALLENGE, VerificationSession.Information.CAPTCHA),
@@ -437,10 +437,10 @@ class VerificationControllerTest {
registrationServiceSession)));
when(verificationSessionManager.findForId(any()))
.thenReturn(CompletableFuture.completedFuture(
Optional.of(new VerificationSession(null, null, Collections.emptyList(), Collections.emptyList(), null, null, false,
Optional.of(new VerificationSession(encodedSessionId, null, null, Collections.emptyList(), Collections.emptyList(), null, null, false,
clock.millis(), clock.millis(), registrationServiceSession.expiration()))));
when(verificationSessionManager.update(any(), any()))
when(verificationSessionManager.update(any()))
.thenReturn(CompletableFuture.completedFuture(null));
doThrow(RateLimitExceededException.class)
@@ -473,10 +473,10 @@ class VerificationControllerTest {
registrationServiceSession)));
when(verificationSessionManager.findForId(any()))
.thenReturn(CompletableFuture.completedFuture(
Optional.of(new VerificationSession(null, null, Collections.emptyList(), Collections.emptyList(), null, null, false,
Optional.of(new VerificationSession(encodedSessionId, null, null, Collections.emptyList(), Collections.emptyList(), null, null, false,
clock.millis(), clock.millis(), registrationServiceSession.expiration()))));
when(verificationSessionManager.update(any(), any()))
when(verificationSessionManager.update(any()))
.thenReturn(CompletableFuture.completedFuture(null));
doThrow(RateLimitExceededException.class)
@@ -509,10 +509,10 @@ class VerificationControllerTest {
registrationServiceSession)));
when(verificationSessionManager.findForId(any()))
.thenReturn(CompletableFuture.completedFuture(
Optional.of(new VerificationSession("challenge", null, List.of(VerificationSession.Information.PUSH_CHALLENGE),
Optional.of(new VerificationSession(encodedSessionId, "challenge", null, List.of(VerificationSession.Information.PUSH_CHALLENGE),
Collections.emptyList(), null, null, false, clock.millis(), clock.millis(),
registrationServiceSession.expiration()))));
when(verificationSessionManager.update(any(), any()))
when(verificationSessionManager.update(any()))
.thenReturn(CompletableFuture.completedFuture(null));
final Invocation.Builder request = resources.getJerseyTest()
@@ -543,14 +543,14 @@ class VerificationControllerTest {
registrationServiceSession)));
when(verificationSessionManager.findForId(any()))
.thenReturn(CompletableFuture.completedFuture(
Optional.of(new VerificationSession(null, null, List.of(VerificationSession.Information.CAPTCHA),
Optional.of(new VerificationSession(encodedSessionId, null, null, List.of(VerificationSession.Information.CAPTCHA),
Collections.emptyList(), null, null, false, clock.millis(), clock.millis(),
registrationServiceSession.expiration()))));
when(registrationCaptchaManager.assessCaptcha(any(), any(), any(), any()))
.thenReturn(Optional.of(AssessmentResult.invalid()));
when(verificationSessionManager.update(any(), any()))
when(verificationSessionManager.update(any()))
.thenReturn(CompletableFuture.completedFuture(null));
final Invocation.Builder request = resources.getJerseyTest()
@@ -563,7 +563,7 @@ class VerificationControllerTest {
final ArgumentCaptor<VerificationSession> verificationSessionArgumentCaptor = ArgumentCaptor.forClass(
VerificationSession.class);
verify(verificationSessionManager).update(any(), verificationSessionArgumentCaptor.capture());
verify(verificationSessionManager).update(verificationSessionArgumentCaptor.capture());
final VerificationSession updatedSession = verificationSessionArgumentCaptor.getValue();
assertEquals(List.of(VerificationSession.Information.CAPTCHA),
@@ -590,13 +590,14 @@ class VerificationControllerTest {
registrationServiceSession)));
when(verificationSessionManager.findForId(any()))
.thenReturn(CompletableFuture.completedFuture(
Optional.of(new VerificationSession("challenge",
Optional.of(new VerificationSession(encodedSessionId,
"challenge",
null,
List.of(VerificationSession.Information.CAPTCHA),
List.of(VerificationSession.Information.PUSH_CHALLENGE),
null, null, false,
clock.millis(), clock.millis(), registrationServiceSession.expiration()))));
when(verificationSessionManager.update(any(), any()))
when(verificationSessionManager.update(any()))
.thenReturn(CompletableFuture.completedFuture(null));
final Invocation.Builder request = resources.getJerseyTest()
@@ -609,7 +610,7 @@ class VerificationControllerTest {
final ArgumentCaptor<VerificationSession> verificationSessionArgumentCaptor = ArgumentCaptor.forClass(
VerificationSession.class);
verify(verificationSessionManager).update(any(), verificationSessionArgumentCaptor.capture());
verify(verificationSessionManager).update(verificationSessionArgumentCaptor.capture());
final VerificationSession updatedSession = verificationSessionArgumentCaptor.getValue();
assertEquals(List.of(VerificationSession.Information.PUSH_CHALLENGE),
@@ -636,10 +637,10 @@ class VerificationControllerTest {
Optional.of(registrationServiceSession)));
when(verificationSessionManager.findForId(any()))
.thenReturn(CompletableFuture.completedFuture(
Optional.of(new VerificationSession("challenge", null, List.of(), List.of(), null, null, true,
Optional.of(new VerificationSession(encodedSessionId, "challenge", null, List.of(), List.of(), null, null, true,
clock.millis(), clock.millis(), registrationServiceSession.expiration()))));
when(verificationSessionManager.update(any(), any()))
when(verificationSessionManager.update(any()))
.thenReturn(CompletableFuture.completedFuture(null));
final Invocation.Builder request = resources.getJerseyTest()
@@ -672,12 +673,13 @@ class VerificationControllerTest {
registrationServiceSession)));
when(verificationSessionManager.findForId(any()))
.thenReturn(CompletableFuture.completedFuture(
Optional.of(new VerificationSession("challenge",
Optional.of(new VerificationSession(encodedSessionId,
"challenge",
null,
List.of(VerificationSession.Information.PUSH_CHALLENGE, VerificationSession.Information.CAPTCHA),
Collections.emptyList(), null, null, false, clock.millis(), clock.millis(),
registrationServiceSession.expiration()))));
when(verificationSessionManager.update(any(), any()))
when(verificationSessionManager.update(any()))
.thenReturn(CompletableFuture.completedFuture(null));
final Invocation.Builder request = resources.getJerseyTest()
@@ -690,7 +692,7 @@ class VerificationControllerTest {
final ArgumentCaptor<VerificationSession> verificationSessionArgumentCaptor = ArgumentCaptor.forClass(
VerificationSession.class);
verify(verificationSessionManager).update(any(), verificationSessionArgumentCaptor.capture());
verify(verificationSessionManager).update(verificationSessionArgumentCaptor.capture());
final VerificationSession updatedSession = verificationSessionArgumentCaptor.getValue();
assertEquals(List.of(VerificationSession.Information.PUSH_CHALLENGE),
@@ -717,14 +719,14 @@ class VerificationControllerTest {
registrationServiceSession)));
when(verificationSessionManager.findForId(any()))
.thenReturn(CompletableFuture.completedFuture(
Optional.of(new VerificationSession(null, null, List.of(VerificationSession.Information.CAPTCHA),
Optional.of(new VerificationSession(encodedSessionId, null, null, List.of(VerificationSession.Information.CAPTCHA),
Collections.emptyList(), null, null, false, clock.millis(), clock.millis(),
registrationServiceSession.expiration()))));
when(registrationCaptchaManager.assessCaptcha(any(), any(), any(), any()))
.thenReturn(Optional.of(AssessmentResult.alwaysValid()));
when(verificationSessionManager.update(any(), any()))
when(verificationSessionManager.update(any()))
.thenReturn(CompletableFuture.completedFuture(null));
final Invocation.Builder request = resources.getJerseyTest()
@@ -737,7 +739,7 @@ class VerificationControllerTest {
final ArgumentCaptor<VerificationSession> verificationSessionArgumentCaptor = ArgumentCaptor.forClass(
VerificationSession.class);
verify(verificationSessionManager).update(any(), verificationSessionArgumentCaptor.capture());
verify(verificationSessionManager).update(verificationSessionArgumentCaptor.capture());
final VerificationSession updatedSession = verificationSessionArgumentCaptor.getValue();
assertEquals(List.of(VerificationSession.Information.CAPTCHA),
@@ -764,7 +766,8 @@ class VerificationControllerTest {
registrationServiceSession)));
when(verificationSessionManager.findForId(any()))
.thenReturn(CompletableFuture.completedFuture(
Optional.of(new VerificationSession("challenge",
Optional.of(new VerificationSession(encodedSessionId,
"challenge",
null,
List.of(VerificationSession.Information.CAPTCHA, VerificationSession.Information.CAPTCHA),
Collections.emptyList(), null, null, false, clock.millis(), clock.millis(),
@@ -773,7 +776,7 @@ class VerificationControllerTest {
when(registrationCaptchaManager.assessCaptcha(any(), any(), any(), any()))
.thenReturn(Optional.of(AssessmentResult.alwaysValid()));
when(verificationSessionManager.update(any(), any()))
when(verificationSessionManager.update(any()))
.thenReturn(CompletableFuture.completedFuture(null));
final Invocation.Builder request = resources.getJerseyTest()
@@ -787,7 +790,7 @@ class VerificationControllerTest {
final ArgumentCaptor<VerificationSession> verificationSessionArgumentCaptor = ArgumentCaptor.forClass(
VerificationSession.class);
verify(verificationSessionManager).update(any(), verificationSessionArgumentCaptor.capture());
verify(verificationSessionManager).update(verificationSessionArgumentCaptor.capture());
final VerificationSession updatedSession = verificationSessionArgumentCaptor.getValue();
assertEquals(List.of(VerificationSession.Information.PUSH_CHALLENGE, VerificationSession.Information.CAPTCHA),
@@ -812,7 +815,8 @@ class VerificationControllerTest {
.thenReturn(CompletableFuture.completedFuture(Optional.of(registrationServiceSession)));
when(verificationSessionManager.findForId(any()))
.thenReturn(CompletableFuture.completedFuture(
Optional.of(new VerificationSession(null,
Optional.of(new VerificationSession(encodedSessionId,
null,
null,
List.of(VerificationSession.Information.CAPTCHA),
Collections.emptyList(), null, null, false, clock.millis(), clock.millis(),
@@ -821,7 +825,7 @@ class VerificationControllerTest {
when(registrationCaptchaManager.assessCaptcha(any(), any(), any(), any()))
.thenThrow(new IOException("expected service error"));
when(verificationSessionManager.update(any(), any()))
when(verificationSessionManager.update(any()))
.thenReturn(CompletableFuture.completedFuture(null));
final Invocation.Builder request = resources.getJerseyTest()
@@ -835,7 +839,7 @@ class VerificationControllerTest {
final ArgumentCaptor<VerificationSession> verificationSessionArgumentCaptor = ArgumentCaptor.forClass(
VerificationSession.class);
verify(verificationSessionManager).update(any(), verificationSessionArgumentCaptor.capture());
verify(verificationSessionManager).update(verificationSessionArgumentCaptor.capture());
final VerificationSession updatedSession = verificationSessionArgumentCaptor.getValue();
assertTrue(updatedSession.submittedInformation().isEmpty());
@@ -970,7 +974,7 @@ class VerificationControllerTest {
.thenReturn(CompletableFuture.completedFuture(Optional.of(registrationServiceSession)));
when(verificationSessionManager.findForId(any()))
.thenReturn(CompletableFuture.completedFuture(
Optional.of(new VerificationSession(null, null, Collections.emptyList(), Collections.emptyList(), null, null, true,
Optional.of(new VerificationSession(encodedSessionId, 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));
@@ -1000,7 +1004,7 @@ class VerificationControllerTest {
Optional.of(
registrationServiceSession)));
when(verificationSessionManager.findForId(any()))
.thenReturn(CompletableFuture.completedFuture(Optional.of(new VerificationSession(null, null,
.thenReturn(CompletableFuture.completedFuture(Optional.of(new VerificationSession(encodedSessionId, null, null,
List.of(VerificationSession.Information.CAPTCHA), Collections.emptyList(), null, null, false, clock.millis(), clock.millis(),
registrationServiceSession.expiration()))));
@@ -1032,7 +1036,7 @@ class VerificationControllerTest {
registrationServiceSession)));
when(verificationSessionManager.findForId(any()))
.thenReturn(CompletableFuture.completedFuture(
Optional.of(new VerificationSession(null, null, Collections.emptyList(), Collections.emptyList(), null, null, false,
Optional.of(new VerificationSession(encodedSessionId, null, null, Collections.emptyList(), Collections.emptyList(), null, null, false,
clock.millis(), clock.millis(), registrationServiceSession.expiration()))));
final Invocation.Builder request = resources.getJerseyTest()
@@ -1060,7 +1064,7 @@ class VerificationControllerTest {
.thenReturn(CompletableFuture.completedFuture(Optional.of(registrationServiceSession)));
when(verificationSessionManager.findForId(any()))
.thenReturn(CompletableFuture.completedFuture(
Optional.of(new VerificationSession(null, null, Collections.emptyList(), Collections.emptyList(), null, null, true,
Optional.of(new VerificationSession(encodedSessionId, 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(
@@ -1092,7 +1096,7 @@ class VerificationControllerTest {
.thenReturn(CompletableFuture.completedFuture(Optional.of(registrationServiceSession)));
when(verificationSessionManager.findForId(any()))
.thenReturn(CompletableFuture.completedFuture(
Optional.of(new VerificationSession(null, null, Collections.emptyList(), Collections.emptyList(), null, null, true,
Optional.of(new VerificationSession(encodedSessionId, 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(
@@ -1124,7 +1128,7 @@ class VerificationControllerTest {
.thenReturn(CompletableFuture.completedFuture(Optional.of(registrationServiceSession)));
when(verificationSessionManager.findForId(any()))
.thenReturn(CompletableFuture.completedFuture(
Optional.of(new VerificationSession(null, null, Collections.emptyList(), Collections.emptyList(), null, null, true,
Optional.of(new VerificationSession(encodedSessionId, 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));
@@ -1157,7 +1161,7 @@ class VerificationControllerTest {
Optional.of(registrationServiceSession)));
when(verificationSessionManager.findForId(any()))
.thenReturn(CompletableFuture.completedFuture(
Optional.of(new VerificationSession(null, null, Collections.emptyList(), Collections.emptyList(), null, null, true,
Optional.of(new VerificationSession(encodedSessionId, null, null, Collections.emptyList(), Collections.emptyList(), null, null, true,
clock.millis(), clock.millis(), registrationServiceSession.expiration()))));
when(registrationServiceClient.sendVerificationCode(any(), any(), any(), any(), any(), any()))
@@ -1201,7 +1205,7 @@ class VerificationControllerTest {
.thenReturn(CompletableFuture.completedFuture(Optional.of(registrationServiceSession)));
when(verificationSessionManager.findForId(any()))
.thenReturn(CompletableFuture.completedFuture(
Optional.of(new VerificationSession(null, null, Collections.emptyList(), Collections.emptyList(), null, null, true,
Optional.of(new VerificationSession(encodedSessionId, null, null, Collections.emptyList(), Collections.emptyList(), null, null, true,
clock.millis(), clock.millis(), registrationServiceSession.expiration()))));
when(registrationServiceClient.sendVerificationCode(any(), any(), any(), any(), any(), any()))
@@ -1235,7 +1239,7 @@ class VerificationControllerTest {
Optional.of(registrationServiceSession)));
when(verificationSessionManager.findForId(any()))
.thenReturn(CompletableFuture.completedFuture(
Optional.of(new VerificationSession(null, null, Collections.emptyList(), Collections.emptyList(), null, null, true,
Optional.of(new VerificationSession(encodedSessionId, null, null, Collections.emptyList(), Collections.emptyList(), null, null, true,
clock.millis(), clock.millis(), registrationServiceSession.expiration()))));
when(registrationServiceClient.checkVerificationCode(any(), any(), any()))
@@ -1262,7 +1266,7 @@ class VerificationControllerTest {
Optional.of(registrationServiceSession)));
when(verificationSessionManager.findForId(any()))
.thenReturn(CompletableFuture.completedFuture(
Optional.of(new VerificationSession(null, null, Collections.emptyList(), Collections.emptyList(), null, null, true,
Optional.of(new VerificationSession(encodedSessionId, null, null, Collections.emptyList(), Collections.emptyList(), null, null, true,
clock.millis(), clock.millis(), registrationServiceSession.expiration()))));
final Invocation.Builder request = resources.getJerseyTest()
@@ -1297,7 +1301,7 @@ class VerificationControllerTest {
Optional.of(registrationServiceSession)));
when(verificationSessionManager.findForId(any()))
.thenReturn(CompletableFuture.completedFuture(
Optional.of(new VerificationSession(null, null, Collections.emptyList(), Collections.emptyList(), null, null, true,
Optional.of(new VerificationSession(encodedSessionId, 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
@@ -1334,7 +1338,7 @@ class VerificationControllerTest {
Optional.of(registrationServiceSession)));
when(verificationSessionManager.findForId(any()))
.thenReturn(CompletableFuture.completedFuture(
Optional.of(new VerificationSession(null, null, Collections.emptyList(), Collections.emptyList(), null, null, true,
Optional.of(new VerificationSession(encodedSessionId, null, null, Collections.emptyList(), Collections.emptyList(), null, null, true,
clock.millis(), clock.millis(), registrationServiceSession.expiration()))));
when(registrationServiceClient.checkVerificationCode(any(), any(), any()))
@@ -1360,7 +1364,7 @@ class VerificationControllerTest {
Optional.of(registrationServiceSession)));
when(verificationSessionManager.findForId(any()))
.thenReturn(CompletableFuture.completedFuture(
Optional.of(new VerificationSession(null, null, Collections.emptyList(), Collections.emptyList(), null, null, true,
Optional.of(new VerificationSession(encodedSessionId, null, null, Collections.emptyList(), Collections.emptyList(), null, null, true,
clock.millis(), clock.millis(), registrationServiceSession.expiration()))));
when(registrationServiceClient.checkVerificationCode(any(), any(), any()))
.thenReturn(CompletableFuture.failedFuture(
@@ -1392,8 +1396,10 @@ class VerificationControllerTest {
Optional.of(registrationServiceSession)));
when(verificationSessionManager.findForId(any()))
.thenReturn(CompletableFuture.completedFuture(
Optional.of(new VerificationSession(null, null, Collections.emptyList(), Collections.emptyList(), null, null, true,
Optional.of(new VerificationSession(encodedSessionId, null, null, Collections.emptyList(), Collections.emptyList(), null, null, true,
clock.millis(), clock.millis(), registrationServiceSession.expiration()))));
when(registrationRecoveryPasswordsManager.remove(any()))
.thenReturn(CompletableFuture.completedFuture(true));
final RegistrationServiceSession verifiedSession = new RegistrationServiceSession(SESSION_ID, NUMBER, true, null,
null, 0L,
@@ -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;
@@ -19,19 +18,16 @@ 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;
@@ -62,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;
@@ -90,9 +87,12 @@ class BackupsAnonymousGrpcServiceTest extends
@BeforeEach
void setup() {
when(backupManager.authenticateBackupUserAsync(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
@@ -129,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)));
@@ -174,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],
@@ -211,17 +211,17 @@ class BackupsAnonymousGrpcServiceTest extends
}
@Test
void getBackupInfo() {
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);
}
@@ -229,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();
@@ -250,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 ->
@@ -278,7 +279,7 @@ class BackupsAnonymousGrpcServiceTest extends
}
@Test
void mediaUploadForm() throws RateLimitExceededException {
void mediaUploadForm() throws RateLimitExceededException, BackupException {
when(backupManager.createTemporaryAttachmentUploadDescriptor(any()))
.thenReturn(new BackupUploadDescriptor(3, "abc", Map.of("k", "v"), "example.org"));
final GetUploadFormRequest request = GetUploadFormRequest.newBuilder()
@@ -287,10 +288,10 @@ class BackupsAnonymousGrpcServiceTest extends
.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);
@@ -309,7 +310,7 @@ 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(new BackupUploadDescriptor(3, "abc", Map.of("k", "v"), "example.org"));
final GetUploadFormRequest.MessagesUploadType.Builder builder = GetUploadFormRequest.MessagesUploadType.newBuilder();
@@ -318,24 +319,20 @@ class BackupsAnonymousGrpcServiceTest extends
.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(
@@ -343,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,
@@ -36,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;
@@ -54,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;
@@ -61,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> {
@@ -98,7 +106,7 @@ class BackupsGrpcServiceTest extends SimpleBaseGrpcTest<BackupsGrpcService, Back
@Test
void setBackupId() throws RateLimitExceededException {
void setBackupId() throws RateLimitExceededException, BackupInvalidArgumentException, BackupPermissionException {
authenticatedServiceStub().setBackupId(
SetBackupIdRequest.newBuilder()
.setMediaBackupAuthCredentialRequest(ByteString.copyFrom(mediaAuthCredRequest.serialize()))
@@ -111,7 +119,8 @@ class BackupsGrpcServiceTest extends SimpleBaseGrpcTest<BackupsGrpcService, Back
@ParameterizedTest
@ValueSource(booleans = {false, true})
void setBackupIdPartial(boolean media) throws RateLimitExceededException {
void setBackupIdPartial(boolean media)
throws RateLimitExceededException, BackupInvalidArgumentException, BackupPermissionException {
final SetBackupIdRequest.Builder builder = SetBackupIdRequest.newBuilder();
if (media) {
builder.setMediaBackupAuthCredentialRequest(ByteString.copyFrom(mediaAuthCredRequest.serialize()));
@@ -141,15 +150,14 @@ class BackupsGrpcServiceTest extends SimpleBaseGrpcTest<BackupsGrpcService, Back
public static Stream<Arguments> setBackupIdException() {
return Stream.of(
Arguments.of(new RateLimitExceededException(null), Status.RESOURCE_EXHAUSTED),
Arguments.of(Status.INVALID_ARGUMENT.withDescription("test").asRuntimeException(),
Status.INVALID_ARGUMENT)
);
Arguments.of(new BackupPermissionException("test"), Status.INVALID_ARGUMENT),
Arguments.of(new BackupInvalidArgumentException("test"), Status.INVALID_ARGUMENT));
}
@ParameterizedTest
@MethodSource
void setBackupIdException(final Exception ex, final Status expected)
throws RateLimitExceededException {
throws RateLimitExceededException, BackupInvalidArgumentException, BackupPermissionException {
doThrow(ex).when(backupAuthManager).commitBackupId(any(), any(), any(), any());
GrpcTestUtils.assertStatusException(
@@ -160,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());
@@ -171,16 +189,22 @@ class BackupsGrpcServiceTest extends SimpleBaseGrpcTest<BackupsGrpcService, Back
final ReceiptCredential receiptCredential = clientOps.receiveReceiptCredential(rcrc, rcr);
final ReceiptCredentialPresentation presentation = clientOps.createReceiptCredentialPresentation(receiptCredential);
authenticatedServiceStub().redeemReceipt(RedeemReceiptRequest.newBuilder()
.setPresentation(ByteString.copyFrom(presentation.serialize()))
.build());
if (exception != null) {
doThrow(exception).when(backupAuthManager).redeemReceipt(any(), any());
}
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);
@@ -190,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(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()
@@ -202,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());
@@ -22,6 +22,7 @@ import org.signal.chat.calling.quality.SubmitCallQualitySurveyRequest;
import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
import org.whispersystems.textsecuregcm.limits.RateLimiter;
import org.whispersystems.textsecuregcm.limits.RateLimiters;
import org.whispersystems.textsecuregcm.metrics.CallQualityInvalidArgumentsException;
import org.whispersystems.textsecuregcm.metrics.CallQualitySurveyManager;
class CallQualitySurveyGrpcServiceTest extends SimpleBaseGrpcTest<CallQualitySurveyGrpcService, CallQualityGrpc.CallQualityBlockingStub> {
@@ -50,7 +51,7 @@ class CallQualitySurveyGrpcServiceTest extends SimpleBaseGrpcTest<CallQualitySur
}
@Test
void submitCallQualitySurvey() {
void submitCallQualitySurvey() throws CallQualityInvalidArgumentsException {
final SubmitCallQualitySurveyRequest request = SubmitCallQualitySurveyRequest.getDefaultInstance();
assertDoesNotThrow(() -> unauthenticatedServiceStub().submitCallQualitySurvey(request));
@@ -70,10 +71,10 @@ class CallQualitySurveyGrpcServiceTest extends SimpleBaseGrpcTest<CallQualitySur
}
@Test
void submitCallQualitySurveyInvalidArgument() {
void submitCallQualitySurveyInvalidArgument() throws CallQualityInvalidArgumentsException {
final SubmitCallQualitySurveyRequest request = SubmitCallQualitySurveyRequest.getDefaultInstance();
doThrow(new IllegalArgumentException())
doThrow(new CallQualityInvalidArgumentsException("test"))
.when(callQualitySurveyManager).submitCallQualitySurvey(request, REMOTE_ADDRESS, USER_AGENT);
//noinspection ResultOfMethodCallIgnored
@@ -6,13 +6,16 @@
package org.whispersystems.textsecuregcm.grpc;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import com.google.i18n.phonenumbers.PhoneNumberUtil;
import io.grpc.Status;
import io.grpc.StatusRuntimeException;
import java.time.Duration;
import java.util.Map;
import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.stream.IntStream;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.Mock;
@@ -59,8 +62,7 @@ class ExternalServiceCredentialsAnonymousGrpcServiceTest extends
@BeforeEach
public void setup() {
Mockito.when(accountsManager.getByE164Async(USER_E164))
.thenReturn(CompletableFuture.completedFuture(Optional.of(account(USER_UUID))));
Mockito.when(accountsManager.getByE164(USER_E164)).thenReturn(Optional.of(account(USER_UUID)));
}
@Test
@@ -125,6 +127,17 @@ class ExternalServiceCredentialsAnonymousGrpcServiceTest extends
), day(25));
}
@Test
public void testTooManyPasswords() {
final CheckSvrCredentialsRequest request = CheckSvrCredentialsRequest.newBuilder()
.setNumber(USER_E164)
.addAllPasswords(IntStream.range(0, 12).mapToObj(i -> token(UUID.randomUUID(), day(10))).toList())
.build();
final StatusRuntimeException status = assertThrows(StatusRuntimeException.class,
() -> unauthenticatedServiceStub().checkSvrCredentials(request));
assertEquals(Status.INVALID_ARGUMENT.getCode(), status.getStatus().getCode());
}
private void assertExpectedCredentialCheckResponse(
final Map<String, AuthCheckResult> expected,
final long nowMillis) throws Exception {
@@ -0,0 +1,111 @@
/*
* Copyright 2026 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.grpc;
import static org.assertj.core.api.Assertions.assertThat;
import com.google.protobuf.ByteString;
import io.grpc.ManagedChannel;
import io.grpc.Server;
import io.grpc.Status;
import io.grpc.inprocess.InProcessChannelBuilder;
import io.grpc.inprocess.InProcessServerBuilder;
import java.io.IOException;
import java.util.Collections;
import java.util.List;
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;
class GrpcAllowListInterceptorTest {
private Server server;
private ManagedChannel channel;
@BeforeEach
void setUp() {
channel = InProcessChannelBuilder.forName("GrpcAllowListInterceptorTest")
.directExecutor()
.build();
}
@AfterEach
void tearDown() throws Exception {
server.shutdownNow();
channel.shutdownNow();
server.awaitTermination(1, TimeUnit.SECONDS);
channel.awaitTermination(1, TimeUnit.SECONDS);
}
@Test
public void disableAll() throws Exception {
final EchoServiceGrpc.EchoServiceBlockingStub client =
setup(false, Collections.emptyList(), Collections.emptyList());
GrpcTestUtils.assertStatusException(Status.UNIMPLEMENTED, () ->
client.echo(EchoRequest.newBuilder().setPayload(ByteString.empty()).build()));
}
@Test
public void enableAll() throws Exception {
final EchoServiceGrpc.EchoServiceBlockingStub client =
setup(true, Collections.emptyList(), Collections.emptyList());
final EchoResponse echo = client.echo(EchoRequest.newBuilder().setPayload(ByteString.empty()).build());
assertThat(echo.getPayload()).isEqualTo(ByteString.empty());
}
@Test
public void enableByMethod() throws Exception {
final EchoServiceGrpc.EchoServiceBlockingStub client =
setup(false, Collections.emptyList(), List.of("org.signal.chat.rpc.EchoService/echo"));
final EchoResponse echo = client.echo(EchoRequest.newBuilder().setPayload(ByteString.empty()).build());
assertThat(echo.getPayload()).isEqualTo(ByteString.empty());
GrpcTestUtils.assertStatusException(Status.UNIMPLEMENTED, () ->
client.echo2(EchoRequest.newBuilder().setPayload(ByteString.empty()).build()));
}
@Test
public void enableByService() throws Exception {
final EchoServiceGrpc.EchoServiceBlockingStub client =
setup(false, List.of("org.signal.chat.rpc.EchoService"), Collections.emptyList());
final EchoResponse echo = client.echo(EchoRequest.newBuilder().setPayload(ByteString.empty()).build());
assertThat(echo.getPayload()).isEqualTo(ByteString.empty());
final EchoResponse echo2 = client.echo2(EchoRequest.newBuilder().setPayload(ByteString.empty()).build());
assertThat(echo2.getPayload()).isEqualTo(ByteString.empty());
}
@Test
public void enableByServiceWrongService() throws Exception {
final EchoServiceGrpc.EchoServiceBlockingStub client =
setup(false, List.of("org.signal.chat.rpc.NotEchoService"), Collections.emptyList());
GrpcTestUtils.assertStatusException(Status.UNIMPLEMENTED, () ->
client.echo(EchoRequest.newBuilder().setPayload(ByteString.empty()).build()));
}
private EchoServiceGrpc.EchoServiceBlockingStub setup(
boolean enableAll,
List<String> enabledServices,
List<String> enabledMethods)
throws IOException {
if (server != null) {
server.shutdownNow();
}
server = InProcessServerBuilder.forName("GrpcAllowListInterceptorTest")
.directExecutor()
.addService(new EchoServiceImpl())
.intercept(new GrpcAllowListInterceptor(enableAll, enabledServices, enabledMethods))
.build()
.start();
return EchoServiceGrpc.newBlockingStub(channel);
}
}
@@ -155,10 +155,10 @@ class CallQualitySurveyManagerTest {
if (expectValid) {
assertDoesNotThrow(validateRequest);
} else {
final IllegalArgumentException illegalArgumentException =
assertThrows(IllegalArgumentException.class, validateRequest);
final CallQualityInvalidArgumentsException invalidArgumentsException =
assertThrows(CallQualityInvalidArgumentsException.class, validateRequest);
assertTrue(StringUtils.isNotBlank(illegalArgumentException.getMessage()));
assertTrue(StringUtils.isNotBlank(invalidArgumentsException.getMessage()));
}
}
@@ -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<>();
@@ -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);
@@ -5,7 +5,6 @@
package org.whispersystems.textsecuregcm.storage;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
@@ -61,7 +60,7 @@ public class RegistrationRecoveryTest {
@Test
public void testLookupAfterWrite() throws Exception {
registrationRecoveryPasswords.addOrReplace(PNI, ORIGINAL_HASH).get();
assertTrue(registrationRecoveryPasswords.addOrReplace(PNI, ORIGINAL_HASH).get());
final long initialExp = fetchTimestamp(PNI);
final long expectedExpiration = CLOCK.instant().getEpochSecond() + EXPIRATION.getSeconds();
assertEquals(expectedExpiration, initialExp);
@@ -90,8 +89,8 @@ public class RegistrationRecoveryTest {
@Test
public void testReplace() throws Exception {
registrationRecoveryPasswords.addOrReplace(PNI, ORIGINAL_HASH).get();
registrationRecoveryPasswords.addOrReplace(PNI, ANOTHER_HASH).get();
assertTrue(registrationRecoveryPasswords.addOrReplace(PNI, ORIGINAL_HASH).get());
assertFalse(registrationRecoveryPasswords.addOrReplace(PNI, ANOTHER_HASH).get());
final Optional<SaltedTokenHash> saltedTokenHashByPni = registrationRecoveryPasswords.lookup(PNI).get();
assertTrue(saltedTokenHashByPni.isPresent());
@@ -101,12 +100,12 @@ public class RegistrationRecoveryTest {
@Test
public void testRemove() throws Exception {
assertDoesNotThrow(() -> registrationRecoveryPasswords.removeEntry(PNI).join());
assertFalse(registrationRecoveryPasswords.removeEntry(PNI).join());
registrationRecoveryPasswords.addOrReplace(PNI, ORIGINAL_HASH).get();
assertTrue(registrationRecoveryPasswords.lookup(PNI).get().isPresent());
registrationRecoveryPasswords.removeEntry(PNI).get();
assertTrue(registrationRecoveryPasswords.removeEntry(PNI).get());
assertTrue(registrationRecoveryPasswords.lookup(PNI).get().isEmpty());
}
@@ -48,7 +48,7 @@ class VerificationSessionsTest {
final Instant updates = Instant.now();
final Duration remoteExpiration = Duration.ofMinutes(2);
final VerificationSession verificationSession = new VerificationSession(null, null,
final VerificationSession verificationSession = new VerificationSession("test", null, null,
List.of(VerificationSession.Information.PUSH_CHALLENGE), Collections.emptyList(), null, null, true,
created.toEpochMilli(), updates.toEpochMilli(), remoteExpiration.toSeconds());
@@ -65,7 +65,7 @@ class VerificationSessionsTest {
final Optional<VerificationSession> absentSession = verificationSessions.findForKey(sessionId).join();
assertTrue(absentSession.isEmpty());
final VerificationSession session = new VerificationSession(null, new CarrierData("Test", CarrierData.LineType.MOBILE, Optional.of("123"), Optional.empty()),
final VerificationSession session = new VerificationSession(sessionId, null, new CarrierData("Test", CarrierData.LineType.MOBILE, Optional.of("123"), Optional.empty(), Optional.empty()),
List.of(VerificationSession.Information.PUSH_CHALLENGE), Collections.emptyList(), null, null, true,
clock.millis(), clock.millis(), Duration.ofMinutes(1).toSeconds());
@@ -80,7 +80,7 @@ class VerificationSessionsTest {
assertInstanceOf(ConditionalCheckFailedException.class, t,
"inserting with the same key should fail conditional checks");
final VerificationSession updatedSession = new VerificationSession(null, new CarrierData("Test", CarrierData.LineType.MOBILE, Optional.of("123"), Optional.empty()), Collections.emptyList(),
final VerificationSession updatedSession = new VerificationSession(sessionId, null, new CarrierData("Test", CarrierData.LineType.MOBILE, Optional.of("123"), Optional.empty(), Optional.empty()), Collections.emptyList(),
List.of(VerificationSession.Information.PUSH_CHALLENGE), null, null, true, clock.millis(), clock.millis(),
Duration.ofMinutes(2).toSeconds());
verificationSessions.update(sessionId, updatedSession).join();
@@ -110,7 +110,7 @@ class HlrLookupCarrierDataProviderTest {
final Optional<CarrierData> maybeCarrierData =
hlrLookupCarrierDataProvider.lookupCarrierData(PhoneNumberUtil.getInstance().getExampleNumber("US"), Duration.ZERO);
assertEquals(Optional.of(new CarrierData("Virgin Mobile", CarrierData.LineType.MOBILE, Optional.of("234"), Optional.of("38"))),
assertEquals(Optional.of(new CarrierData("Virgin Mobile", CarrierData.LineType.MOBILE, Optional.of("234"), Optional.of("38"), Optional.of(true))),
maybeCarrierData);
}
@@ -219,6 +219,25 @@ class HlrLookupCarrierDataProviderTest {
);
}
@SuppressWarnings("OptionalUsedAsFieldOrParameterType")
@ParameterizedTest
@MethodSource
void isPorted(final String isPortedString, final Optional<Boolean> expectedIsPortedValue) {
final HlrLookupResult hlrLookupResult =
new HlrLookupResult("NONE", 1.0f, "NOT_AVAILABLE", null, "NOT_AVAILABLE", null, "MOBILE", isPortedString);
assertEquals(expectedIsPortedValue, HlrLookupCarrierDataProvider.isPorted(hlrLookupResult.isPorted()));
}
private static List<Arguments> isPorted() {
return List.of(
Arguments.argumentSet("Null isPorted string", null, Optional.empty()),
Arguments.argumentSet("Is ported", "YES", Optional.of(true)),
Arguments.argumentSet("Is not ported", "NO", Optional.of(false)),
Arguments.argumentSet("Unrecognized isPorted string", "UNKNOWN", Optional.empty())
);
}
@SuppressWarnings("OptionalUsedAsFieldOrParameterType")
@ParameterizedTest
@MethodSource
@@ -266,11 +285,13 @@ class HlrLookupCarrierDataProviderTest {
@Nullable final NetworkDetails currentNetwork) {
return new HlrLookupResult(null,
1.0f,
originalNetwork == null ? "NOT_AVAILABLE" : "AVAILABLE",
originalNetwork,
currentNetwork == null ? "NOT_AVAILABLE" : "AVAILABLE",
currentNetwork,
"MOBILE");
"MOBILE",
"NO");
}
@Test
@@ -517,6 +517,9 @@ idlePrimaryDeviceReminder:
grpc:
port: 50051
grpcAllowList:
enableAll: true
asnTable:
s3Region: a-region
s3Bucket: a-bucket