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
53 changed files with 747 additions and 302 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) {
@@ -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;
@@ -209,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;
@@ -877,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();
@@ -897,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,
@@ -916,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,
@@ -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();
@@ -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)
@@ -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();
@@ -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);
}
}
@@ -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) {
}
@@ -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) {}
}
@@ -13,11 +13,6 @@ package org.signal.chat.calling;
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.
rpc GetTurnCredentials(GetTurnCredentialsRequest) returns (GetTurnCredentialsResponse) {}
}
@@ -15,16 +15,6 @@ package org.signal.chat.credentials;
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.
rpc GetExternalServiceCredentials(GetExternalServiceCredentialsRequest)
returns (GetExternalServiceCredentialsResponse) {}
}
@@ -33,10 +23,6 @@ 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.
rpc CheckSvrCredentials(CheckSvrCredentialsRequest)
returns (CheckSvrCredentialsResponse) {}
}
@@ -81,7 +67,8 @@ message CheckSvrCredentialsRequest {
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.
// 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;
}
@@ -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);
@@ -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()
@@ -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,
@@ -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()));
}
}
@@ -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