Compare commits

..
Author SHA1 Message Date
Ravi Khadiwala 05a3af6224 Temporarily disable flaky test 2026-07-17 16:34:36 -05:00
Chris Eager add6194c1c Update to the latest version of the spam filter 2026-07-17 16:32:18 -05:00
367 changed files with 5838 additions and 16573 deletions

No files matched your search

+1 -28
View File
@@ -10,36 +10,9 @@ updates:
update-types: [ minor, patch ]
- package-ecosystem: maven
directories: [ "**/*" ]
directory: /
schedule:
interval: monthly
ignore:
# Only patch updates don't require coordination with the deployed database
- dependency-name: "org.foundationdb:fdb-java"
update-types:
- version-update:semver-major
- version-update:semver-minor
# Ignore the latest pre-release version
versions: ["<=7.3.79"]
# Temporary exclusions, pending upstream fixes
# https://github.com/dropwizard/dropwizard/pull/11273
- dependency-name: "ch.qos.logback:*"
versions: [">=1.6.0"]
# https://github.com/jetty/jetty.project/issues/15657
- dependency-name: "org.eclipse.jetty:*"
versions: ["<=12.1.12"]
- dependency-name: "org.eclipse.jetty.ee10:*"
versions: ["<=12.1.12"]
# Temporary exclusions, pending adaptation to upstream changes
- dependency-name: "io.lettuce:lettuce-core"
versions: [">=7.7.0.RELEASE"]
# Dependency convergence sentinels, pinned to specific versions
- dependency-name: "tools.jackson.core:jackson-databind"
- dependency-name: "com.squareup.okio:okio-jvm"
groups:
minor-java-dependencies:
# Java: Only group minor and patch updates (we want to carefully review major updates)
+7 -8
View File
@@ -11,18 +11,17 @@ jobs:
contents: write
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
- name: Install APT packages
run: |
sudo apt-get update
# setup-java requires gpg
sudo apt-get install -y protobuf-compiler gpg
pip install sabledocs
- uses: actions/setup-java@dd06d9cba3e5552c54d9f8ea23572deb30010f7c # v6.0.0
- uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0
- uses: actions/setup-java@1bcf9fb12cf4aa7d266a90ae39939e61372fe520 # v5.4.0
with:
distribution: 'temurin'
java-version-file: .java-version
cache: 'maven'
- name: Install gRPC documentation tooling
run: |
sudo apt-get update
sudo apt-get install -y protobuf-compiler
pip install sabledocs
- name: Generate OpenAPI documentation
run: ./mvnw compile
- name: Generate gRPC documentation
+3 -8
View File
@@ -19,18 +19,13 @@ jobs:
contents: read
issues: write
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
- name: Install APT packages
run: |
# setup-java requires gpg
sudo apt update
sudo apt install -y gpg
- uses: actions/setup-java@dd06d9cba3e5552c54d9f8ea23572deb30010f7c # v6.0.0
- uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0
- uses: actions/setup-java@1bcf9fb12cf4aa7d266a90ae39939e61372fe520 # v5.4.0
with:
distribution: 'temurin'
java-version-file: .java-version
cache: 'maven'
- uses: aws-actions/configure-aws-credentials@e6de054238d6b7531b4efff3b6587d9aade6a06c # v6.2.3
- uses: aws-actions/configure-aws-credentials@254c19bd240aabef8777f48595e9d2d7b972184b # v6.2.1
name: Configure AWS credentials from Test account
with:
role-to-assume: ${{ vars.AWS_ROLE }}
+14 -16
View File
@@ -12,7 +12,7 @@ on:
jobs:
build:
runs-on: ubuntu-latest
container: ubuntu:26.04
container: ubuntu:24.04
timeout-minutes: 20
services:
@@ -28,15 +28,23 @@ jobs:
options: --name foundationdb1
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
- uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0
- name: Set up JDK
uses: actions/setup-java@1bcf9fb12cf4aa7d266a90ae39939e61372fe520 # v5.4.0
with:
distribution: 'temurin'
java-version-file: .java-version
cache: 'maven'
env:
# work around an issue with actions/runner setting an incorrect HOME in containers, which breaks maven caching
# https://github.com/actions/setup-java/issues/356
HOME: /root
- name: Install APT packages
# ca-certificates: required for AWS CRT client
run: |
apt update
# Maven Wrapper requires `unzip`; see https://github.com/apache/maven-wrapper/issues/425
# setup-java requires gpg
apt install -y ca-certificates curl gpg unzip
# Add Docker's official GPG key:
apt update
apt install -y ca-certificates curl
install -m 0755 -d /etc/apt/keyrings
curl -fsSL https://download.docker.com/linux/ubuntu/gpg -o /etc/apt/keyrings/docker.asc
chmod a+r /etc/apt/keyrings/docker.asc
@@ -49,16 +57,6 @@ jobs:
# ca-certificates: required for AWS CRT client
apt update && apt install -y docker-ce docker-ce-cli containerd.io docker-buildx-plugin docker-compose-plugin ca-certificates
- name: Set up JDK
uses: actions/setup-java@dd06d9cba3e5552c54d9f8ea23572deb30010f7c # v6.0.0
with:
distribution: 'temurin'
java-version-file: .java-version
cache: 'maven'
env:
# work around an issue with actions/runner setting an incorrect HOME in containers, which breaks maven caching
# https://github.com/actions/setup-java/issues/356
HOME: /root
- name: Configure FoundationDB0 database
run: docker exec foundationdb0 /usr/bin/fdbcli --exec 'configure new single memory'
- name: Configure FoundationDB1 database
+1 -1
View File
@@ -1 +1 @@
temurin-26
temurin-25
BIN
View File
Binary file not shown.
+3 -4
View File
@@ -14,8 +14,7 @@
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
wrapperVersion=3.3.4
distributionType=only-script
distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.9.16/apache-maven-3.9.16-bin.zip
distributionSha256Sum=5af3b743dd8b876b5c45da33b676251e5f1687712644abb4ee519ca56e1d89ce
distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.9.14/apache-maven-3.9.14-bin.zip
wrapperUrl=https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.3.4/maven-wrapper-3.3.4.jar
distributionSha256Sum=55fadd669532a3205d5db95f490bf13971d8b0843526f407f29db0e61f074ab3
wrapperSha256Sum=4e2fbf6554bc8a4702cdfdd3bef464f423393d784ddbb037216320ce55d5e4e1
+5
View File
@@ -10,6 +10,10 @@
<modelVersion>4.0.0</modelVersion>
<artifactId>integration-tests</artifactId>
<properties>
<jetty.http2-client.version>12.1.5</jetty.http2-client.version>
</properties>
<dependencies>
<dependency>
<groupId>org.whispersystems.textsecure</groupId>
@@ -35,6 +39,7 @@
<dependency>
<groupId>org.eclipse.jetty.http2</groupId>
<artifactId>jetty-http2-client-transport</artifactId>
<version>${jetty.http2-client.version}</version>
</dependency>
</dependencies>
@@ -0,0 +1,101 @@
/*
* Copyright 2023 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.signal.integration;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import java.io.IOException;
import java.util.Base64;
import org.signal.libsignal.protocol.IdentityKey;
import org.signal.libsignal.protocol.ecc.ECPublicKey;
public final class Codecs {
private Codecs() {
// utility class
}
@FunctionalInterface
public interface CheckedFunction<T, R> {
R apply(T t) throws Exception;
}
public static class Base64BasedSerializer<T> extends JsonSerializer<T> {
private final CheckedFunction<T, byte[]> mapper;
public Base64BasedSerializer(final CheckedFunction<T, byte[]> mapper) {
this.mapper = mapper;
}
@Override
public void serialize(final T value, final JsonGenerator gen, final SerializerProvider serializers) throws IOException {
try {
gen.writeString(Base64.getEncoder().withoutPadding().encodeToString(mapper.apply(value)));
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
public static class Base64BasedDeserializer<T> extends JsonDeserializer<T> {
private final CheckedFunction<byte[], T> mapper;
public Base64BasedDeserializer(final CheckedFunction<byte[], T> mapper) {
this.mapper = mapper;
}
@Override
public T deserialize(final JsonParser p, final DeserializationContext ctxt) throws IOException {
try {
return mapper.apply(Base64.getDecoder().decode(p.getValueAsString()));
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
public static class ByteArraySerializer extends Base64BasedSerializer<byte[]> {
public ByteArraySerializer() {
super(bytes -> bytes);
}
}
public static class ByteArrayDeserializer extends Base64BasedDeserializer<byte[]> {
public ByteArrayDeserializer() {
super(bytes -> bytes);
}
}
public static class ECPublicKeySerializer extends Base64BasedSerializer<ECPublicKey> {
public ECPublicKeySerializer() {
super(ECPublicKey::serialize);
}
}
public static class ECPublicKeyDeserializer extends Base64BasedDeserializer<ECPublicKey> {
public ECPublicKeyDeserializer() {
super(ECPublicKey::new);
}
}
public static class IdentityKeySerializer extends Base64BasedSerializer<IdentityKey> {
public IdentityKeySerializer() {
super(IdentityKey::serialize);
}
}
public static class IdentityKeyDeserializer extends Base64BasedDeserializer<IdentityKey> {
public IdentityKeyDeserializer() {
super(bytes -> new IdentityKey(bytes, 0));
}
}
}
@@ -13,14 +13,12 @@ import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import org.signal.integration.config.Config;
import org.signal.libsignal.zkgroup.receipts.ReceiptSerial;
import org.whispersystems.textsecuregcm.metrics.NoopAwsSdkMetricPublisher;
import org.whispersystems.textsecuregcm.registration.VerificationSession;
import org.whispersystems.textsecuregcm.storage.ChangeNumberWaitingPeriods;
import org.whispersystems.textsecuregcm.storage.PhoneNumberIdentifiers;
import org.whispersystems.textsecuregcm.storage.PhoneNumberRecoveryPasswords;
import org.whispersystems.textsecuregcm.storage.PhoneNumberRecoveryPasswordsManager;
import org.whispersystems.textsecuregcm.storage.RedeemedReceiptsManager;
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 software.amazon.awssdk.auth.credentials.AwsCredentialsProvider;
@@ -30,7 +28,7 @@ import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
public class IntegrationTools {
private final PhoneNumberRecoveryPasswordsManager phoneNumberRecoveryPasswordsManager;
private final RegistrationRecoveryPasswordsManager registrationRecoveryPasswordsManager;
private final VerificationSessionManager verificationSessionManager;
@@ -38,8 +36,6 @@ public class IntegrationTools {
private final ChangeNumberWaitingPeriods changeNumberWaitingPeriods;
private final RedeemedReceiptsManager redeemedReceiptsManager;
public static IntegrationTools create(final Config config) {
final AwsCredentialsProvider credentialsProvider = DefaultCredentialsProvider.builder().build();
@@ -49,39 +45,36 @@ public class IntegrationTools {
final DynamoDbClient dynamoDbClient =
config.dynamoDbClient().buildSyncClient(credentialsProvider, new NoopAwsSdkMetricPublisher());
final PhoneNumberRecoveryPasswords phoneNumberRecoveryPasswords = new PhoneNumberRecoveryPasswords(
final RegistrationRecoveryPasswords registrationRecoveryPasswords = new RegistrationRecoveryPasswords(
config.dynamoDbTables().registrationRecovery(), Duration.ofDays(1), dynamoDbClient, Clock.systemUTC());
final VerificationSessions verificationSessions = new VerificationSessions(
dynamoDbClient, config.dynamoDbTables().verificationSessions(), Clock.systemUTC());
return new IntegrationTools(
new PhoneNumberRecoveryPasswordsManager(phoneNumberRecoveryPasswords),
new RegistrationRecoveryPasswordsManager(registrationRecoveryPasswords),
new VerificationSessionManager(verificationSessions),
new PhoneNumberIdentifiers(dynamoDbAsyncClient, config.dynamoDbTables().phoneNumberIdentifiers()),
new ChangeNumberWaitingPeriods(config.dynamoDbTables().changeNumberWaitingPeriods(), dynamoDbClient),
new RedeemedReceiptsManager(Clock.systemUTC(), config.dynamoDbTables().redeemedReceipts(), dynamoDbClient)
new ChangeNumberWaitingPeriods(config.dynamoDbTables().changeNumberWaitingPeriods(), dynamoDbClient)
);
}
private IntegrationTools(
final PhoneNumberRecoveryPasswordsManager phoneNumberRecoveryPasswordsManager,
final RegistrationRecoveryPasswordsManager registrationRecoveryPasswordsManager,
final VerificationSessionManager verificationSessionManager,
final PhoneNumberIdentifiers phoneNumberIdentifiers,
final ChangeNumberWaitingPeriods changeNumberWaitingPeriods,
final RedeemedReceiptsManager redeemedReceiptsManager) {
this.phoneNumberRecoveryPasswordsManager = phoneNumberRecoveryPasswordsManager;
final ChangeNumberWaitingPeriods changeNumberWaitingPeriods) {
this.registrationRecoveryPasswordsManager = registrationRecoveryPasswordsManager;
this.verificationSessionManager = verificationSessionManager;
this.phoneNumberIdentifiers = phoneNumberIdentifiers;
this.changeNumberWaitingPeriods = changeNumberWaitingPeriods;
this.redeemedReceiptsManager = redeemedReceiptsManager;
}
public void populateRecoveryPassword(final String phoneNumber, final byte[] password) {
try {
final UUID pni = phoneNumberIdentifiers
.getPhoneNumberIdentifier(phoneNumber).get(5, TimeUnit.SECONDS);
phoneNumberRecoveryPasswordsManager.store(pni, password);
registrationRecoveryPasswordsManager.store(pni, password);
} catch (ExecutionException | InterruptedException | TimeoutException e) {
throw new RuntimeException("failed to get pni", e);
}
@@ -94,8 +87,4 @@ public class IntegrationTools {
public void clearChangeNumberWaitingPeriod(TestUser user) {
changeNumberWaitingPeriods.delete(user.aciUuid());
}
public void deleteRedeemedReceipt(final ReceiptSerial receiptSerial) {
redeemedReceiptsManager.deleteReceipt(receiptSerial);
}
}
@@ -12,17 +12,8 @@ import com.google.common.io.Resources;
import com.google.common.net.HttpHeaders;
import io.dropwizard.configuration.ConfigurationValidationException;
import io.dropwizard.jersey.validation.Validators;
import io.grpc.ChannelCredentials;
import io.grpc.ClientInterceptor;
import io.grpc.Grpc;
import io.grpc.ManagedChannel;
import io.grpc.Metadata;
import io.grpc.TlsChannelCredentials;
import io.grpc.stub.MetadataUtils;
import jakarta.validation.ConstraintViolation;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.lang.invoke.MethodHandles;
import java.net.URI;
import java.net.URL;
@@ -41,7 +32,6 @@ import java.util.Optional;
import java.util.Set;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import javax.annotation.Nullable;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.Validate;
import org.apache.commons.lang3.tuple.Pair;
@@ -59,16 +49,8 @@ import org.signal.libsignal.protocol.ecc.ECPublicKey;
import org.signal.libsignal.protocol.kem.KEMKeyPair;
import org.signal.libsignal.protocol.kem.KEMKeyType;
import org.signal.libsignal.protocol.kem.KEMPublicKey;
import org.signal.libsignal.zkgroup.InvalidInputException;
import org.signal.libsignal.zkgroup.ServerPublicParams;
import org.signal.libsignal.zkgroup.VerificationFailedException;
import org.signal.libsignal.zkgroup.receipts.ClientZkReceiptOperations;
import org.signal.libsignal.zkgroup.receipts.ReceiptCredential;
import org.signal.libsignal.zkgroup.receipts.ReceiptCredentialPresentation;
import org.signal.libsignal.zkgroup.receipts.ReceiptSerial;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.auth.grpc.RequireAuthenticationInterceptor;
import org.whispersystems.textsecuregcm.entities.AccountAttributes;
import org.whispersystems.textsecuregcm.entities.AccountIdentityResponse;
import org.whispersystems.textsecuregcm.entities.DeviceActivationRequest;
@@ -88,8 +70,6 @@ public final class Operations {
private static final Config CONFIG = loadConfigFromClasspath("config.yml");
private static final String GRPC_DOMAIN = "grpc." + CONFIG.domain();
private static final IntegrationTools INTEGRATION_TOOLS = IntegrationTools.create(CONFIG);
private static final String USER_AGENT = "integration-test";
@@ -98,85 +78,11 @@ public final class Operations {
private static final WebSocketClient WEB_SOCKET_CLIENT = buildWebSocketClient();
private static final ManagedChannel GRPC_CHANNEL = buildGrpcChannel();
private Operations() {
// utility class
}
public record Receipt(ReceiptSerial serial, ReceiptCredential credential) {}
public static Receipt getPrescribedReceipt() throws InvalidInputException {
return new Receipt(
new ReceiptSerial(Base64.getUrlDecoder().decode(CONFIG.prescribedReceiptSerial())),
new ReceiptCredential(Base64.getUrlDecoder().decode(CONFIG.prescribedReceiptCredential()))
);
}
public static TestUser registerNumberlessUser(final ReceiptCredential receiptCredential)
throws InvalidInputException, VerificationFailedException {
final String accountPassword = Base64.getEncoder().encodeToString(randomBytes(32));
final byte[] recoveryPassword = randomBytes(32);
final TestUser user = TestUser.createNumberless(accountPassword, recoveryPassword);
final ClientZkReceiptOperations clientOps = new ClientZkReceiptOperations(new ServerPublicParams(Base64.getDecoder().decode(CONFIG.serverZkPublicParams())));
final ReceiptCredentialPresentation receiptCredentialPresentation = clientOps.createReceiptCredentialPresentation(receiptCredential);
final ECKeyPair aciIdentityKeyPair = ECKeyPair.generate();
final RegistrationRequest registrationRequest = new RegistrationRequest(null,
null,
receiptCredentialPresentation.serialize(),
null,
user.accountAttributes(),
true,
new IdentityKey(aciIdentityKeyPair.getPublicKey()),
null,
new DeviceActivationRequest(generateSignedECPreKey(1, aciIdentityKeyPair),
Optional.empty(),
generateSignedKEMPreKey(3, aciIdentityKeyPair),
Optional.empty(),
Optional.empty(),
Optional.empty()));
final AccountIdentityResponse registrationResponse = apiPost("/v1/registration", registrationRequest)
// username must be present but can be set to anything for a numberless registration request
.authorized("test", accountPassword)
.executeExpectSuccess(AccountIdentityResponse.class);
user.setAciUuid(registrationResponse.uuid());
return user;
}
public static TestUser recoverNumberlessUser(final TestUser testUser, @Nullable final Integer totp) {
final String accountPassword = Base64.getEncoder().encodeToString(randomBytes(32));
final TestUser recoveredUser = TestUser.createNumberlessForRecovery(accountPassword, testUser.registrationPassword());
final ECKeyPair aciIdentityKeyPair = ECKeyPair.generate();
final ECKeyPair pniIdentityKeyPair = ECKeyPair.generate();
final RegistrationRequest registrationRequest = new RegistrationRequest(null,
testUser.registrationPassword(),
null,
totp,
recoveredUser.accountAttributes(),
true,
new IdentityKey(aciIdentityKeyPair.getPublicKey()),
new IdentityKey(pniIdentityKeyPair.getPublicKey()),
new DeviceActivationRequest(generateSignedECPreKey(1, aciIdentityKeyPair),
Optional.of(generateSignedECPreKey(2, pniIdentityKeyPair)),
generateSignedKEMPreKey(3, aciIdentityKeyPair),
Optional.of(generateSignedKEMPreKey(4, pniIdentityKeyPair)),
Optional.empty(),
Optional.empty()));
final AccountIdentityResponse registrationResponse = apiPost("/v1/registration", registrationRequest)
// For a numberless account recovery, the username is the ACI
.authorized(testUser.aciUuid().toString(), accountPassword)
.executeExpectSuccess(AccountIdentityResponse.class);
recoveredUser.setAciUuid(registrationResponse.uuid());
return recoveredUser;
}
public static TestUser newRegisteredUser(final String number) {
final byte[] registrationPassword = populateRandomRecoveryPassword(number);
final String accountPassword = Base64.getEncoder().encodeToString(randomBytes(32));
@@ -190,16 +96,14 @@ public final class Operations {
// register account
final RegistrationRequest registrationRequest = new RegistrationRequest(null,
registrationPassword,
null,
null,
accountAttributes,
true,
new IdentityKey(aciIdentityKeyPair.getPublicKey()),
new IdentityKey(pniIdentityKeyPair.getPublicKey()),
new DeviceActivationRequest(generateSignedECPreKey(1, aciIdentityKeyPair),
Optional.of(generateSignedECPreKey(2, pniIdentityKeyPair)),
generateSignedECPreKey(2, pniIdentityKeyPair),
generateSignedKEMPreKey(3, aciIdentityKeyPair),
Optional.of(generateSignedKEMPreKey(4, pniIdentityKeyPair)),
generateSignedKEMPreKey(4, pniIdentityKeyPair),
Optional.empty(),
Optional.empty()));
@@ -208,7 +112,7 @@ public final class Operations {
.executeExpectSuccess(AccountIdentityResponse.class);
user.setAciUuid(registrationResponse.uuid());
registrationResponse.pni().ifPresent(user::setPniUuid);
user.setPniUuid(registrationResponse.pni());
return user;
}
@@ -241,10 +145,6 @@ public final class Operations {
INTEGRATION_TOOLS.clearChangeNumberWaitingPeriod(user);
}
public static void deleteReceipt(final ReceiptSerial receiptSerial) {
INTEGRATION_TOOLS.deleteRedeemedReceipt(receiptSerial);
}
public static <T> T sendEmptyRequestAuthenticated(
final String endpoint,
final String method,
@@ -283,7 +183,7 @@ public final class Operations {
}
}
public static byte[] randomBytes(final int numBytes) {
private static byte[] randomBytes(int numBytes) {
final byte[] bytes = new byte[numBytes];
new SecureRandom().nextBytes(bytes);
return bytes;
@@ -316,33 +216,6 @@ public final class Operations {
return URI.create("https://" + CONFIG.domain() + endpoint + query);
}
public static ManagedChannel grpcChannel() {
return GRPC_CHANNEL;
}
public static ClientInterceptor authorizationInterceptor(final TestUser user, final byte deviceId) {
final String username = "%s.%d".formatted(user.aciUuid().toString(), deviceId);
final Metadata metadata = new Metadata();
metadata.put(RequireAuthenticationInterceptor.AUTHORIZATION_METADATA_KEY,
HeaderUtils.basicAuthHeader(username, user.accountPassword()));
return MetadataUtils.newAttachHeadersInterceptor(metadata);
}
private static ManagedChannel buildGrpcChannel() {
try {
final ByteArrayInputStream rootCert =
new ByteArrayInputStream(CONFIG.rootCert().getBytes(StandardCharsets.UTF_8));
final ChannelCredentials credentials = TlsChannelCredentials.newBuilder().trustManager(rootCert).build();
return Grpc.newChannelBuilderForAddress(GRPC_DOMAIN, 443, credentials)
.userAgent(USER_AGENT)
.build();
} catch (final IOException e) {
throw new UncheckedIOException(e);
}
}
public static class RequestBuilder {
private final HttpRequest.Builder builder;
@@ -487,7 +360,7 @@ public final class Operations {
final String path,
final Map<String, String> headers) throws IOException {
final URI uri = URI.create("wss://" + GRPC_DOMAIN + path);
final URI uri = URI.create("wss://grpc." + CONFIG.domain() + path);
final ClientUpgradeRequest request = new ClientUpgradeRequest(uri);
headers.forEach(request::setHeader);
@@ -0,0 +1,58 @@
/*
* Copyright 2023 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.signal.integration;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import org.apache.commons.lang3.tuple.Pair;
import org.signal.libsignal.protocol.IdentityKeyPair;
import org.signal.libsignal.protocol.ecc.ECKeyPair;
import org.signal.libsignal.protocol.state.SignedPreKeyRecord;
public class TestDevice {
private final byte deviceId;
private final Map<Integer, Pair<IdentityKeyPair, SignedPreKeyRecord>> signedPreKeys = new ConcurrentHashMap<>();
public static TestDevice create(
final byte deviceId,
final IdentityKeyPair aciIdentityKeyPair,
final IdentityKeyPair pniIdentityKeyPair) {
final TestDevice device = new TestDevice(deviceId);
device.addSignedPreKey(aciIdentityKeyPair);
device.addSignedPreKey(pniIdentityKeyPair);
return device;
}
public TestDevice(final byte deviceId) {
this.deviceId = deviceId;
}
public byte deviceId() {
return deviceId;
}
public SignedPreKeyRecord latestSignedPreKey(final IdentityKeyPair identity) {
final int id = signedPreKeys.entrySet()
.stream()
.filter(p -> p.getValue().getLeft().equals(identity))
.mapToInt(Map.Entry::getKey)
.max()
.orElseThrow();
return signedPreKeys.get(id).getRight();
}
public SignedPreKeyRecord addSignedPreKey(final IdentityKeyPair identity) {
final int nextId = signedPreKeys.keySet().stream().mapToInt(k -> k + 1).max().orElse(0);
final ECKeyPair keyPair = ECKeyPair.generate();
final byte[] signature = keyPair.getPrivateKey().calculateSignature(keyPair.getPublicKey().serialize());
final SignedPreKeyRecord signedPreKeyRecord = new SignedPreKeyRecord(nextId, System.currentTimeMillis(), keyPair, signature);
signedPreKeys.put(nextId, Pair.of(identity, signedPreKeyRecord));
return signedPreKeyRecord;
}
}
@@ -5,76 +5,71 @@
package org.signal.integration;
import java.nio.charset.StandardCharsets;
import static java.util.Objects.requireNonNull;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import java.security.SecureRandom;
import java.util.Optional;
import java.nio.charset.StandardCharsets;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import javax.annotation.Nullable;
import java.util.concurrent.ConcurrentHashMap;
import org.signal.libsignal.protocol.IdentityKey;
import org.signal.libsignal.protocol.IdentityKeyPair;
import org.signal.libsignal.protocol.InvalidKeyException;
import org.signal.libsignal.protocol.ecc.ECPublicKey;
import org.signal.libsignal.protocol.state.SignedPreKeyRecord;
import org.signal.libsignal.protocol.util.KeyHelper;
import org.whispersystems.textsecuregcm.auth.UnidentifiedAccessUtil;
import org.whispersystems.textsecuregcm.entities.AccountAttributes;
import org.whispersystems.textsecuregcm.storage.Device;
import org.whispersystems.textsecuregcm.storage.DeviceCapability;
public class TestUser {
private final int registrationId;
@Nullable
private final Integer pniRegistrationId;
private final int pniRegistrationId;
private final IdentityKeyPair aciIdentityKey;
private final Map<Byte, TestDevice> devices = new ConcurrentHashMap<>();
private final byte[] unidentifiedAccessKey;
@Nullable
private final String phoneNumber;
private String phoneNumber;
private final String accountPassword;
private IdentityKeyPair pniIdentityKey;
private final byte[] registrationPassword;
private String accountPassword;
private byte[] registrationPassword;
private UUID aciUuid;
@Nullable
private UUID pniUuid;
public static TestUser createNumberless(final String accountPassword, final byte[] accountRecoveryPassword) {
final int registrationId = KeyHelper.generateRegistrationId(false);
final byte[] unidentifiedAccessKey = Operations.randomBytes(UnidentifiedAccessUtil.UNIDENTIFIED_ACCESS_KEY_LENGTH);
return new TestUser(
registrationId,
null,
null,
unidentifiedAccessKey,
accountPassword,
accountRecoveryPassword);
}
public static TestUser createNumberlessForRecovery(final String accountPassword, final byte[] accountRecoveryPassword) {
// Recovering a numberless account requires PNI keys (though they are discarded by the server)
final int registrationId = KeyHelper.generateRegistrationId(false);
final int pniRegistrationId = KeyHelper.generateRegistrationId(false);
final byte[] unidentifiedAccessKey = new byte[UnidentifiedAccessUtil.UNIDENTIFIED_ACCESS_KEY_LENGTH];
new SecureRandom().nextBytes(unidentifiedAccessKey);
return new TestUser(
registrationId,
pniRegistrationId,
null,
unidentifiedAccessKey,
accountPassword,
accountRecoveryPassword);
}
public static TestUser create(final String phoneNumber, final String accountPassword, final byte[] registrationPassword) {
// ACI identity key pair
final IdentityKeyPair aciIdentityKey = IdentityKeyPair.generate();
// PNI identity key pair
final IdentityKeyPair pniIdentityKey = IdentityKeyPair.generate();
// registration id
final int registrationId = KeyHelper.generateRegistrationId(false);
final int pniRegistrationId = KeyHelper.generateRegistrationId(false);
// uak
final byte[] unidentifiedAccessKey = new byte[UnidentifiedAccessUtil.UNIDENTIFIED_ACCESS_KEY_LENGTH];
new SecureRandom().nextBytes(unidentifiedAccessKey);
return new TestUser(
registrationId,
pniRegistrationId,
aciIdentityKey,
phoneNumber,
pniIdentityKey,
unidentifiedAccessKey,
accountPassword,
registrationPassword);
@@ -82,25 +77,38 @@ public class TestUser {
public TestUser(
final int registrationId,
@Nullable final Integer pniRegistrationId,
@Nullable final String phoneNumber,
final int pniRegistrationId,
final IdentityKeyPair aciIdentityKey,
final String phoneNumber,
final IdentityKeyPair pniIdentityKey,
final byte[] unidentifiedAccessKey,
final String accountPassword,
final byte[] registrationPassword) {
this.registrationId = registrationId;
this.pniRegistrationId = pniRegistrationId;
this.aciIdentityKey = aciIdentityKey;
this.phoneNumber = phoneNumber;
this.pniIdentityKey = pniIdentityKey;
this.unidentifiedAccessKey = unidentifiedAccessKey;
this.accountPassword = accountPassword;
this.registrationPassword = registrationPassword;
devices.put(Device.PRIMARY_ID, TestDevice.create(Device.PRIMARY_ID, aciIdentityKey, pniIdentityKey));
}
public int registrationId() {
return registrationId;
}
public Optional<String> phoneNumber() {
return Optional.ofNullable(phoneNumber);
public IdentityKeyPair aciIdentityKey() {
return aciIdentityKey;
}
public String phoneNumber() {
return phoneNumber;
}
public IdentityKeyPair pniIdentityKey() {
return pniIdentityKey;
}
public String accountPassword() {
@@ -115,21 +123,77 @@ public class TestUser {
return aciUuid;
}
public Optional<UUID> pniUuid() {
return Optional.ofNullable(pniUuid);
public UUID pniUuid() {
return pniUuid;
}
public AccountAttributes accountAttributes() {
return new AccountAttributes(true, registrationId, pniRegistrationId, "".getBytes(StandardCharsets.UTF_8), "", true,
DeviceCapability.CAPABILITIES_REQUIRED_FOR_NEW_DEVICES, registrationPassword)
.setUnidentifiedAccessKey(unidentifiedAccessKey);
DeviceCapability.CAPABILITIES_REQUIRED_FOR_NEW_DEVICES)
.setUnidentifiedAccessKey(unidentifiedAccessKey)
.setRecoveryPassword(registrationPassword);
}
public void setAciUuid(final UUID aciUuid) {
this.aciUuid = aciUuid;
}
public void setPniUuid(@Nullable final UUID pniUuid) {
public void setPniUuid(final UUID pniUuid) {
this.pniUuid = pniUuid;
}
public void setPhoneNumber(final String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public void setPniIdentityKey(final IdentityKeyPair pniIdentityKey) {
this.pniIdentityKey = pniIdentityKey;
}
public void setAccountPassword(final String accountPassword) {
this.accountPassword = accountPassword;
}
public void setRegistrationPassword(final byte[] registrationPassword) {
this.registrationPassword = registrationPassword;
}
public PreKeySetPublicView preKeys(final byte deviceId, final boolean pni) {
final IdentityKeyPair identity = pni
? pniIdentityKey
: aciIdentityKey;
final TestDevice device = requireNonNull(devices.get(deviceId));
final SignedPreKeyRecord signedPreKeyRecord = device.latestSignedPreKey(identity);
try {
return new PreKeySetPublicView(
Collections.emptyList(),
identity.getPublicKey(),
new SignedPreKeyPublicView(
signedPreKeyRecord.getId(),
signedPreKeyRecord.getKeyPair().getPublicKey(),
signedPreKeyRecord.getSignature()
)
);
} catch (InvalidKeyException e) {
throw new RuntimeException(e);
}
}
public record SignedPreKeyPublicView(
int keyId,
@JsonSerialize(using = Codecs.ECPublicKeySerializer.class)
@JsonDeserialize(using = Codecs.ECPublicKeyDeserializer.class)
ECPublicKey publicKey,
@JsonSerialize(using = Codecs.ByteArraySerializer.class)
@JsonDeserialize(using = Codecs.ByteArrayDeserializer.class)
byte[] signature) {
}
public record PreKeySetPublicView(
List<String> preKeys,
@JsonSerialize(using = Codecs.IdentityKeySerializer.class)
@JsonDeserialize(using = Codecs.IdentityKeyDeserializer.class)
IdentityKey identityKey,
SignedPreKeyPublicView signedPreKey) {
}
}
@@ -15,8 +15,5 @@ public record Config(@NotBlank String domain,
@NotNull @Valid DynamoDbClientFactory dynamoDbClient,
@NotNull @Valid DynamoDbTables dynamoDbTables,
@NotBlank String prescribedRegistrationNumber,
@NotBlank String prescribedRegistrationCode,
@NotBlank String prescribedReceiptSerial,
@NotBlank String prescribedReceiptCredential,
@NotBlank String serverZkPublicParams) {
@NotBlank String prescribedRegistrationCode) {
}
@@ -10,6 +10,5 @@ import jakarta.validation.constraints.NotBlank;
public record DynamoDbTables(@NotBlank String registrationRecovery,
@NotBlank String verificationSessions,
@NotBlank String phoneNumberIdentifiers,
@NotBlank String changeNumberWaitingPeriods,
@NotBlank String redeemedReceipts) {
@NotBlank String changeNumberWaitingPeriods) {
}
@@ -5,43 +5,21 @@
package org.signal.integration;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import com.eatthepath.otp.TimeBasedOneTimePasswordGenerator;
import com.google.protobuf.ByteString;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.time.Duration;
import java.time.Instant;
import java.util.Arrays;
import java.util.Base64;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.UUID;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.lang3.tuple.Pair;
import org.apache.http.HttpStatus;
import org.junit.jupiter.api.Test;
import org.signal.chat.account.AccountsGrpc;
import org.signal.chat.account.ConfirmTotpKeyRequest;
import org.signal.chat.account.ConfirmTotpKeyResponse;
import org.signal.chat.account.GenerateTotpKeyRequest;
import org.signal.chat.account.GenerateTotpKeyResponse;
import org.signal.chat.account.ListMfaKeysRequest;
import org.signal.chat.account.ListMfaKeysResponse;
import org.signal.chat.account.TotpParameters;
import org.signal.libsignal.protocol.IdentityKey;
import org.signal.libsignal.protocol.ecc.ECKeyPair;
import org.signal.libsignal.usernames.BaseUsernameException;
import org.signal.libsignal.usernames.Username;
import org.signal.libsignal.zkgroup.InvalidInputException;
import org.signal.libsignal.zkgroup.VerificationFailedException;
import org.whispersystems.textsecuregcm.entities.AccountIdentifierResponse;
import org.whispersystems.textsecuregcm.entities.AccountIdentityResponse;
import org.whispersystems.textsecuregcm.entities.ChangeNumberRequest;
@@ -54,79 +32,6 @@ import org.whispersystems.textsecuregcm.storage.Device;
public class AccountTest {
@Test
public void testCreateNumberlessAccount()
throws VerificationFailedException, InvalidInputException {
final Operations.Receipt receipt = Operations.getPrescribedReceipt();
final TestUser user = Operations.registerNumberlessUser(receipt.credential());
try {
final Pair<Integer, AccountIdentityResponse> execute = Operations.apiGet("/v1/accounts/whoami")
.authorized(user)
.execute(AccountIdentityResponse.class);
assertEquals(HttpStatus.SC_OK, execute.getLeft());
} finally {
Operations.deleteReceipt(receipt.serial());
Operations.deleteUser(user);
}
}
@Test
public void testRecoverWithTotp()
throws VerificationFailedException, InvalidInputException, NoSuchAlgorithmException, InvalidKeyException {
final Operations.Receipt receipt = Operations.getPrescribedReceipt();
final TestUser originalUser = Operations.registerNumberlessUser(receipt.credential());
try {
final GenerateTotpKeyResponse generateTotpKeyResponse =
getAccountsStubForUser(originalUser).generateTotpKey(GenerateTotpKeyRequest.getDefaultInstance());
assertEquals(GenerateTotpKeyResponse.ResponseCase.KEY_GENERATED, generateTotpKeyResponse.getResponseCase());
final TotpParameters totpParameters = generateTotpKeyResponse.getKeyGenerated().getTotpParameters();
final TimeBasedOneTimePasswordGenerator totpGenerator = new TimeBasedOneTimePasswordGenerator(
Duration.ofSeconds(totpParameters.getTimeStepSeconds()),
totpParameters.getPasswordLength(),
totpParameters.getAlgorithm());
final SecretKey totpKey = new SecretKeySpec(
generateTotpKeyResponse.getKeyGenerated().getKey().toByteArray(),
totpParameters.getAlgorithm());
final byte[] totpMetadata = Operations.randomBytes(160);
final ConfirmTotpKeyResponse confirmTotpKeyResponse = getAccountsStubForUser(originalUser)
.confirmTotpKey(ConfirmTotpKeyRequest.newBuilder()
.setOneTimePassword(totpGenerator.generateOneTimePassword(totpKey, Instant.now()))
.setMetadataCiphertext(ByteString.copyFrom(totpMetadata))
.build());
assertEquals(ConfirmTotpKeyResponse.ResponseCase.KEY_CONFIRMED, confirmTotpKeyResponse.getResponseCase());
final int keyId = confirmTotpKeyResponse.getKeyConfirmed().getKeyId();
final TestUser recoveredUser =
Operations.recoverNumberlessUser(originalUser, totpGenerator.generateOneTimePassword(totpKey, Instant.now()));
assertEquals(originalUser.aciUuid(), recoveredUser.aciUuid());
// MFA key should remain set after re-registration
final Map<Integer, ListMfaKeysResponse.MfaKeyMetadata> mfaKeys =
getAccountsStubForUser(recoveredUser).listMfaKeys(ListMfaKeysRequest.getDefaultInstance()).getKeysMap();
assertEquals(1, mfaKeys.size());
assertTrue(mfaKeys.containsKey(keyId));
assertEquals(ListMfaKeysResponse.MfaKeyMetadata.MfaKeyType.MFA_KEY_TYPE_TOTP, mfaKeys.get(keyId).getType());
assertArrayEquals(totpMetadata, mfaKeys.get(keyId).getMetadataCiphertext().toByteArray());
} finally {
Operations.deleteReceipt(receipt.serial());
Operations.deleteUser(originalUser);
}
}
private static AccountsGrpc.AccountsBlockingStub getAccountsStubForUser(final TestUser user) {
return AccountsGrpc
.newBlockingStub(Operations.grpcChannel())
.withInterceptors(Operations.authorizationInterceptor(user, Device.PRIMARY_ID));
}
@Test
public void testCreateAccount() {
final TestUser user = Operations.newRegisteredUser("+19995550101");
@@ -167,7 +72,7 @@ public class AccountTest {
assertEquals(user.aciUuid(), accountIdentityResponse.uuid());
assertNotEquals(user.pniUuid(), accountIdentityResponse.pni());
assertEquals(Optional.of(targetNumber), accountIdentityResponse.number());
assertEquals(targetNumber, accountIdentityResponse.number());
} finally {
Operations.deleteUser(user);
}
@@ -11,16 +11,20 @@ import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTimeoutPreemptively;
import com.google.common.net.HttpHeaders;
import jakarta.ws.rs.core.MediaType;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.TimeUnit;
import jakarta.ws.rs.core.MediaType;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.Timeout;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.entities.IncomingMessage;
import org.whispersystems.textsecuregcm.entities.IncomingMessageList;
import org.whispersystems.textsecuregcm.entities.MessageProtos;
@@ -61,7 +65,7 @@ public class MessagingTest {
assertDoesNotThrow(() -> WebsocketClientSession.decode(SendMessageResponse.class, responseMessage));
final WebsocketClientSession websocketB = Operations.authenticatedWebsocket(userB, Device.PRIMARY_ID);
assertTimeoutPreemptively(Duration.ofSeconds(15), websocketB::waitForQueueEmpty);
assertTimeoutPreemptively(Duration.ofSeconds(5), websocketB::waitForQueueEmpty);
assertEquals(1, websocketB.getReceivedEnvelopes().size());
final MessageProtos.Envelope envelope = websocketB.getReceivedEnvelopes().getFirst();
Vendored
+251 -238
View File
@@ -19,277 +19,290 @@
# ----------------------------------------------------------------------------
# ----------------------------------------------------------------------------
# Apache Maven Wrapper startup batch script, version 3.3.4
# Apache Maven Wrapper startup batch script, version 3.2.0
#
# Required ENV vars:
# ------------------
# JAVA_HOME - location of a JDK home dir
#
# Optional ENV vars
# -----------------
# JAVA_HOME - location of a JDK home dir, required when download maven via java source
# MVNW_REPOURL - repo url base for downloading maven distribution
# MVNW_USERNAME/MVNW_PASSWORD - user and password for downloading maven
# MVNW_VERBOSE - true: enable verbose log; debug: trace the mvnw script; others: silence the output
# MAVEN_OPTS - parameters passed to the Java VM when running Maven
# e.g. to debug Maven itself, use
# set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000
# MAVEN_SKIP_RC - flag to disable loading of mavenrc files
# ----------------------------------------------------------------------------
set -euf
[ "${MVNW_VERBOSE-}" != debug ] || set -x
if [ -z "$MAVEN_SKIP_RC" ] ; then
# OS specific support.
native_path() { printf %s\\n "$1"; }
if [ -f /usr/local/etc/mavenrc ] ; then
. /usr/local/etc/mavenrc
fi
if [ -f /etc/mavenrc ] ; then
. /etc/mavenrc
fi
if [ -f "$HOME/.mavenrc" ] ; then
. "$HOME/.mavenrc"
fi
fi
# OS specific support. $var _must_ be set to either true or false.
cygwin=false;
darwin=false;
mingw=false
case "$(uname)" in
CYGWIN* | MINGW*)
[ -z "${JAVA_HOME-}" ] || JAVA_HOME="$(cygpath --unix "$JAVA_HOME")"
native_path() { cygpath --path --windows "$1"; }
;;
CYGWIN*) cygwin=true ;;
MINGW*) mingw=true;;
Darwin*) darwin=true
# Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home
# See https://developer.apple.com/library/mac/qa/qa1170/_index.html
if [ -z "$JAVA_HOME" ]; then
if [ -x "/usr/libexec/java_home" ]; then
JAVA_HOME="$(/usr/libexec/java_home)"; export JAVA_HOME
else
JAVA_HOME="/Library/Java/Home"; export JAVA_HOME
fi
fi
;;
esac
# set JAVACMD and JAVACCMD
set_java_home() {
# For Cygwin and MinGW, ensure paths are in Unix format before anything is touched
if [ -n "${JAVA_HOME-}" ]; then
if [ -x "$JAVA_HOME/jre/sh/java" ]; then
if [ -z "$JAVA_HOME" ] ; then
if [ -r /etc/gentoo-release ] ; then
JAVA_HOME=$(java-config --jre-home)
fi
fi
# For Cygwin, ensure paths are in UNIX format before anything is touched
if $cygwin ; then
[ -n "$JAVA_HOME" ] &&
JAVA_HOME=$(cygpath --unix "$JAVA_HOME")
[ -n "$CLASSPATH" ] &&
CLASSPATH=$(cygpath --path --unix "$CLASSPATH")
fi
# For Mingw, ensure paths are in UNIX format before anything is touched
if $mingw ; then
[ -n "$JAVA_HOME" ] && [ -d "$JAVA_HOME" ] &&
JAVA_HOME="$(cd "$JAVA_HOME" || (echo "cannot cd into $JAVA_HOME."; exit 1); pwd)"
fi
if [ -z "$JAVA_HOME" ]; then
javaExecutable="$(which javac)"
if [ -n "$javaExecutable" ] && ! [ "$(expr "\"$javaExecutable\"" : '\([^ ]*\)')" = "no" ]; then
# readlink(1) is not available as standard on Solaris 10.
readLink=$(which readlink)
if [ ! "$(expr "$readLink" : '\([^ ]*\)')" = "no" ]; then
if $darwin ; then
javaHome="$(dirname "\"$javaExecutable\"")"
javaExecutable="$(cd "\"$javaHome\"" && pwd -P)/javac"
else
javaExecutable="$(readlink -f "\"$javaExecutable\"")"
fi
javaHome="$(dirname "\"$javaExecutable\"")"
javaHome=$(expr "$javaHome" : '\(.*\)/bin')
JAVA_HOME="$javaHome"
export JAVA_HOME
fi
fi
fi
if [ -z "$JAVACMD" ] ; then
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD="$JAVA_HOME/jre/sh/java"
JAVACCMD="$JAVA_HOME/jre/sh/javac"
else
JAVACMD="$JAVA_HOME/bin/java"
JAVACCMD="$JAVA_HOME/bin/javac"
if [ ! -x "$JAVACMD" ] || [ ! -x "$JAVACCMD" ]; then
echo "The JAVA_HOME environment variable is not defined correctly, so mvnw cannot run." >&2
echo "JAVA_HOME is set to \"$JAVA_HOME\", but \"\$JAVA_HOME/bin/java\" or \"\$JAVA_HOME/bin/javac\" does not exist." >&2
return 1
fi
fi
else
JAVACMD="$(
'set' +e
'unset' -f command 2>/dev/null
'command' -v java
)" || :
JAVACCMD="$(
'set' +e
'unset' -f command 2>/dev/null
'command' -v javac
)" || :
if [ ! -x "${JAVACMD-}" ] || [ ! -x "${JAVACCMD-}" ]; then
echo "The java/javac command does not exist in PATH nor is JAVA_HOME set, so mvnw cannot run." >&2
return 1
fi
JAVACMD="$(\unset -f command 2>/dev/null; \command -v java)"
fi
}
fi
# hash string like Java String::hashCode
hash_string() {
str="${1:-}" h=0
while [ -n "$str" ]; do
char="${str%"${str#?}"}"
h=$(((h * 31 + $(LC_CTYPE=C printf %d "'$char")) % 4294967296))
str="${str#?}"
done
printf %x\\n $h
}
verbose() { :; }
[ "${MVNW_VERBOSE-}" != true ] || verbose() { printf %s\\n "${1-}"; }
die() {
printf %s\\n "$1" >&2
if [ ! -x "$JAVACMD" ] ; then
echo "Error: JAVA_HOME is not defined correctly." >&2
echo " We cannot execute $JAVACMD" >&2
exit 1
}
trim() {
# MWRAPPER-139:
# Trims trailing and leading whitespace, carriage returns, tabs, and linefeeds.
# Needed for removing poorly interpreted newline sequences when running in more
# exotic environments such as mingw bash on Windows.
printf "%s" "${1}" | tr -d '[:space:]'
}
scriptDir="$(dirname "$0")"
scriptName="$(basename "$0")"
# parse distributionUrl and optional distributionSha256Sum, requires .mvn/wrapper/maven-wrapper.properties
while IFS="=" read -r key value; do
case "${key-}" in
distributionUrl) distributionUrl=$(trim "${value-}") ;;
distributionSha256Sum) distributionSha256Sum=$(trim "${value-}") ;;
esac
done <"$scriptDir/.mvn/wrapper/maven-wrapper.properties"
[ -n "${distributionUrl-}" ] || die "cannot read distributionUrl property in $scriptDir/.mvn/wrapper/maven-wrapper.properties"
case "${distributionUrl##*/}" in
maven-mvnd-*bin.*)
MVN_CMD=mvnd.sh _MVNW_REPO_PATTERN=/maven/mvnd/
case "${PROCESSOR_ARCHITECTURE-}${PROCESSOR_ARCHITEW6432-}:$(uname -a)" in
*AMD64:CYGWIN* | *AMD64:MINGW*) distributionPlatform=windows-amd64 ;;
:Darwin*x86_64) distributionPlatform=darwin-amd64 ;;
:Darwin*arm64) distributionPlatform=darwin-aarch64 ;;
:Linux*x86_64*) distributionPlatform=linux-amd64 ;;
*)
echo "Cannot detect native platform for mvnd on $(uname)-$(uname -m), use pure java version" >&2
distributionPlatform=linux-amd64
;;
esac
distributionUrl="${distributionUrl%-bin.*}-$distributionPlatform.zip"
;;
maven-mvnd-*) MVN_CMD=mvnd.sh _MVNW_REPO_PATTERN=/maven/mvnd/ ;;
*) MVN_CMD="mvn${scriptName#mvnw}" _MVNW_REPO_PATTERN=/org/apache/maven/ ;;
esac
# apply MVNW_REPOURL and calculate MAVEN_HOME
# maven home pattern: ~/.m2/wrapper/dists/{apache-maven-<version>,maven-mvnd-<version>-<platform>}/<hash>
[ -z "${MVNW_REPOURL-}" ] || distributionUrl="$MVNW_REPOURL$_MVNW_REPO_PATTERN${distributionUrl#*"$_MVNW_REPO_PATTERN"}"
distributionUrlName="${distributionUrl##*/}"
distributionUrlNameMain="${distributionUrlName%.*}"
distributionUrlNameMain="${distributionUrlNameMain%-bin}"
MAVEN_USER_HOME="${MAVEN_USER_HOME:-${HOME}/.m2}"
MAVEN_HOME="${MAVEN_USER_HOME}/wrapper/dists/${distributionUrlNameMain-}/$(hash_string "$distributionUrl")"
exec_maven() {
unset MVNW_VERBOSE MVNW_USERNAME MVNW_PASSWORD MVNW_REPOURL || :
exec "$MAVEN_HOME/bin/$MVN_CMD" "$@" || die "cannot exec $MAVEN_HOME/bin/$MVN_CMD"
}
if [ -d "$MAVEN_HOME" ]; then
verbose "found existing MAVEN_HOME at $MAVEN_HOME"
exec_maven "$@"
fi
case "${distributionUrl-}" in
*?-bin.zip | *?maven-mvnd-?*-?*.zip) ;;
*) die "distributionUrl is not valid, must match *-bin.zip or maven-mvnd-*.zip, but found '${distributionUrl-}'" ;;
esac
# prepare tmp dir
if TMP_DOWNLOAD_DIR="$(mktemp -d)" && [ -d "$TMP_DOWNLOAD_DIR" ]; then
clean() { rm -rf -- "$TMP_DOWNLOAD_DIR"; }
trap clean HUP INT TERM EXIT
else
die "cannot create temp dir"
if [ -z "$JAVA_HOME" ] ; then
echo "Warning: JAVA_HOME environment variable is not set."
fi
mkdir -p -- "${MAVEN_HOME%/*}"
# traverses directory structure from process work directory to filesystem root
# first directory with .mvn subdirectory is considered project base directory
find_maven_basedir() {
if [ -z "$1" ]
then
echo "Path not specified to find_maven_basedir"
return 1
fi
# Download and Install Apache Maven
verbose "Couldn't find MAVEN_HOME, downloading and installing it ..."
verbose "Downloading from: $distributionUrl"
verbose "Downloading to: $TMP_DOWNLOAD_DIR/$distributionUrlName"
# select .zip or .tar.gz
if ! command -v unzip >/dev/null; then
distributionUrl="${distributionUrl%.zip}.tar.gz"
distributionUrlName="${distributionUrl##*/}"
fi
# verbose opt
__MVNW_QUIET_WGET=--quiet __MVNW_QUIET_CURL=--silent __MVNW_QUIET_UNZIP=-q __MVNW_QUIET_TAR=''
[ "${MVNW_VERBOSE-}" != true ] || __MVNW_QUIET_WGET='' __MVNW_QUIET_CURL='' __MVNW_QUIET_UNZIP='' __MVNW_QUIET_TAR=v
# normalize http auth
case "${MVNW_PASSWORD:+has-password}" in
'') MVNW_USERNAME='' MVNW_PASSWORD='' ;;
has-password) [ -n "${MVNW_USERNAME-}" ] || MVNW_USERNAME='' MVNW_PASSWORD='' ;;
esac
if [ -z "${MVNW_USERNAME-}" ] && command -v wget >/dev/null; then
verbose "Found wget ... using wget"
wget ${__MVNW_QUIET_WGET:+"$__MVNW_QUIET_WGET"} "$distributionUrl" -O "$TMP_DOWNLOAD_DIR/$distributionUrlName" || die "wget: Failed to fetch $distributionUrl"
elif [ -z "${MVNW_USERNAME-}" ] && command -v curl >/dev/null; then
verbose "Found curl ... using curl"
curl ${__MVNW_QUIET_CURL:+"$__MVNW_QUIET_CURL"} -f -L -o "$TMP_DOWNLOAD_DIR/$distributionUrlName" "$distributionUrl" || die "curl: Failed to fetch $distributionUrl"
elif set_java_home; then
verbose "Falling back to use Java to download"
javaSource="$TMP_DOWNLOAD_DIR/Downloader.java"
targetZip="$TMP_DOWNLOAD_DIR/$distributionUrlName"
cat >"$javaSource" <<-END
public class Downloader extends java.net.Authenticator
{
protected java.net.PasswordAuthentication getPasswordAuthentication()
{
return new java.net.PasswordAuthentication( System.getenv( "MVNW_USERNAME" ), System.getenv( "MVNW_PASSWORD" ).toCharArray() );
}
public static void main( String[] args ) throws Exception
{
setDefault( new Downloader() );
java.nio.file.Files.copy( java.net.URI.create( args[0] ).toURL().openStream(), java.nio.file.Paths.get( args[1] ).toAbsolutePath().normalize() );
}
}
END
# For Cygwin/MinGW, switch paths to Windows format before running javac and java
verbose " - Compiling Downloader.java ..."
"$(native_path "$JAVACCMD")" "$(native_path "$javaSource")" || die "Failed to compile Downloader.java"
verbose " - Running Downloader.java ..."
"$(native_path "$JAVACMD")" -cp "$(native_path "$TMP_DOWNLOAD_DIR")" Downloader "$distributionUrl" "$(native_path "$targetZip")"
fi
# If specified, validate the SHA-256 sum of the Maven distribution zip file
if [ -n "${distributionSha256Sum-}" ]; then
distributionSha256Result=false
if [ "$MVN_CMD" = mvnd.sh ]; then
echo "Checksum validation is not supported for maven-mvnd." >&2
echo "Please disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." >&2
exit 1
elif command -v sha256sum >/dev/null; then
if echo "$distributionSha256Sum $TMP_DOWNLOAD_DIR/$distributionUrlName" | sha256sum -c - >/dev/null 2>&1; then
distributionSha256Result=true
basedir="$1"
wdir="$1"
while [ "$wdir" != '/' ] ; do
if [ -d "$wdir"/.mvn ] ; then
basedir=$wdir
break
fi
elif command -v shasum >/dev/null; then
if echo "$distributionSha256Sum $TMP_DOWNLOAD_DIR/$distributionUrlName" | shasum -a 256 -c >/dev/null 2>&1; then
distributionSha256Result=true
# workaround for JBEAP-8937 (on Solaris 10/Sparc)
if [ -d "${wdir}" ]; then
wdir=$(cd "$wdir/.." || exit 1; pwd)
fi
# end of workaround
done
printf '%s' "$(cd "$basedir" || exit 1; pwd)"
}
# concatenates all lines of a file
concat_lines() {
if [ -f "$1" ]; then
# Remove \r in case we run on Windows within Git Bash
# and check out the repository with auto CRLF management
# enabled. Otherwise, we may read lines that are delimited with
# \r\n and produce $'-Xarg\r' rather than -Xarg due to word
# splitting rules.
tr -s '\r\n' ' ' < "$1"
fi
}
log() {
if [ "$MVNW_VERBOSE" = true ]; then
printf '%s\n' "$1"
fi
}
BASE_DIR=$(find_maven_basedir "$(dirname "$0")")
if [ -z "$BASE_DIR" ]; then
exit 1;
fi
MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"}; export MAVEN_PROJECTBASEDIR
log "$MAVEN_PROJECTBASEDIR"
##########################################################################################
# Extension to allow automatically downloading the maven-wrapper.jar from Maven-central
# This allows using the maven wrapper in projects that prohibit checking in binary data.
##########################################################################################
wrapperJarPath="$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar"
if [ -r "$wrapperJarPath" ]; then
log "Found $wrapperJarPath"
else
log "Couldn't find $wrapperJarPath, downloading it ..."
if [ -n "$MVNW_REPOURL" ]; then
wrapperUrl="$MVNW_REPOURL/org/apache/maven/wrapper/maven-wrapper/3.2.0/maven-wrapper-3.2.0.jar"
else
wrapperUrl="https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.2.0/maven-wrapper-3.2.0.jar"
fi
while IFS="=" read -r key value; do
# Remove '\r' from value to allow usage on windows as IFS does not consider '\r' as a separator ( considers space, tab, new line ('\n'), and custom '=' )
safeValue=$(echo "$value" | tr -d '\r')
case "$key" in (wrapperUrl) wrapperUrl="$safeValue"; break ;;
esac
done < "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.properties"
log "Downloading from: $wrapperUrl"
if $cygwin; then
wrapperJarPath=$(cygpath --path --windows "$wrapperJarPath")
fi
if command -v wget > /dev/null; then
log "Found wget ... using wget"
[ "$MVNW_VERBOSE" = true ] && QUIET="" || QUIET="--quiet"
if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then
wget $QUIET "$wrapperUrl" -O "$wrapperJarPath" || rm -f "$wrapperJarPath"
else
wget $QUIET --http-user="$MVNW_USERNAME" --http-password="$MVNW_PASSWORD" "$wrapperUrl" -O "$wrapperJarPath" || rm -f "$wrapperJarPath"
fi
elif command -v curl > /dev/null; then
log "Found curl ... using curl"
[ "$MVNW_VERBOSE" = true ] && QUIET="" || QUIET="--silent"
if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then
curl $QUIET -o "$wrapperJarPath" "$wrapperUrl" -f -L || rm -f "$wrapperJarPath"
else
curl $QUIET --user "$MVNW_USERNAME:$MVNW_PASSWORD" -o "$wrapperJarPath" "$wrapperUrl" -f -L || rm -f "$wrapperJarPath"
fi
else
log "Falling back to using Java to download"
javaSource="$MAVEN_PROJECTBASEDIR/.mvn/wrapper/MavenWrapperDownloader.java"
javaClass="$MAVEN_PROJECTBASEDIR/.mvn/wrapper/MavenWrapperDownloader.class"
# For Cygwin, switch paths to Windows format before running javac
if $cygwin; then
javaSource=$(cygpath --path --windows "$javaSource")
javaClass=$(cygpath --path --windows "$javaClass")
fi
if [ -e "$javaSource" ]; then
if [ ! -e "$javaClass" ]; then
log " - Compiling MavenWrapperDownloader.java ..."
("$JAVA_HOME/bin/javac" "$javaSource")
fi
if [ -e "$javaClass" ]; then
log " - Running MavenWrapperDownloader.java ..."
("$JAVA_HOME/bin/java" -cp .mvn/wrapper MavenWrapperDownloader "$wrapperUrl" "$wrapperJarPath") || rm -f "$wrapperJarPath"
fi
fi
fi
fi
##########################################################################################
# End of extension
##########################################################################################
# If specified, validate the SHA-256 sum of the Maven wrapper jar file
wrapperSha256Sum=""
while IFS="=" read -r key value; do
case "$key" in (wrapperSha256Sum) wrapperSha256Sum=$value; break ;;
esac
done < "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.properties"
if [ -n "$wrapperSha256Sum" ]; then
wrapperSha256Result=false
if command -v sha256sum > /dev/null; then
if echo "$wrapperSha256Sum $wrapperJarPath" | sha256sum -c - > /dev/null 2>&1; then
wrapperSha256Result=true
fi
elif command -v shasum > /dev/null; then
if echo "$wrapperSha256Sum $wrapperJarPath" | shasum -a 256 -c > /dev/null 2>&1; then
wrapperSha256Result=true
fi
else
echo "Checksum validation was requested but neither 'sha256sum' or 'shasum' are available." >&2
echo "Please install either command, or disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." >&2
echo "Checksum validation was requested but neither 'sha256sum' or 'shasum' are available."
echo "Please install either command, or disable validation by removing 'wrapperSha256Sum' from your maven-wrapper.properties."
exit 1
fi
if [ $distributionSha256Result = false ]; then
echo "Error: Failed to validate Maven distribution SHA-256, your Maven distribution might be compromised." >&2
echo "If you updated your Maven version, you need to update the specified distributionSha256Sum property." >&2
if [ $wrapperSha256Result = false ]; then
echo "Error: Failed to validate Maven wrapper SHA-256, your Maven wrapper might be compromised." >&2
echo "Investigate or delete $wrapperJarPath to attempt a clean download." >&2
echo "If you updated your Maven version, you need to update the specified wrapperSha256Sum property." >&2
exit 1
fi
fi
# unzip and move
if command -v unzip >/dev/null; then
unzip ${__MVNW_QUIET_UNZIP:+"$__MVNW_QUIET_UNZIP"} "$TMP_DOWNLOAD_DIR/$distributionUrlName" -d "$TMP_DOWNLOAD_DIR" || die "failed to unzip"
else
tar xzf${__MVNW_QUIET_TAR:+"$__MVNW_QUIET_TAR"} "$TMP_DOWNLOAD_DIR/$distributionUrlName" -C "$TMP_DOWNLOAD_DIR" || die "failed to untar"
MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS"
# For Cygwin, switch paths to Windows format before running java
if $cygwin; then
[ -n "$JAVA_HOME" ] &&
JAVA_HOME=$(cygpath --path --windows "$JAVA_HOME")
[ -n "$CLASSPATH" ] &&
CLASSPATH=$(cygpath --path --windows "$CLASSPATH")
[ -n "$MAVEN_PROJECTBASEDIR" ] &&
MAVEN_PROJECTBASEDIR=$(cygpath --path --windows "$MAVEN_PROJECTBASEDIR")
fi
# Find the actual extracted directory name (handles snapshots where filename != directory name)
actualDistributionDir=""
# Provide a "standardized" way to retrieve the CLI args that will
# work with both Windows and non-Windows executions.
MAVEN_CMD_LINE_ARGS="$MAVEN_CONFIG $*"
export MAVEN_CMD_LINE_ARGS
# First try the expected directory name (for regular distributions)
if [ -d "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain" ]; then
if [ -f "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain/bin/$MVN_CMD" ]; then
actualDistributionDir="$distributionUrlNameMain"
fi
fi
WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain
# If not found, search for any directory with the Maven executable (for snapshots)
if [ -z "$actualDistributionDir" ]; then
# enable globbing to iterate over items
set +f
for dir in "$TMP_DOWNLOAD_DIR"/*; do
if [ -d "$dir" ]; then
if [ -f "$dir/bin/$MVN_CMD" ]; then
actualDistributionDir="$(basename "$dir")"
break
fi
fi
done
set -f
fi
if [ -z "$actualDistributionDir" ]; then
verbose "Contents of $TMP_DOWNLOAD_DIR:"
verbose "$(ls -la "$TMP_DOWNLOAD_DIR")"
die "Could not find Maven distribution directory in extracted archive"
fi
verbose "Found extracted Maven distribution directory: $actualDistributionDir"
printf %s\\n "$distributionUrl" >"$TMP_DOWNLOAD_DIR/$actualDistributionDir/mvnw.url"
mv -- "$TMP_DOWNLOAD_DIR/$actualDistributionDir" "$MAVEN_HOME" || [ -d "$MAVEN_HOME" ] || die "fail to move MAVEN_HOME"
clean || :
exec_maven "$@"
# shellcheck disable=SC2086 # safe args
exec "$JAVACMD" \
$MAVEN_OPTS \
$MAVEN_DEBUG_OPTS \
-classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \
"-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \
${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@"
Vendored
+170 -154
View File
@@ -1,4 +1,3 @@
<# : batch portion
@REM ----------------------------------------------------------------------------
@REM Licensed to the Apache Software Foundation (ASF) under one
@REM or more contributor license agreements. See the NOTICE file
@@ -8,7 +7,7 @@
@REM "License"); you may not use this file except in compliance
@REM with the License. You may obtain a copy of the License at
@REM
@REM https://www.apache.org/licenses/LICENSE-2.0
@REM http://www.apache.org/licenses/LICENSE-2.0
@REM
@REM Unless required by applicable law or agreed to in writing,
@REM software distributed under the License is distributed on an
@@ -19,171 +18,188 @@
@REM ----------------------------------------------------------------------------
@REM ----------------------------------------------------------------------------
@REM Apache Maven Wrapper startup batch script, version 3.3.4
@REM Apache Maven Wrapper startup batch script, version 3.2.0
@REM
@REM Required ENV vars:
@REM JAVA_HOME - location of a JDK home dir
@REM
@REM Optional ENV vars
@REM MVNW_REPOURL - repo url base for downloading maven distribution
@REM MVNW_USERNAME/MVNW_PASSWORD - user and password for downloading maven
@REM MVNW_VERBOSE - true: enable verbose log; others: silence the output
@REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands
@REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a keystroke before ending
@REM MAVEN_OPTS - parameters passed to the Java VM when running Maven
@REM e.g. to debug Maven itself, use
@REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000
@REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files
@REM ----------------------------------------------------------------------------
@IF "%__MVNW_ARG0_NAME__%"=="" (SET __MVNW_ARG0_NAME__=%~nx0)
@SET __MVNW_CMD__=
@SET __MVNW_ERROR__=
@SET __MVNW_PSMODULEP_SAVE=%PSModulePath%
@SET PSModulePath=
@FOR /F "usebackq tokens=1* delims==" %%A IN (`powershell -noprofile "& {$scriptDir='%~dp0'; $script='%__MVNW_ARG0_NAME__%'; icm -ScriptBlock ([Scriptblock]::Create((Get-Content -Raw '%~f0'))) -NoNewScope}"`) DO @(
IF "%%A"=="MVN_CMD" (set __MVNW_CMD__=%%B) ELSE IF "%%B"=="" (echo %%A) ELSE (echo %%A=%%B)
@REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on'
@echo off
@REM set title of command window
title %0
@REM enable echoing by setting MAVEN_BATCH_ECHO to 'on'
@if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO%
@REM set %HOME% to equivalent of $HOME
if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%")
@REM Execute a user defined script before this one
if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre
@REM check for pre script, once with legacy .bat ending and once with .cmd ending
if exist "%USERPROFILE%\mavenrc_pre.bat" call "%USERPROFILE%\mavenrc_pre.bat" %*
if exist "%USERPROFILE%\mavenrc_pre.cmd" call "%USERPROFILE%\mavenrc_pre.cmd" %*
:skipRcPre
@setlocal
set ERROR_CODE=0
@REM To isolate internal variables from possible post scripts, we use another setlocal
@setlocal
@REM ==== START VALIDATION ====
if not "%JAVA_HOME%" == "" goto OkJHome
echo.
echo Error: JAVA_HOME not found in your environment. >&2
echo Please set the JAVA_HOME variable in your environment to match the >&2
echo location of your Java installation. >&2
echo.
goto error
:OkJHome
if exist "%JAVA_HOME%\bin\java.exe" goto init
echo.
echo Error: JAVA_HOME is set to an invalid directory. >&2
echo JAVA_HOME = "%JAVA_HOME%" >&2
echo Please set the JAVA_HOME variable in your environment to match the >&2
echo location of your Java installation. >&2
echo.
goto error
@REM ==== END VALIDATION ====
:init
@REM Find the project base dir, i.e. the directory that contains the folder ".mvn".
@REM Fallback to current working directory if not found.
set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR%
IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir
set EXEC_DIR=%CD%
set WDIR=%EXEC_DIR%
:findBaseDir
IF EXIST "%WDIR%"\.mvn goto baseDirFound
cd ..
IF "%WDIR%"=="%CD%" goto baseDirNotFound
set WDIR=%CD%
goto findBaseDir
:baseDirFound
set MAVEN_PROJECTBASEDIR=%WDIR%
cd "%EXEC_DIR%"
goto endDetectBaseDir
:baseDirNotFound
set MAVEN_PROJECTBASEDIR=%EXEC_DIR%
cd "%EXEC_DIR%"
:endDetectBaseDir
IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig
@setlocal EnableExtensions EnableDelayedExpansion
for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a
@endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS%
:endReadAdditionalConfig
SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe"
set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar"
set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain
set WRAPPER_URL="https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.2.0/maven-wrapper-3.2.0.jar"
FOR /F "usebackq tokens=1,2 delims==" %%A IN ("%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties") DO (
IF "%%A"=="wrapperUrl" SET WRAPPER_URL=%%B
)
@SET PSModulePath=%__MVNW_PSMODULEP_SAVE%
@SET __MVNW_PSMODULEP_SAVE=
@SET __MVNW_ARG0_NAME__=
@SET MVNW_USERNAME=
@SET MVNW_PASSWORD=
@IF NOT "%__MVNW_CMD__%"=="" ("%__MVNW_CMD__%" %*)
@echo Cannot start maven from wrapper >&2 && exit /b 1
@GOTO :EOF
: end batch / begin powershell #>
$ErrorActionPreference = "Stop"
if ($env:MVNW_VERBOSE -eq "true") {
$VerbosePreference = "Continue"
}
@REM Extension to allow automatically downloading the maven-wrapper.jar from Maven-central
@REM This allows using the maven wrapper in projects that prohibit checking in binary data.
if exist %WRAPPER_JAR% (
if "%MVNW_VERBOSE%" == "true" (
echo Found %WRAPPER_JAR%
)
) else (
if not "%MVNW_REPOURL%" == "" (
SET WRAPPER_URL="%MVNW_REPOURL%/org/apache/maven/wrapper/maven-wrapper/3.2.0/maven-wrapper-3.2.0.jar"
)
if "%MVNW_VERBOSE%" == "true" (
echo Couldn't find %WRAPPER_JAR%, downloading it ...
echo Downloading from: %WRAPPER_URL%
)
# calculate distributionUrl, requires .mvn/wrapper/maven-wrapper.properties
$distributionUrl = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionUrl
if (!$distributionUrl) {
Write-Error "cannot read distributionUrl property in $scriptDir/.mvn/wrapper/maven-wrapper.properties"
}
powershell -Command "&{"^
"$webclient = new-object System.Net.WebClient;"^
"if (-not ([string]::IsNullOrEmpty('%MVNW_USERNAME%') -and [string]::IsNullOrEmpty('%MVNW_PASSWORD%'))) {"^
"$webclient.Credentials = new-object System.Net.NetworkCredential('%MVNW_USERNAME%', '%MVNW_PASSWORD%');"^
"}"^
"[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; $webclient.DownloadFile('%WRAPPER_URL%', '%WRAPPER_JAR%')"^
"}"
if "%MVNW_VERBOSE%" == "true" (
echo Finished downloading %WRAPPER_JAR%
)
)
@REM End of extension
switch -wildcard -casesensitive ( $($distributionUrl -replace '^.*/','') ) {
"maven-mvnd-*" {
$USE_MVND = $true
$distributionUrl = $distributionUrl -replace '-bin\.[^.]*$',"-windows-amd64.zip"
$MVN_CMD = "mvnd.cmd"
break
}
default {
$USE_MVND = $false
$MVN_CMD = $script -replace '^mvnw','mvn'
break
}
}
@REM If specified, validate the SHA-256 sum of the Maven wrapper jar file
SET WRAPPER_SHA_256_SUM=""
FOR /F "usebackq tokens=1,2 delims==" %%A IN ("%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties") DO (
IF "%%A"=="wrapperSha256Sum" SET WRAPPER_SHA_256_SUM=%%B
)
IF NOT %WRAPPER_SHA_256_SUM%=="" (
powershell -Command "&{"^
"$hash = (Get-FileHash \"%WRAPPER_JAR%\" -Algorithm SHA256).Hash.ToLower();"^
"If('%WRAPPER_SHA_256_SUM%' -ne $hash){"^
" Write-Output 'Error: Failed to validate Maven wrapper SHA-256, your Maven wrapper might be compromised.';"^
" Write-Output 'Investigate or delete %WRAPPER_JAR% to attempt a clean download.';"^
" Write-Output 'If you updated your Maven version, you need to update the specified wrapperSha256Sum property.';"^
" exit 1;"^
"}"^
"}"
if ERRORLEVEL 1 goto error
)
# apply MVNW_REPOURL and calculate MAVEN_HOME
# maven home pattern: ~/.m2/wrapper/dists/{apache-maven-<version>,maven-mvnd-<version>-<platform>}/<hash>
if ($env:MVNW_REPOURL) {
$MVNW_REPO_PATTERN = if ($USE_MVND -eq $False) { "/org/apache/maven/" } else { "/maven/mvnd/" }
$distributionUrl = "$env:MVNW_REPOURL$MVNW_REPO_PATTERN$($distributionUrl -replace "^.*$MVNW_REPO_PATTERN",'')"
}
$distributionUrlName = $distributionUrl -replace '^.*/',''
$distributionUrlNameMain = $distributionUrlName -replace '\.[^.]*$','' -replace '-bin$',''
@REM Provide a "standardized" way to retrieve the CLI args that will
@REM work with both Windows and non-Windows executions.
set MAVEN_CMD_LINE_ARGS=%*
$MAVEN_M2_PATH = "$HOME/.m2"
if ($env:MAVEN_USER_HOME) {
$MAVEN_M2_PATH = "$env:MAVEN_USER_HOME"
}
%MAVEN_JAVA_EXE% ^
%JVM_CONFIG_MAVEN_PROPS% ^
%MAVEN_OPTS% ^
%MAVEN_DEBUG_OPTS% ^
-classpath %WRAPPER_JAR% ^
"-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" ^
%WRAPPER_LAUNCHER% %MAVEN_CONFIG% %*
if ERRORLEVEL 1 goto error
goto end
if (-not (Test-Path -Path $MAVEN_M2_PATH)) {
New-Item -Path $MAVEN_M2_PATH -ItemType Directory | Out-Null
}
:error
set ERROR_CODE=1
$MAVEN_WRAPPER_DISTS = $null
if ((Get-Item $MAVEN_M2_PATH).Target[0] -eq $null) {
$MAVEN_WRAPPER_DISTS = "$MAVEN_M2_PATH/wrapper/dists"
} else {
$MAVEN_WRAPPER_DISTS = (Get-Item $MAVEN_M2_PATH).Target[0] + "/wrapper/dists"
}
:end
@endlocal & set ERROR_CODE=%ERROR_CODE%
$MAVEN_HOME_PARENT = "$MAVEN_WRAPPER_DISTS/$distributionUrlNameMain"
$MAVEN_HOME_NAME = ([System.Security.Cryptography.SHA256]::Create().ComputeHash([byte[]][char[]]$distributionUrl) | ForEach-Object {$_.ToString("x2")}) -join ''
$MAVEN_HOME = "$MAVEN_HOME_PARENT/$MAVEN_HOME_NAME"
if not "%MAVEN_SKIP_RC%"=="" goto skipRcPost
@REM check for post script, once with legacy .bat ending and once with .cmd ending
if exist "%USERPROFILE%\mavenrc_post.bat" call "%USERPROFILE%\mavenrc_post.bat"
if exist "%USERPROFILE%\mavenrc_post.cmd" call "%USERPROFILE%\mavenrc_post.cmd"
:skipRcPost
if (Test-Path -Path "$MAVEN_HOME" -PathType Container) {
Write-Verbose "found existing MAVEN_HOME at $MAVEN_HOME"
Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD"
exit $?
}
@REM pause the script if MAVEN_BATCH_PAUSE is set to 'on'
if "%MAVEN_BATCH_PAUSE%"=="on" pause
if (! $distributionUrlNameMain -or ($distributionUrlName -eq $distributionUrlNameMain)) {
Write-Error "distributionUrl is not valid, must end with *-bin.zip, but found $distributionUrl"
}
if "%MAVEN_TERMINATE_CMD%"=="on" exit %ERROR_CODE%
# prepare tmp dir
$TMP_DOWNLOAD_DIR_HOLDER = New-TemporaryFile
$TMP_DOWNLOAD_DIR = New-Item -Itemtype Directory -Path "$TMP_DOWNLOAD_DIR_HOLDER.dir"
$TMP_DOWNLOAD_DIR_HOLDER.Delete() | Out-Null
trap {
if ($TMP_DOWNLOAD_DIR.Exists) {
try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null }
catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" }
}
}
New-Item -Itemtype Directory -Path "$MAVEN_HOME_PARENT" -Force | Out-Null
# Download and Install Apache Maven
Write-Verbose "Couldn't find MAVEN_HOME, downloading and installing it ..."
Write-Verbose "Downloading from: $distributionUrl"
Write-Verbose "Downloading to: $TMP_DOWNLOAD_DIR/$distributionUrlName"
$webclient = New-Object System.Net.WebClient
if ($env:MVNW_USERNAME -and $env:MVNW_PASSWORD) {
$webclient.Credentials = New-Object System.Net.NetworkCredential($env:MVNW_USERNAME, $env:MVNW_PASSWORD)
}
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
$webclient.DownloadFile($distributionUrl, "$TMP_DOWNLOAD_DIR/$distributionUrlName") | Out-Null
# If specified, validate the SHA-256 sum of the Maven distribution zip file
$distributionSha256Sum = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionSha256Sum
if ($distributionSha256Sum) {
if ($USE_MVND) {
Write-Error "Checksum validation is not supported for maven-mvnd. `nPlease disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties."
}
Import-Module $PSHOME\Modules\Microsoft.PowerShell.Utility -Function Get-FileHash
if ((Get-FileHash "$TMP_DOWNLOAD_DIR/$distributionUrlName" -Algorithm SHA256).Hash.ToLower() -ne $distributionSha256Sum) {
Write-Error "Error: Failed to validate Maven distribution SHA-256, your Maven distribution might be compromised. If you updated your Maven version, you need to update the specified distributionSha256Sum property."
}
}
# unzip and move
Expand-Archive "$TMP_DOWNLOAD_DIR/$distributionUrlName" -DestinationPath "$TMP_DOWNLOAD_DIR" | Out-Null
# Find the actual extracted directory name (handles snapshots where filename != directory name)
$actualDistributionDir = ""
# First try the expected directory name (for regular distributions)
$expectedPath = Join-Path "$TMP_DOWNLOAD_DIR" "$distributionUrlNameMain"
$expectedMvnPath = Join-Path "$expectedPath" "bin/$MVN_CMD"
if ((Test-Path -Path $expectedPath -PathType Container) -and (Test-Path -Path $expectedMvnPath -PathType Leaf)) {
$actualDistributionDir = $distributionUrlNameMain
}
# If not found, search for any directory with the Maven executable (for snapshots)
if (!$actualDistributionDir) {
Get-ChildItem -Path "$TMP_DOWNLOAD_DIR" -Directory | ForEach-Object {
$testPath = Join-Path $_.FullName "bin/$MVN_CMD"
if (Test-Path -Path $testPath -PathType Leaf) {
$actualDistributionDir = $_.Name
}
}
}
if (!$actualDistributionDir) {
Write-Error "Could not find Maven distribution directory in extracted archive"
}
Write-Verbose "Found extracted Maven distribution directory: $actualDistributionDir"
Rename-Item -Path "$TMP_DOWNLOAD_DIR/$actualDistributionDir" -NewName $MAVEN_HOME_NAME | Out-Null
try {
Move-Item -Path "$TMP_DOWNLOAD_DIR/$MAVEN_HOME_NAME" -Destination $MAVEN_HOME_PARENT | Out-Null
} catch {
if (! (Test-Path -Path "$MAVEN_HOME" -PathType Container)) {
Write-Error "fail to move MAVEN_HOME"
}
} finally {
try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null }
catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" }
}
Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD"
cmd /C exit /B %ERROR_CODE%
+74 -105
View File
@@ -45,59 +45,58 @@
</modules>
<properties>
<aws.sdk2.version>2.54.7</aws.sdk2.version>
<braintree.version>3.53.0</braintree.version>
<aws.sdk2.version>2.42.27</aws.sdk2.version>
<braintree.version>3.48.0</braintree.version>
<commons-csv.version>1.14.1</commons-csv.version>
<commons-io.version>2.22.0</commons-io.version>
<dropwizard.version>5.0.2</dropwizard.version>
<commons-io.version>2.21.0</commons-io.version>
<dropwizard.version>5.0.1</dropwizard.version>
<!-- Note: We use x86_64 builds without AVX instructions enabled (i.e. FoundationDB versions with even-numbered
patch versions). -->
<foundationdb.version>7.3.76</foundationdb.version>
patch versions). Also when updating FoundationDB, make sure to update the version of FoundationDBused by GitHub
Actions. -->
<foundationdb.version>7.3.68</foundationdb.version>
<foundationdb.api-version>730</foundationdb.api-version>
<foundationdb.client-library-sha256>af099848721d08904ff9e5d38fade0de24d92e86451ea491d9ab5ce84adcf62a</foundationdb.client-library-sha256>
<google-cloud-libraries.version>26.87.0</google-cloud-libraries.version>
<foundationdb.client-library-sha256>8c96a1f7ab561cd38e16e4c269c5e50ae0fd8063854e0d72c89339a7ac1b6873</foundationdb.client-library-sha256>
<google-cloud-libraries.version>26.79.0</google-cloud-libraries.version>
<grpc.version>1.76.3</grpc.version> <!-- should be kept in sync with the value from Google libraries-bom -->
<gson.version>2.14.0</gson.version>
<guava.version>33.7.1-jre</guava.version>
<gson.version>2.13.2</gson.version>
<guava.version>33.5.0-jre</guava.version>
<!-- several libraries (AWS, Google Cloud) use Apache http components transitively, and we need to align them -->
<httpcore.version>4.4.16</httpcore.version>
<httpclient.version>4.5.14</httpclient.version>
<jackson.version>2.22.2</jackson.version>
<java-otp.version>1.0.0</java-otp.version>
<jetty.version>12.1.9</jetty.version>
<jackson.version>2.21.2</jackson.version>
<junit-pioneer.version>2.3.0</junit-pioneer.version>
<jsr305.version>3.0.2</jsr305.version>
<kotlin.version>2.4.10</kotlin.version>
<!-- dropwizard references a constant removed in 1.6. See also: dependabot.yml -->
<kotlin.version>2.3.20</kotlin.version>
<logback.version>1.5.38</logback.version>
<logback-access-common.version>2.0.15</logback-access-common.version>
<lettuce.version>7.6.0.RELEASE</lettuce.version>
<libphonenumber.version>9.0.38</libphonenumber.version>
<logstash.logback.version>9.0</logstash.logback.version>
<log4j-bom.version>2.26.1</log4j-bom.version>
<luajava.version>4.1.0</luajava.version>
<micrometer.version>1.17.1</micrometer.version>
<netty.version>4.2.17.Final</netty.version>
<!-- must be greater than or equal to the value from Google libraries-bom, see https://protobuf.dev/support/cross-version-runtime-guarantee/ -->
<!-- the latest 4.x should be fine https://central.sonatype.com/artifact/com.google.protobuf/protobuf-java/versions -->
<protobuf.version>4.36.0</protobuf.version>
<pushy.version>0.15.6</pushy.version>
<reactor-bom.version>2025.0.7</reactor-bom.version> <!-- 3.8.4, see https://github.com/reactor/reactor#bom-versioning-scheme -->
<logback-access-common.version>2.0.12</logback-access-common.version>
<lettuce.version>7.5.1.RELEASE</lettuce.version>
<libphonenumber.version>9.0.21</libphonenumber.version>
<logstash.logback.version>8.1</logstash.logback.version>
<log4j-bom.version>2.25.4</log4j-bom.version>
<luajava.version>3.5.0</luajava.version>
<micrometer.version>1.16.4</micrometer.version>
<netty.version>4.2.13.Final</netty.version>
<!-- Must be less than or equal to the value from Google libraries-bom which controls the protobuf runtime version.
See https://protobuf.dev/support/cross-version-runtime-guarantee/. -->
<protoc.version>4.33.2</protoc.version>
<pushy.version>0.15.4</pushy.version>
<reactor-bom.version>2025.0.4</reactor-bom.version> <!-- 3.8.4, see https://github.com/reactor/reactor#bom-versioning-scheme -->
<resilience4j.version>2.4.0</resilience4j.version>
<semver4j.version>3.1.0</semver4j.version>
<simple-grpc.version>0.2.1</simple-grpc.version>
<slf4j.version>2.0.18</slf4j.version>
<stripe.version>33.4.0</stripe.version>
<swagger.version>2.2.54</swagger.version>
<testcontainers.version>2.0.5</testcontainers.version>
<simple-grpc.version>0.2.0</simple-grpc.version>
<slf4j.version>2.0.17</slf4j.version>
<stripe.version>33.1.0</stripe.version>
<swagger.version>2.2.46</swagger.version>
<testcontainers.version>2.0.4</testcontainers.version>
<!-- images to use in tests via testcontainers -->
<dynamodb.image>amazon/dynamodb-local:3.3.1@sha256:ff89bd48ff32cd8d9be5fee8873b65b8854dc408f1afe881be6eb00247bc0dab</dynamodb.image>
<localstack.image>localstack/localstack:4.14@sha256:3ebc37595918b8accb852f8048fef2aff047d465167edd655528065b07bc364a</localstack.image>
<redis.image>redis:7.4-alpine@sha256:6ab0b6e7381779332f97b8ca76193e45b0756f38d4c0dcda72dbb3c32061ab99</redis.image>
<dynamodb.image>amazon/dynamodb-local:3.3.0@sha256:d89f8fcc6b1a39cb35976c248ed42a28c66ae00dc043099210f5571e42648ab4</dynamodb.image>
<localstack.image>localstack/localstack:4.13@sha256:46302bcb91a7e8008e6394be8afafdbfa40fb77a54d4046a38be35992042d5de</localstack.image>
<redis.image>redis:7.4-alpine@sha256:af1d0fc3f63b02b13ff7906c9baf7c5b390b8881ca08119cd570677fe2f60b55</redis.image>
<redis-cluster.image>docker.io/bitnamilegacy/redis-cluster:7.4.3@sha256:a53d023fdfaf8a8d7ddc58da040d3494e4cb45772644618ffa44c42dcd32b9af</redis-cluster.image>
<docker.image>eclipse-temurin:26-jre-resolute@sha256:c3b6e31e48772c98e8868654e5f21fb2c3670e67c055ddd76d8cf37e62113eb5</docker.image>
<!-- eclipse-temurin:25.0.2_10-jre-noble (note: always use the multi-arch manifest *LIST* here) -->
<docker.image.sha256>d2975fcad8dc9ac2180c0c278c8ae7b3443d36cb80845cb0811c20d9463f5fee</docker.image.sha256>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
@@ -107,9 +106,7 @@
<version>JGITVER</version>
<dependencyManagement>
<!-- note: order matters, and earlier declarations take precedence -->
<dependencies>
<!-- use a pinned version of jackson, rather than Dropwizard's BOM -->
<dependency>
<groupId>com.fasterxml.jackson</groupId>
<artifactId>jackson-bom</artifactId>
@@ -117,50 +114,6 @@
<type>pom</type>
<scope>import</scope>
</dependency>
<!-- use a pinned version of jetty, rather than Dropwizard's BOM -->
<dependency>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-bom</artifactId>
<version>${jetty.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<!-- use a pinned version of jetty, rather than Dropwizard's BOM -->
<dependency>
<groupId>org.eclipse.jetty.ee10</groupId>
<artifactId>jetty-ee10-bom</artifactId>
<version>${jetty.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-bom</artifactId>
<version>${netty.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<dependency>
<groupId>com.google.protobuf</groupId>
<artifactId>protobuf-bom</artifactId>
<type>pom</type>
<scope>import</scope>
<version>${protobuf.version}</version>
</dependency>
<dependency>
<groupId>com.google.cloud</groupId>
<artifactId>libraries-bom</artifactId>
<version>${google-cloud-libraries.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<dependency>
<groupId>software.amazon.awssdk</groupId>
<artifactId>bom</artifactId>
<version>${aws.sdk2.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<dependency>
<groupId>io.dropwizard</groupId>
<artifactId>dropwizard-dependencies</artifactId>
@@ -175,6 +128,27 @@
<version>6.0.53</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-bom</artifactId>
<version>${netty.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<dependency>
<groupId>software.amazon.awssdk</groupId>
<artifactId>bom</artifactId>
<version>${aws.sdk2.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<dependency>
<groupId>com.google.cloud</groupId>
<artifactId>libraries-bom</artifactId>
<version>${google-cloud-libraries.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<dependency>
<groupId>io.github.resilience4j</groupId>
<artifactId>resilience4j-bom</artifactId>
@@ -192,14 +166,14 @@
<dependency>
<groupId>io.opentelemetry</groupId>
<artifactId>opentelemetry-bom</artifactId>
<version>1.65.0</version>
<version>1.60.1</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<dependency>
<groupId>io.opentelemetry.instrumentation</groupId>
<artifactId>opentelemetry-instrumentation-bom</artifactId>
<version>2.31.1</version>
<version>2.26.1</version>
<type>pom</type>
<scope>import</scope>
</dependency>
@@ -217,11 +191,6 @@
<type>pom</type>
<scope>import</scope>
</dependency>
<dependency>
<groupId>com.eatthepath</groupId>
<artifactId>java-otp</artifactId>
<version>${java-otp.version}</version>
</dependency>
<dependency>
<groupId>com.eatthepath</groupId>
<artifactId>pushy</artifactId>
@@ -281,7 +250,7 @@
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.4.0</version>
<version>1.3.6</version>
</dependency>
<dependency>
<groupId>com.stripe</groupId>
@@ -317,7 +286,7 @@
<dependency>
<groupId>org.signal</groupId>
<artifactId>libsignal-server</artifactId>
<version>0.101.2</version>
<version>0.96.2</version>
</dependency>
<dependency>
<groupId>org.signal</groupId>
@@ -386,7 +355,7 @@
<dependency>
<groupId>org.wiremock</groupId>
<artifactId>wiremock-jetty12</artifactId>
<version>3.13.2</version>
<version>3.13.1</version>
<scope>test</scope>
</dependency>
<dependency>
@@ -454,32 +423,32 @@
<plugin>
<groupId>com.google.cloud.tools</groupId>
<artifactId>jib-maven-plugin</artifactId>
<version>3.5.2</version>
<version>3.4.6</version>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>3.5.6</version>
<version>3.5.5</version>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-failsafe-plugin</artifactId>
<version>3.5.6</version>
<version>3.5.4</version>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>3.5.1</version>
<version>3.5.0</version>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>3.6.2</version>
<version>3.6.1</version>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-assembly-plugin</artifactId>
<version>3.8.0</version>
<version>3.7.1</version>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
@@ -489,7 +458,7 @@
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>properties-maven-plugin</artifactId>
<version>1.3.0</version>
<version>1.2.1</version>
</plugin>
</plugins>
</pluginManagement>
@@ -501,7 +470,7 @@
<version>0.6.1</version>
<configuration>
<checkStaleness>false</checkStaleness>
<protocArtifact>com.google.protobuf:protoc:${protobuf.version}:exe:${os.detected.classifier}</protocArtifact>
<protocArtifact>com.google.protobuf:protoc:${protoc.version}:exe:${os.detected.classifier}</protocArtifact>
<pluginId>grpc-java</pluginId>
<pluginArtifact>io.grpc:protoc-gen-grpc-java:${grpc.version}:exe:${os.detected.classifier}</pluginArtifact>
@@ -532,14 +501,14 @@
<artifactId>maven-compiler-plugin</artifactId>
<version>3.15.0</version>
<configuration>
<release>26</release>
<release>25</release>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>3.5.1</version>
<version>3.5.0</version>
<configuration>
<archive>
<manifest>
@@ -552,7 +521,7 @@
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<version>3.11.0</version>
<version>3.10.0</version>
<executions>
<execution>
<!--
@@ -572,7 +541,7 @@
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-enforcer-plugin</artifactId>
<version>3.6.3</version>
<version>3.6.2</version>
<executions>
<execution>
<goals>
+1 -2
View File
@@ -79,8 +79,7 @@ storageService.userAuthenticationTokenSharedSecret: AAAAAAAAAAAAAAAAAAAAAAAAAAAA
zkConfig-libsignal-0.42.serverSecret: ABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdef
callingZkConfigPreV101.serverSecret: ABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzAA==
callingZkConfigV101.serverSecret: ABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzAA==
callingZkConfig.serverSecret: ABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzAA==
chatZkConfig.serverSecret: ABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzAA==
paymentsService.userAuthenticationTokenSharedSecret: AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA= # base64-encoded 32-byte secret shared with MobileCoin services used to generate auth tokens for Signal users
+8 -11
View File
@@ -74,6 +74,7 @@ appleDeviceCheck:
deviceCheck:
backupRedemptionDuration: P30D
backupRedemptionLevel: 201
dynamoDbClient:
region: us-west-2 # AWS Region
@@ -104,8 +105,9 @@ dynamoDbTables:
expiration: P7D # Duration of time until rows expire
issuedReceipts:
tableName: Example_IssuedReceipts
expiration: P30D # Duration of time until rows expire
generator: abcdefg12345678= # random base64-encoded binary sequence
maxReceiptsPerSubscriptionPayment:
maxIssuedReceiptsPerPaymentId:
STRIPE: 1
BRAINTREE: 1
GOOGLE_PLAY_BILLING: 1
@@ -138,6 +140,7 @@ dynamoDbTables:
tableName: Example_PushNotificationExperimentSamples
redeemedReceipts:
tableName: Example_RedeemedReceipts
expiration: P30D # Duration of time until rows expire
registrationRecovery:
tableName: Example_RegistrationRecovery
expiration: P300D # Duration of time until rows expire
@@ -315,11 +318,8 @@ storageService:
AAAAAAAAAAAAAAAAAAAA
-----END CERTIFICATE-----
callingZkConfigPreV101:
serverSecret: secret://callingZkConfigPreV101.serverSecret
callingZkConfig:
serverSecret: secret://callingZkConfigV101.serverSecret
serverSecret: secret://callingZkConfig.serverSecret
chatZkConfig:
serverSecret: secret://chatZkConfig.serverSecret
@@ -366,7 +366,7 @@ badges:
- light: example-light.svg
dark: example-dark.svg
receiptLevels:
ONE_TIME_DONATION: TEST
'1': TEST
subscription: # configuration for Stripe subscriptions
badgeExpiration: P30D
@@ -385,17 +385,14 @@ subscription: # configuration for Stripe subscriptions
STRIPE: price_example # stripe Price ID
BRAINTREE: plan_example # braintree Plan ID
loginPurchase:
playProductId: login_example
playOptionId: login_option_example
appStoreProductId: login_example
oneTimeDonations:
sepaMaximumEuros: '10000'
boost:
level: 1
expiration: P90D
badge: EXAMPLE
gift:
level: 10
expiration: P90D
badge: EXAMPLE
currencies:
+21 -52
View File
@@ -11,18 +11,19 @@
<artifactId>service</artifactId>
<properties>
<apollo-api-jvm.version>3.8.6</apollo-api-jvm.version>
<apollo-api-jvm.version>3.8.5</apollo-api-jvm.version>
<commons-compress.version>1.28.0</commons-compress.version>
<dynamodb-lock-client.version>1.5.0</dynamodb-lock-client.version>
<firebase-admin.version>9.10.0</firebase-admin.version>
<libphonenumber-geocoder.version>3.38</libphonenumber-geocoder.version>
<dynamodb-lock-client.version>1.4.0</dynamodb-lock-client.version>
<firebase-admin.version>9.7.0</firebase-admin.version>
<libphonenumber-geocoder.version>3.23</libphonenumber-geocoder.version>
<google-androidpublisher.version>v3-rev20250904-2.0.0</google-androidpublisher.version>
<java-jwt.version>4.6.0</java-jwt.version>
<java-jwt.version>4.5.0</java-jwt.version>
<java-uuid-generator.version>5.2.0</java-uuid-generator.version>
<!-- *all* opentelemetry-logback-appender versions are "alpha" despite the advanced version number -->
<opentelemetry-logback-appender-1.0.version>2.31.1-alpha</opentelemetry-logback-appender-1.0.version>
<storekit.version>5.2.0</storekit.version>
<webauthn4j.version>0.31.9.RELEASE</webauthn4j.version>
<opentelemetry-logback-appender-1.0.version>2.22.0-alpha</opentelemetry-logback-appender-1.0.version>
<storekit.version>4.0.0</storekit.version>
<webauthn4j.version>0.30.2.RELEASE</webauthn4j.version>
<jetty.http2-client.version>12.1.5</jetty.http2-client.version>
</properties>
<dependencies>
@@ -46,11 +47,6 @@
<groupId>com.squareup.okio</groupId>
<artifactId>okio-jvm</artifactId>
</exclusion>
<!-- conflicts with our direct dependency -->
<exclusion>
<groupId>com.auth0</groupId>
<artifactId>java-jwt</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
@@ -146,6 +142,7 @@
<groupId>org.eclipse.jetty.http2</groupId>
<artifactId>jetty-http2-client-transport</artifactId>
<scope>test</scope>
<version>${jetty.http2-client.version}</version>
</dependency>
<dependency>
<groupId>io.dropwizard</groupId>
@@ -176,20 +173,6 @@
<dependency>
<groupId>net.logstash.logback</groupId>
<artifactId>logstash-logback-encoder</artifactId>
<exclusions>
<!-- conflicts with webauthn4j-appattest -->
<exclusion>
<groupId>tools.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
</exclusion>
</exclusions>
</dependency>
<!-- sentinel for dependency convergence -->
<dependency>
<groupId>tools.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<!-- update dependabot.yml when this dependency is removed -->
<version>3.2.1</version>
</dependency>
<dependency>
@@ -301,11 +284,16 @@
<groupId>com.google.firebase</groupId>
<artifactId>firebase-admin</artifactId>
<version>${firebase-admin.version}</version>
</dependency>
<dependency>
<groupId>com.google.cloud</groupId>
<artifactId>google-cloud-firestore</artifactId>
<exclusions>
<!-- incubator packages aren't included in the opentelemetry BOM, and we don't use them -->
<exclusion>
<!-- conflicts with jackson-dataformat 2.22.1 -->
<groupId>org.codehaus.woodstox</groupId>
<artifactId>stax2-api</artifactId>
<groupId>io.opentelemetry.instrumentation</groupId>
<artifactId>opentelemetry-instrumentation-api-incubator</artifactId>
</exclusion>
</exclusions>
</dependency>
@@ -315,13 +303,6 @@
<artifactId>jsr305</artifactId>
</dependency>
<dependency>
<!-- manually resolve dependency conflict -->
<groupId>org.codehaus.woodstox</groupId>
<artifactId>stax2-api</artifactId>
<version>4.3.0</version>
</dependency>
<dependency>
<groupId>io.github.resilience4j</groupId>
<artifactId>resilience4j-circuitbreaker</artifactId>
@@ -423,11 +404,6 @@
<artifactId>lettuce-core</artifactId>
</dependency>
<dependency>
<groupId>com.eatthepath</groupId>
<artifactId>java-otp</artifactId>
</dependency>
<dependency>
<groupId>com.eatthepath</groupId>
<artifactId>pushy</artifactId>
@@ -516,12 +492,6 @@
<classifier>linux-x86_64</classifier>
</dependency>
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-pkitesting</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-testsuite-common</artifactId>
@@ -640,8 +610,7 @@
<dependency>
<groupId>com.squareup.okio</groupId>
<artifactId>okio-jvm</artifactId>
<!-- update dependabot.yml when this dependency is removed -->
<version>3.17.0</version>
<version>3.16.4</version>
</dependency>
</dependencies>
@@ -757,7 +726,7 @@
</executions>
<configuration>
<from>
<image>${docker.image}</image>
<image>eclipse-temurin@sha256:${docker.image.sha256}</image>
<platforms>
<platform>
<architecture>amd64</architecture>
@@ -856,7 +825,7 @@
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>templating-maven-plugin</artifactId>
<version>3.1.0</version>
<version>3.0.0</version>
<executions>
<execution>
<id>filter-src</id>
@@ -44,7 +44,6 @@ import org.whispersystems.textsecuregcm.configuration.HlrLookupConfiguration;
import org.whispersystems.textsecuregcm.configuration.IdlePrimaryDeviceReminderConfiguration;
import org.whispersystems.textsecuregcm.configuration.KeyTransparencyServiceConfiguration;
import org.whispersystems.textsecuregcm.configuration.LinkDeviceSecretConfiguration;
import org.whispersystems.textsecuregcm.configuration.LoginPurchaseConfiguration;
import org.whispersystems.textsecuregcm.configuration.MessageByteLimitCardinalityEstimatorConfiguration;
import org.whispersystems.textsecuregcm.configuration.MessageCacheConfiguration;
import org.whispersystems.textsecuregcm.configuration.OneTimeDonationConfiguration;
@@ -63,7 +62,6 @@ import org.whispersystems.textsecuregcm.configuration.SpamFilterConfiguration;
import org.whispersystems.textsecuregcm.configuration.StripeConfiguration;
import org.whispersystems.textsecuregcm.configuration.SubscriptionConfiguration;
import org.whispersystems.textsecuregcm.configuration.TlsKeyStoreConfiguration;
import org.whispersystems.textsecuregcm.configuration.TotpConfiguration;
import org.whispersystems.textsecuregcm.configuration.TurnConfiguration;
import org.whispersystems.textsecuregcm.configuration.UnidentifiedDeliveryConfiguration;
import org.whispersystems.textsecuregcm.configuration.VirtualThreadConfiguration;
@@ -228,11 +226,6 @@ public class WhisperServerConfiguration extends Configuration {
@JsonProperty
private PaymentsServiceConfiguration paymentsService;
@Valid
@NotNull
@JsonProperty
private GenericZkConfig callingZkConfigPreV101;
@Valid
@NotNull
@JsonProperty
@@ -273,11 +266,6 @@ public class WhisperServerConfiguration extends Configuration {
@NotNull
private OneTimeDonationConfiguration oneTimeDonations;
@Valid
@JsonProperty
@NotNull
private LoginPurchaseConfiguration loginPurchase;
@Valid
@JsonProperty
@NotNull
@@ -385,11 +373,6 @@ public class WhisperServerConfiguration extends Configuration {
@JsonProperty
private FoundationDbMessagesConfiguration foundationDbMessages;
@Valid
@NotNull
@JsonProperty
private TotpConfiguration registrationTotp = TotpConfiguration.DEFAULT;
public TlsKeyStoreConfiguration getTlsKeyStoreConfiguration() {
return tlsKeyStore;
}
@@ -519,11 +502,6 @@ public class WhisperServerConfiguration extends Configuration {
return chatZkConfig;
}
/// ZK secret shared with Calling Service
public GenericZkConfig getCallingZkConfigPreV101() {
return callingZkConfigPreV101;
}
/// ZK secret shared with Calling Service
public GenericZkConfig getCallingZkConfig() {
return callingZkConfig;
@@ -554,10 +532,6 @@ public class WhisperServerConfiguration extends Configuration {
return oneTimeDonations;
}
public LoginPurchaseConfiguration getLoginPurchase() {
return loginPurchase;
}
public PagedSingleUseKEMPreKeyStoreConfiguration getPagedSingleUseKEMPreKeyStore() {
return pagedSingleUseKEMPreKeyStore;
}
@@ -649,8 +623,4 @@ public class WhisperServerConfiguration extends Configuration {
public FoundationDbMessagesConfiguration getFoundationDbMessagesConfiguration() {
return foundationDbMessages;
}
public TotpConfiguration getRegistrationTotpConfiguration() {
return registrationTotp;
}
}
@@ -110,8 +110,6 @@ import org.whispersystems.textsecuregcm.captcha.CaptchaChecker;
import org.whispersystems.textsecuregcm.captcha.CaptchaClient;
import org.whispersystems.textsecuregcm.captcha.RegistrationCaptchaManager;
import org.whispersystems.textsecuregcm.captcha.ShortCodeExpander;
import org.whispersystems.textsecuregcm.configuration.BadgeConfiguration;
import org.whispersystems.textsecuregcm.configuration.FoundationDbExternalClientConfiguration;
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
import org.whispersystems.textsecuregcm.configuration.secrets.SecretStore;
import org.whispersystems.textsecuregcm.configuration.secrets.SecretsModule;
@@ -131,7 +129,6 @@ import org.whispersystems.textsecuregcm.controllers.DonationController;
import org.whispersystems.textsecuregcm.controllers.KeepAliveController;
import org.whispersystems.textsecuregcm.controllers.KeyTransparencyController;
import org.whispersystems.textsecuregcm.controllers.KeysController;
import org.whispersystems.textsecuregcm.controllers.LoginPurchaseController;
import org.whispersystems.textsecuregcm.controllers.MessageController;
import org.whispersystems.textsecuregcm.controllers.OneTimeDonationController;
import org.whispersystems.textsecuregcm.controllers.PaymentsController;
@@ -173,10 +170,8 @@ import org.whispersystems.textsecuregcm.grpc.ErrorMappingInterceptor;
import org.whispersystems.textsecuregcm.grpc.ExternalServiceDefinitions;
import org.whispersystems.textsecuregcm.grpc.GroupSendTokenUtil;
import org.whispersystems.textsecuregcm.grpc.GrpcAllowListInterceptor;
import org.whispersystems.textsecuregcm.grpc.KeyTransparencyGrpcService;
import org.whispersystems.textsecuregcm.grpc.KeysAnonymousGrpcService;
import org.whispersystems.textsecuregcm.grpc.KeysGrpcService;
import org.whispersystems.textsecuregcm.grpc.LoginPurchaseGrpcService;
import org.whispersystems.textsecuregcm.grpc.MessageDispatcher;
import org.whispersystems.textsecuregcm.grpc.MessagesAnonymousGrpcService;
import org.whispersystems.textsecuregcm.grpc.MessagesGrpcService;
@@ -186,7 +181,6 @@ import org.whispersystems.textsecuregcm.grpc.PaymentsGrpcService;
import org.whispersystems.textsecuregcm.grpc.ProductConfigurationGrpcService;
import org.whispersystems.textsecuregcm.grpc.ProfileAnonymousGrpcService;
import org.whispersystems.textsecuregcm.grpc.ProfileGrpcService;
import org.whispersystems.textsecuregcm.grpc.RemoteConfigurationGrpcService;
import org.whispersystems.textsecuregcm.grpc.RequestAttributesInterceptor;
import org.whispersystems.textsecuregcm.grpc.SubscriptionsGrpcService;
import org.whispersystems.textsecuregcm.grpc.ValidatingInterceptor;
@@ -208,8 +202,8 @@ import org.whispersystems.textsecuregcm.limits.RedisMessageDeliveryLoopMonitor;
import org.whispersystems.textsecuregcm.mappers.BackupExceptionMapper;
import org.whispersystems.textsecuregcm.mappers.CompletionExceptionMapper;
import org.whispersystems.textsecuregcm.mappers.DeviceLimitExceededExceptionMapper;
import org.whispersystems.textsecuregcm.mappers.GrpcStatusRuntimeExceptionMapper;
import org.whispersystems.textsecuregcm.mappers.IOExceptionMapper;
import org.whispersystems.textsecuregcm.mappers.IllegalStateExceptionMapper;
import org.whispersystems.textsecuregcm.mappers.ImpossiblePhoneNumberExceptionMapper;
import org.whispersystems.textsecuregcm.mappers.InvalidWebsocketAddressExceptionMapper;
import org.whispersystems.textsecuregcm.mappers.JsonMappingExceptionMapper;
@@ -273,14 +267,14 @@ import org.whispersystems.textsecuregcm.storage.OneTimeDonationsManager;
import org.whispersystems.textsecuregcm.storage.PagedSingleUseKEMPreKeyStore;
import org.whispersystems.textsecuregcm.storage.PersistentTimer;
import org.whispersystems.textsecuregcm.storage.PhoneNumberIdentifiers;
import org.whispersystems.textsecuregcm.storage.PhoneNumberRecoveryPasswords;
import org.whispersystems.textsecuregcm.storage.PhoneNumberRecoveryPasswordsManager;
import org.whispersystems.textsecuregcm.storage.ProfileAvatars;
import org.whispersystems.textsecuregcm.storage.Profiles;
import org.whispersystems.textsecuregcm.storage.ProfilesManager;
import org.whispersystems.textsecuregcm.storage.ProfilesV2;
import org.whispersystems.textsecuregcm.storage.PushChallengeDynamoDb;
import org.whispersystems.textsecuregcm.storage.RedeemedReceiptsManager;
import org.whispersystems.textsecuregcm.storage.RegistrationRecoveryPasswords;
import org.whispersystems.textsecuregcm.storage.RegistrationRecoveryPasswordsManager;
import org.whispersystems.textsecuregcm.storage.RemoteConfigs;
import org.whispersystems.textsecuregcm.storage.RemoteConfigsManager;
import org.whispersystems.textsecuregcm.storage.RepeatedUseECSignedPreKeyStore;
@@ -295,18 +289,14 @@ import org.whispersystems.textsecuregcm.storage.VerificationSessions;
import org.whispersystems.textsecuregcm.storage.devicecheck.AppleDeviceCheckManager;
import org.whispersystems.textsecuregcm.storage.devicecheck.AppleDeviceCheckTrustAnchor;
import org.whispersystems.textsecuregcm.storage.devicecheck.AppleDeviceChecks;
import org.whispersystems.textsecuregcm.storage.foundationdb.FaultTolerantDatabase;
import org.whispersystems.textsecuregcm.storage.foundationdb.FoundationDbMessageStore;
import org.whispersystems.textsecuregcm.storage.foundationdb.FoundationDBWarmup;
import org.whispersystems.textsecuregcm.storage.foundationdb.VersionstampUUIDCipher;
import org.whispersystems.textsecuregcm.subscriptions.AppleAppStoreClient;
import org.whispersystems.textsecuregcm.subscriptions.AppleAppStoreManager;
import org.whispersystems.textsecuregcm.subscriptions.BankMandateTranslator;
import org.whispersystems.textsecuregcm.subscriptions.BraintreeManager;
import org.whispersystems.textsecuregcm.subscriptions.GooglePlayBillingManager;
import org.whispersystems.textsecuregcm.subscriptions.LoginPurchaseManager;
import org.whispersystems.textsecuregcm.subscriptions.PayPalDonationsTranslator;
import org.whispersystems.textsecuregcm.subscriptions.PaymentProvider;
import org.whispersystems.textsecuregcm.subscriptions.StripeManager;
import org.whispersystems.textsecuregcm.telephony.CarrierDataProvider;
import org.whispersystems.textsecuregcm.telephony.hlrlookup.HlrLookupCarrierDataProvider;
@@ -330,7 +320,6 @@ import org.whispersystems.textsecuregcm.workers.CertificateCommand;
import org.whispersystems.textsecuregcm.workers.CheckDynamicConfigurationCommand;
import org.whispersystems.textsecuregcm.workers.ClearExpiredFoundationDbMessagesCommand;
import org.whispersystems.textsecuregcm.workers.ClearIssuedReceiptRedemptionsCommand;
import org.whispersystems.textsecuregcm.workers.ClearOrphanedFoundationDbQueuesCommand;
import org.whispersystems.textsecuregcm.workers.CopyToS3Command;
import org.whispersystems.textsecuregcm.workers.DeleteUserCommand;
import org.whispersystems.textsecuregcm.workers.IdleDeviceNotificationSchedulerFactory;
@@ -347,7 +336,6 @@ import org.whispersystems.textsecuregcm.workers.ScheduledApnPushNotificationSend
import org.whispersystems.textsecuregcm.workers.ServerVersionCommand;
import org.whispersystems.textsecuregcm.workers.SetRequestLoggingEnabledTask;
import org.whispersystems.textsecuregcm.workers.SetUserDiscoverabilityCommand;
import org.whispersystems.textsecuregcm.workers.TrimOversizedFoundationDbMessageQueuesCommand;
import org.whispersystems.textsecuregcm.workers.UnlinkDeviceCommand;
import org.whispersystems.textsecuregcm.workers.UnlinkDevicesWithIdlePrimaryCommand;
import org.whispersystems.textsecuregcm.workers.ZkParamsCommand;
@@ -407,8 +395,6 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
bootstrap.addCommand(new ClearIssuedReceiptRedemptionsCommand());
bootstrap.addCommand(new CopyToS3Command());
bootstrap.addCommand(new ClearExpiredFoundationDbMessagesCommand(Clock.systemUTC()));
bootstrap.addCommand(new TrimOversizedFoundationDbMessageQueuesCommand());
bootstrap.addCommand(new ClearOrphanedFoundationDbQueuesCommand());
bootstrap.addCommand(new ProcessScheduledJobsServiceCommand("process-idle-device-notification-jobs",
"Processes scheduled jobs to send notifications to idle devices",
@@ -501,20 +487,9 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
// we'd like, but is the least bad option given current constraints.
fdb.disableShutdownHook();
final FoundationDbExternalClientConfiguration externalClientConfiguration = config.getFoundationDbMessagesConfiguration()
.externalClientConfiguration();
if (externalClientConfiguration != null) {
// If threadsPerClient is not specified, we default to the cluster size so that there is 1:1 correspondence between
// Database objects and threads.
final int clientThreadsPerVersion = externalClientConfiguration.threadsPerClient()
.orElseGet(() -> config.getFoundationDbMessagesConfiguration().clusters().size());
externalClientConfiguration.clientLibraryPaths().forEach(path -> fdb.options().setExternalClientLibrary(path));
fdb.options().setClientThreadsPerVersion(clientThreadsPerVersion);
}
final Map<Integer, List<FaultTolerantDatabase>> messageDatabasesByEpoch;
final Map<Integer, List<Database>> messageDatabasesByEpoch;
{
final Map<String, FaultTolerantDatabase> faultTolerantDatabasesByName =
final Map<String, Database> databasesByName =
config.getFoundationDbMessagesConfiguration().clusters().entrySet().stream()
.collect(Collectors.toUnmodifiableMap(Map.Entry::getKey,
entry -> {
@@ -526,8 +501,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
database.options().setTransactionRetryLimit(
config.getFoundationDbMessagesConfiguration().transactionRetryLimit());
return new FaultTolerantDatabase(database, entry.getKey(),
config.getFoundationDbMessagesConfiguration().circuitBreakerConfigurationName());
return database;
} catch (final IOException e) {
throw new UncheckedIOException(e);
}
@@ -536,10 +510,8 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
messageDatabasesByEpoch = config.getFoundationDbMessagesConfiguration().epochs().entrySet().stream()
.collect(Collectors.toUnmodifiableMap(Map.Entry::getKey,
entry -> entry.getValue().stream()
.map(faultTolerantDatabasesByName::get)
.map(databasesByName::get)
.toList()));
environment.lifecycle().manage(new FoundationDBWarmup(faultTolerantDatabasesByName));
}
final AwsCredentialsProvider cdnCredentialsProvider = config.getCdnConfiguration().credentials().build();
@@ -558,15 +530,10 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
.allowCoreThreadTimeOut(true)
.workQueue(messageDeletionQueue).build();
RedeemedReceiptsManager redeemedReceiptsManager = new RedeemedReceiptsManager(clock,
config.getDynamoDbTables().getRedeemedReceipts().getTableName(),
dynamoDbClient);
Accounts accounts = new Accounts(
clock,
dynamoDbClient,
dynamoDbAsyncClient,
redeemedReceiptsManager,
config.getDynamoDbTables().getAccounts().getTableName(),
config.getDynamoDbTables().getAccounts().getPhoneNumberTableName(),
config.getDynamoDbTables().getAccounts().getPhoneNumberIdentifierTableName(),
@@ -608,7 +575,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
ReportMessageDynamoDb reportMessageDynamoDb = new ReportMessageDynamoDb(dynamoDbClient, dynamoDbAsyncClient,
config.getDynamoDbTables().getReportMessage().getTableName(),
config.getReportMessageConfiguration().getReportTtl());
PhoneNumberRecoveryPasswords phoneNumberRecoveryPasswords = new PhoneNumberRecoveryPasswords(
RegistrationRecoveryPasswords registrationRecoveryPasswords = new RegistrationRecoveryPasswords(
config.getDynamoDbTables().getRegistrationRecovery().getTableName(),
config.getDynamoDbTables().getRegistrationRecovery().getExpiration(),
dynamoDbClient,
@@ -682,6 +649,10 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
.workQueue(receiptSenderQueue)
.rejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy())
.build();
ExecutorService accountLockExecutor = ExecutorServiceBuilder.of(environment, "accountLock")
.minThreads(8)
.maxThreads(8)
.build();
// unbounded executor (same as cachedThreadPool)
ExecutorService remoteStorageHttpExecutor = ExecutorServiceBuilder.of(environment, "remoteStorage")
.minThreads(0)
@@ -746,8 +717,8 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
AsnInfoProvider.EMPTY,
"AsnManager");
PhoneNumberRecoveryPasswordsManager phoneNumberRecoveryPasswordsManager =
new PhoneNumberRecoveryPasswordsManager(phoneNumberRecoveryPasswords);
RegistrationRecoveryPasswordsManager registrationRecoveryPasswordsManager =
new RegistrationRecoveryPasswordsManager(registrationRecoveryPasswords);
UsernameHashZkProofVerifier usernameHashZkProofVerifier = new UsernameHashZkProofVerifier();
final CarrierDataProvider carrierDataProvider =
@@ -811,13 +782,12 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
changeNumberWaitingPeriods, config.getChangeNumber().postRegistrationWaitingPeriod(), clock);
AccountLockManager accountLockManager = new AccountLockManager(dynamoDbClient,
config.getDynamoDbTables().getDeletedAccountsLock().getTableName());
final AccountsManager accountsManager = new AccountsManager(accounts, phoneNumberIdentifiers, cacheCluster,
AccountsManager accountsManager = new AccountsManager(accounts, phoneNumberIdentifiers, cacheCluster,
pubsubClient, accountLockManager, keysManager, messagesManager, profilesManager,
changeNumberWaitingPeriodManager, secureStorageClient, secureValueRecovery2Client, disconnectionRequestManager,
phoneNumberRecoveryPasswordsManager, messagePollExecutor,
retryExecutor, clock, config.getLinkDeviceSecretConfiguration().secret().value(),
config.getRegistrationTotpConfiguration().maxValidationDelay());
RemoteConfigsManager remoteConfigsManager = new RemoteConfigsManager(remoteConfigs, config.getRemoteConfigConfiguration().globalConfig());
registrationRecoveryPasswordsManager, accountLockExecutor, messagePollExecutor,
retryExecutor, clock, config.getLinkDeviceSecretConfiguration().secret().value());
RemoteConfigsManager remoteConfigsManager = new RemoteConfigsManager(remoteConfigs);
APNSender apnSender = new APNSender(apnSenderExecutor, Clock.systemUTC(), config.getApnConfiguration());
FcmSender fcmSender = new FcmSender(fcmSenderExecutor, config.getFcmConfiguration().credentials().value());
PushNotificationScheduler pushNotificationScheduler = new PushNotificationScheduler(pushSchedulerCluster,
@@ -828,13 +798,18 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
ProvisioningManager provisioningManager = new ProvisioningManager(pubsubClient);
IssuedReceiptsManager issuedReceiptsManager = new IssuedReceiptsManager(
config.getDynamoDbTables().getIssuedReceipts().getTableName(),
config.getDynamoDbTables().getIssuedReceipts().getExpiration(),
dynamoDbClient,
config.getDynamoDbTables().getIssuedReceipts().getGenerator(),
config.getDynamoDbTables().getIssuedReceipts().getMaxReceiptsPerSubscriptionPayment());
config.getDynamoDbTables().getIssuedReceipts().getmaxIssuedReceiptsPerPaymentId());
OneTimeDonationsManager oneTimeDonationsManager = new OneTimeDonationsManager(
config.getDynamoDbTables().getOnetimeDonations().getTableName(), config.getDynamoDbTables().getOnetimeDonations().getExpiration(), dynamoDbClient);
DonationPermits donationPermits = new DonationPermits(
config.getDynamoDbTables().getDonationPermits().getTableName(), config.getDynamoDbTables().getDonationPermits().getExpiration(), dynamoDbClient);
RedeemedReceiptsManager redeemedReceiptsManager = new RedeemedReceiptsManager(clock,
config.getDynamoDbTables().getRedeemedReceipts().getTableName(),
dynamoDbClient,
config.getDynamoDbTables().getRedeemedReceipts().getExpiration());
Subscriptions subscriptions = new Subscriptions(
config.getDynamoDbTables().getSubscriptions().getTableName(), dynamoDbClient);
MessageDeliveryLoopMonitor messageDeliveryLoopMonitor =
@@ -845,7 +820,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
callQualitySurveyPubSubExecutor);
final RegistrationLockVerificationManager registrationLockVerificationManager = new RegistrationLockVerificationManager(
accountsManager, disconnectionRequestManager, svr2CredentialsGenerator, phoneNumberRecoveryPasswordsManager,
accountsManager, disconnectionRequestManager, svr2CredentialsGenerator, registrationRecoveryPasswordsManager,
pushNotificationManager, rateLimiters);
final ReportedMessageMetricsListener reportedMessageMetricsListener = new ReportedMessageMetricsListener(
@@ -950,7 +925,6 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
config.getCdnConfiguration().credentials().secretAccessKey().value());
ServerSecretParams groupZkSecretParams = new ServerSecretParams(config.getGroupsZkConfig().serverSecret().value());
GenericServerSecretParams callingPreV101GenericZkSecretParams = new GenericServerSecretParams(config.getCallingZkConfigPreV101().serverSecret().value());
GenericServerSecretParams callingGenericZkSecretParams = new GenericServerSecretParams(config.getCallingZkConfig().serverSecret().value());
GenericServerSecretParams chatGenericZkSecretParams = new GenericServerSecretParams(config.getChatZkConfig().serverSecret().value());
ServerZkProfileOperations zkProfileOperations = new ServerZkProfileOperations(groupZkSecretParams);
@@ -1004,13 +978,6 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
List.of(stripeManager, braintreeManager, googlePlayBillingManager, appleAppStoreManager),
zkReceiptOperations, issuedReceiptsManager);
final LoginPurchaseManager loginPurchaseManager = new LoginPurchaseManager(
Map.of(
PaymentProvider.APPLE_APP_STORE, appleAppStoreManager,
PaymentProvider.GOOGLE_PLAY_BILLING, googlePlayBillingManager),
issuedReceiptsManager,
zkReceiptOperations);
final List<SpamFilter> spamFilters = ServiceLoader.load(SpamFilter.class)
.stream()
.map(ServiceLoader.Provider::get)
@@ -1110,19 +1077,18 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
config.getDeliveryCertificate().embedSigner());
final PhoneVerificationTokenManager phoneVerificationTokenManager = new PhoneVerificationTokenManager(
phoneNumberIdentifiers, registrationServiceClient, phoneNumberRecoveryPasswordsManager, registrationRecoveryChecker);
phoneNumberIdentifiers, registrationServiceClient, registrationRecoveryPasswordsManager, registrationRecoveryChecker);
final ChangeNumberManager changeNumberManager = new ChangeNumberManager(messageSender, accountsManager,
phoneVerificationTokenManager, registrationLockVerificationManager, rateLimiters,
changeNumberWaitingPeriodManager, Clock.systemUTC());
final List<ServerServiceDefinition> authenticatedServices = Stream.of(
new AccountsGrpcService(accountsManager, rateLimiters, usernameHashZkProofVerifier,
phoneNumberRecoveryPasswordsManager, Clock.systemUTC(), changeNumberManager),
new AccountsGrpcService(accountsManager, rateLimiters, usernameHashZkProofVerifier, registrationRecoveryPasswordsManager, Clock.systemUTC(), changeNumberManager),
new CallingGrpcService(cloudflareTurnCredentialsManager, rateLimiters),
new CredentialsGrpcService(accountsManager, certificateGenerator, zkAuthOperations, callingGenericZkSecretParams, rateLimiters, Clock.systemUTC(), ExternalServiceDefinitions.createExternalServiceList(config, Clock.systemUTC())),
new KeysGrpcService(accountsManager, keysManager, rateLimiters),
new ProfileGrpcService(clock, accountsManager, profilesManager, asnInfoProviderSupplier, dynamicConfigurationManager, config.getBadges(), profileCdnPolicyGenerator, chatGenericZkSecretParams, profileBadgeConverter, rateLimiters),
new ProfileGrpcService(clock, accountsManager, profilesManager, dynamicConfigurationManager, config.getBadges(), profileCdnPolicyGenerator, chatGenericZkSecretParams, profileBadgeConverter, rateLimiters),
new MessagesGrpcService(accountsManager, rateLimiters, messageSender, messageByteLimitCardinalityEstimator, spamChecker, messageDispatcher, Clock.systemUTC()),
new BackupsGrpcService(accountsManager, backupAuthManager, backupMetrics),
new DevicesGrpcService(accountsManager),
@@ -1133,12 +1099,8 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
new ChallengeGrpcService(accountsManager, rateLimitChallengeManager, challengeConstraintChecker),
new DonationsGrpcService(clock, zkReceiptOperations, redeemedReceiptsManager, accountsManager, config.getBadges(), ReceiptCredentialPresentation::new, donationPermitsManager, rateLimiters),
new ProductConfigurationGrpcService(config.getSubscription(), config.getOneTimeDonations(),
config.getLoginPurchase(), List.of(stripeManager, braintreeManager),
config.getBackupConfiguration().maxTotalMediaSize()),
new RemoteConfigurationGrpcService(remoteConfigsManager, profileBadgeConverter,
config.getBadges().getBadges().stream()
.map(BadgeConfiguration::getId)
.toList()))
List.of(stripeManager, braintreeManager), profileBadgeConverter,
config.getBackupConfiguration().maxTotalMediaSize()))
.map(bindableService -> ServerInterceptors.intercept(bindableService,
// 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!
@@ -1155,8 +1117,6 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
new AccountsAnonymousGrpcService(accountsManager, rateLimiters, groupSendTokenUtil),
new CallQualitySurveyGrpcService(callQualitySurveyManager, rateLimiters),
new KeysAnonymousGrpcService(accountsManager, keysManager, groupZkSecretParams, Clock.systemUTC()),
new KeyTransparencyGrpcService(rateLimiters, keyTransparencyServiceClient),
new LoginPurchaseGrpcService(loginPurchaseManager, dynamicConfigurationManager),
new ProfileAnonymousGrpcService(accountsManager, profilesManager, profileBadgeConverter, profileCdnPolicyGenerator, chatGenericZkSecretParams, groupZkSecretParams, rateLimiters, clock),
new MessagesAnonymousGrpcService(accountsManager, rateLimiters, messageSender, groupSendTokenUtil, messageByteLimitCardinalityEstimator, spamChecker, Clock.systemUTC()),
new BackupsAnonymousGrpcService(backupManager, backupMetrics, config.getAttachments().maxAttachmentUploadSizeInBytes(), config.getAttachments().maxMessageBackupUploadSizeInBytes()),
@@ -1192,14 +1152,11 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
unauthenticatedServices.forEach(serverBuilder::addService);
final ManagedGrpcServer localGrpcServer = new ManagedGrpcServer(serverBuilder.build());
final String websocketServletPath = "/v1/websocket/";
final String provisioningWebsocketServletPath = "/v1/websocket/provisioning/";
final SocketAddress websocketAddress =
new InetSocketAddress(config.getGrpc().websocketAddress(), config.getGrpc().websocketPort());
final OmnibusRouter omnibusRouter = new OmnibusRouter(Map.of(
websocketServletPath, websocketAddress,
provisioningWebsocketServletPath, websocketAddress),
final OmnibusRouter omnibusRouter = new OmnibusRouter(List.of(
new OmnibusRouter.OmnibusRoute("/v1/websocket", websocketAddress),
new OmnibusRouter.OmnibusRoute("/v1/provisioning", websocketAddress)),
grpcLocalAddress);
@Nullable final Mapping<String, SslContext> sniMapping = config.getGrpc().h2c()
? null
@@ -1230,6 +1187,9 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
.setAuthenticator(accountAuthenticator)
.buildAuthFilter();
final String websocketServletPath = "/v1/websocket/";
final String provisioningWebsocketServletPath = "/v1/websocket/provisioning/";
MetricsHttpEventHandler.configure(environment, Metrics.globalRegistry, clientReleaseManager, Set.of(websocketServletPath, provisioningWebsocketServletPath, "/health-check"));
// BufferingInterceptor is needed on the base environment but not the WebSocketEnvironment,
@@ -1272,19 +1232,20 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
final PersistentTimer persistentTimer = new PersistentTimer(rateLimitersCluster, clock);
final List<Object> commonControllers = Lists.newArrayList(
new AccountController(accountsManager, rateLimiters, phoneNumberRecoveryPasswordsManager,
new AccountController(accountsManager, rateLimiters, registrationRecoveryPasswordsManager,
usernameHashZkProofVerifier),
new AccountControllerV2(accountsManager, changeNumberManager),
new AttachmentControllerV4(rateLimiters, gcsAttachmentGenerator, tusAttachmentGenerator,
experimentEnrollmentManager, config.getAttachments().maxAttachmentUploadSizeInBytes()),
new ArchiveController(accountsManager, backupAuthManager, backupManager, backupMetrics, config.getAttachments().maxAttachmentUploadSizeInBytes(), config.getAttachments().maxMessageBackupUploadSizeInBytes()),
new CallRoutingControllerV2(rateLimiters, cloudflareTurnCredentialsManager),
new CallLinkController(rateLimiters, callingGenericZkSecretParams, callingPreV101GenericZkSecretParams),
new CallLinkController(rateLimiters, callingGenericZkSecretParams),
new CallQualitySurveyController(callQualitySurveyManager),
new CertificateController(accountsManager, certificateGenerator, zkAuthOperations, callingGenericZkSecretParams, callingPreV101GenericZkSecretParams, clock),
new CertificateController(accountsManager, certificateGenerator, zkAuthOperations, callingGenericZkSecretParams, clock),
new ChallengeController(accountsManager, rateLimitChallengeManager, challengeConstraintChecker),
new DeviceController(accountsManager, rateLimiters, persistentTimer),
new DeviceCheckController(clock, accountsManager, backupAuthManager, appleDeviceCheckManager, rateLimiters,
config.getDeviceCheck().backupRedemptionLevel(),
config.getDeviceCheck().backupRedemptionDuration()),
new DirectoryV2Controller(directoryV2CredentialsGenerator),
new DonationController(clock, zkReceiptOperations, redeemedReceiptsManager, accountsManager, config.getBadges(),
@@ -1294,29 +1255,27 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
new MessageController(rateLimiters, messageByteLimitCardinalityEstimator, messageSender, accountsManager,
phoneNumberIdentifiers, reportMessageManager, groupZkSecretParams, spamChecker, Clock.systemUTC()),
new PaymentsController(currencyManager, paymentsCredentialsGenerator),
new ProfileController(clock, rateLimiters, accountsManager, profilesManager, asnInfoProviderSupplier,
dynamicConfigurationManager, profileBadgeConverter, config.getBadges(), profileCdnPolicyGenerator,
new ProfileController(clock, rateLimiters, accountsManager, profilesManager, dynamicConfigurationManager,
profileBadgeConverter, config.getBadges(), profileCdnPolicyGenerator,
groupZkSecretParams, zkProfileOperations, batchIdentityCheckExecutor),
new ProvisioningController(rateLimiters, provisioningManager),
new RegistrationController(accountsManager, phoneVerificationTokenManager, registrationLockVerificationManager,
rateLimiters, registrationFraudChecker, ReceiptCredentialPresentation::new, zkReceiptOperations, clock, dynamicConfigurationManager),
new RemoteConfigController(remoteConfigsManager),
rateLimiters, registrationFraudChecker),
new RemoteConfigController(remoteConfigsManager, config.getRemoteConfigConfiguration().globalConfig()),
new SecureStorageController(storageCredentialsGenerator),
new SecureValueRecovery2Controller(svr2CredentialsGenerator, accountsManager),
new StickerController(rateLimiters, stickerPolicyGenerator, Clock.systemUTC()),
new VerificationController(registrationServiceClient, new VerificationSessionManager(verificationSessions),
pushNotificationManager, registrationCaptchaManager, phoneNumberRecoveryPasswordsManager,
pushNotificationManager, registrationCaptchaManager, registrationRecoveryPasswordsManager,
phoneNumberIdentifiers, rateLimiters, accountsManager, carrierDataProvider, registrationFraudChecker,
dynamicConfigurationManager, experimentEnrollmentManager, clock),
new SubscriptionController(clock, config.getSubscription(), config.getOneTimeDonations(),
config.getLoginPurchase(), subscriptionManager, stripeManager, braintreeManager, googlePlayBillingManager,
appleAppStoreManager,
subscriptionManager, stripeManager, braintreeManager, googlePlayBillingManager, appleAppStoreManager,
profileBadgeConverter, bankMandateTranslator, donationPermitsManager,
config.getBackupConfiguration().maxTotalMediaSize()),
new OneTimeDonationController(clock, config.getOneTimeDonations(), stripeManager, braintreeManager,
payPalDonationsTranslator, zkReceiptOperations, issuedReceiptsManager, oneTimeDonationsManager,
donationPermitsManager),
new LoginPurchaseController(loginPurchaseManager, dynamicConfigurationManager)
donationPermitsManager)
);
for (Object controller : commonControllers) {
@@ -1376,12 +1335,12 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
List.of(
new LoggingUnhandledExceptionMapper(),
new CompletionExceptionMapper(),
new GrpcStatusRuntimeExceptionMapper(),
new IOExceptionMapper(),
new RateLimitExceededExceptionMapper(),
new InvalidWebsocketAddressExceptionMapper(),
new DeviceLimitExceededExceptionMapper(),
new ServerRejectedExceptionMapper(),
new IllegalStateExceptionMapper(),
new ImpossiblePhoneNumberExceptionMapper(),
new NonNormalizedPhoneNumberExceptionMapper(),
new ObsoletePhoneNumberFormatExceptionMapper(),
@@ -19,6 +19,7 @@ import java.time.temporal.ChronoUnit;
import java.util.Optional;
import java.util.UUID;
import org.apache.commons.lang3.StringUtils;
import org.whispersystems.textsecuregcm.identity.IdentityType;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.AccountsManager;
import org.whispersystems.textsecuregcm.storage.Device;
@@ -100,7 +101,7 @@ public class AccountAuthenticator implements Authenticator<BasicCredentials, Aut
if (deviceSaltedTokenHash.verify(basicCredentials.getPassword())) {
succeeded = true;
final Account authenticatedAccount = updateLastSeen(account.get(), device.get());
return Optional.of(new AuthenticatedDevice(authenticatedAccount.getAccountIdentifier(),
return Optional.of(new AuthenticatedDevice(authenticatedAccount.getIdentifier(IdentityType.ACI),
device.get().getId(),
Instant.ofEpochMilli(authenticatedAccount.getPrimaryDevice().getLastSeen())));
} else {
@@ -125,7 +126,7 @@ public class AccountAuthenticator implements Authenticator<BasicCredentials, Aut
@VisibleForTesting
public Account updateLastSeen(Account account, Device device) {
// compute a non-negative integer between 0 and 86400.
long n = Util.ensureNonNegativeLong(account.getAccountIdentifier().getLeastSignificantBits());
long n = Util.ensureNonNegativeLong(account.getUuid().getLeastSignificantBits());
final long lastSeenOffsetSeconds = n % ChronoUnit.DAYS.getDuration().toSeconds();
// produce a truncated timestamp which is either today at UTC midnight
@@ -141,7 +142,7 @@ public class AccountAuthenticator implements Authenticator<BasicCredentials, Aut
Metrics.summary(DAYS_SINCE_LAST_SEEN_DISTRIBUTION_NAME, IS_PRIMARY_DEVICE_TAG, String.valueOf(device.isPrimary()))
.record(Duration.ofMillis(todayInMillisWithOffset - device.getLastSeen()).toDays());
return accountsManager.updateDeviceLastSeen(account.getAccountIdentifier(), device, Util.todayInMillis(clock));
return accountsManager.updateDeviceLastSeen(account.getIdentifier(IdentityType.ACI), device, Util.todayInMillis(clock));
}
return account;
@@ -11,6 +11,7 @@ import java.util.concurrent.TimeUnit;
import org.signal.libsignal.protocol.ecc.ECPrivateKey;
import org.whispersystems.textsecuregcm.entities.MessageProtos.SenderCertificate;
import org.whispersystems.textsecuregcm.entities.MessageProtos.ServerCertificate;
import org.whispersystems.textsecuregcm.identity.IdentityType;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.util.UUIDUtil;
@@ -34,18 +35,14 @@ public class CertificateGenerator {
}
public byte[] createFor(final Account account, final byte deviceId, boolean includeE164) {
if (includeE164 && account.getNumber().isEmpty()) {
throw new IllegalArgumentException();
}
SenderCertificate.Certificate.Builder builder = SenderCertificate.Certificate.newBuilder()
.setSenderDevice(Math.toIntExact(deviceId))
.setExpires(System.currentTimeMillis() + TimeUnit.DAYS.toMillis(expiresDays))
.setIdentityKey(ByteString.copyFrom(account.getAccountIdentityKey().serialize()))
.setSenderUuid(UUIDUtil.toByteString(account.getAccountIdentifier()));
.setIdentityKey(ByteString.copyFrom(account.getIdentityKey(IdentityType.ACI).serialize()))
.setSenderUuid(UUIDUtil.toByteString(account.getUuid()));
if (includeE164) {
builder.setSenderE164(account.getNumber().get());
builder.setSenderE164(account.getNumber());
}
if (embedSigner) {
@@ -164,7 +164,7 @@ public class DisconnectionRequestManager extends RedisPubSubAdapter<byte[], byte
* @return a future that completes when the request has been broadcast
*/
public CompletionStage<Void> requestDisconnection(final Account account) {
return requestDisconnection(account.getAccountIdentifier(),
return requestDisconnection(account.getIdentifier(IdentityType.ACI),
account.getDevices().stream().map(Device::getId).toList());
}
@@ -7,11 +7,9 @@ package org.whispersystems.textsecuregcm.auth;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
public class ExternalServiceCredentialsSelector {
@@ -46,13 +44,13 @@ public class ExternalServiceCredentialsSelector {
* A credential is valid if it passes validation by the provided credentialsGenerator AND it is the most recent
* credential in the provided list for a username.
*
* @param tokens A set of credentials, potentially with different usernames
* @param tokens A list of credentials, potentially with different usernames
* @param credentialsGenerator To validate these credentials
* @param maxAgeSeconds The maximum allowable age of the credential
* @return An unordered list of {@link CredentialInfo} for each provided token
* @return A {@link CredentialInfo} for each provided token
*/
public static List<CredentialInfo> check(
final Set<String> tokens,
final List<String> tokens,
final ExternalServiceCredentialsGenerator credentialsGenerator,
final long maxAgeSeconds) {
@@ -22,7 +22,7 @@ import org.whispersystems.textsecuregcm.entities.RegistrationServiceSession;
import org.whispersystems.textsecuregcm.registration.RegistrationServiceClient;
import org.whispersystems.textsecuregcm.spam.RegistrationRecoveryChecker;
import org.whispersystems.textsecuregcm.storage.PhoneNumberIdentifiers;
import org.whispersystems.textsecuregcm.storage.PhoneNumberRecoveryPasswordsManager;
import org.whispersystems.textsecuregcm.storage.RegistrationRecoveryPasswordsManager;
public class PhoneVerificationTokenManager {
@@ -33,16 +33,16 @@ public class PhoneVerificationTokenManager {
private final PhoneNumberIdentifiers phoneNumberIdentifiers;
private final RegistrationServiceClient registrationServiceClient;
private final PhoneNumberRecoveryPasswordsManager phoneNumberRecoveryPasswordsManager;
private final RegistrationRecoveryPasswordsManager registrationRecoveryPasswordsManager;
private final RegistrationRecoveryChecker registrationRecoveryChecker;
public PhoneVerificationTokenManager(final PhoneNumberIdentifiers phoneNumberIdentifiers,
final RegistrationServiceClient registrationServiceClient,
final PhoneNumberRecoveryPasswordsManager phoneNumberRecoveryPasswordsManager,
final RegistrationRecoveryPasswordsManager registrationRecoveryPasswordsManager,
final RegistrationRecoveryChecker registrationRecoveryChecker) {
this.phoneNumberIdentifiers = phoneNumberIdentifiers;
this.registrationServiceClient = registrationServiceClient;
this.phoneNumberRecoveryPasswordsManager = phoneNumberRecoveryPasswordsManager;
this.registrationRecoveryPasswordsManager = registrationRecoveryPasswordsManager;
this.registrationRecoveryChecker = registrationRecoveryChecker;
}
@@ -127,7 +127,7 @@ public class PhoneVerificationTokenManager {
final UUID phoneNumberIdentifier = phoneNumberIdentifiers.getPhoneNumberIdentifier(number)
.get(VERIFICATION_TIMEOUT_SECONDS, TimeUnit.SECONDS);
final boolean verified = phoneNumberRecoveryPasswordsManager.verify(phoneNumberIdentifier, recoveryPassword);
final boolean verified = registrationRecoveryPasswordsManager.verify(phoneNumberIdentifier, recoveryPassword);
if (!verified) {
throw new RecoveryPasswordVerificationFailedException();
@@ -14,13 +14,13 @@ import io.micrometer.core.instrument.Tag;
import io.micrometer.core.instrument.Tags;
import java.time.Duration;
import java.time.Instant;
import java.util.Collections;
import java.util.List;
import javax.annotation.Nullable;
import org.apache.commons.lang3.StringUtils;
import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
import org.whispersystems.textsecuregcm.entities.PhoneVerificationRequest;
import org.whispersystems.textsecuregcm.entities.RegistrationLockFailure;
import org.whispersystems.textsecuregcm.identity.IdentityType;
import org.whispersystems.textsecuregcm.limits.RateLimiters;
import org.whispersystems.textsecuregcm.metrics.UserAgentTagUtil;
import org.whispersystems.textsecuregcm.push.NotPushRegisteredException;
@@ -28,8 +28,7 @@ import org.whispersystems.textsecuregcm.push.PushNotificationManager;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.AccountsManager;
import org.whispersystems.textsecuregcm.storage.Device;
import org.whispersystems.textsecuregcm.storage.PhoneNumberRecoveryPasswordsManager;
import software.amazon.awssdk.services.dynamodb.model.TransactWriteItem;
import org.whispersystems.textsecuregcm.storage.RegistrationRecoveryPasswordsManager;
public class RegistrationLockVerificationManager {
public enum Flow {
@@ -55,20 +54,20 @@ public class RegistrationLockVerificationManager {
private final DisconnectionRequestManager disconnectionRequestManager;
private final ExternalServiceCredentialsGenerator svr2CredentialGenerator;
private final RateLimiters rateLimiters;
private final PhoneNumberRecoveryPasswordsManager phoneNumberRecoveryPasswordsManager;
private final RegistrationRecoveryPasswordsManager registrationRecoveryPasswordsManager;
private final PushNotificationManager pushNotificationManager;
public RegistrationLockVerificationManager(
final AccountsManager accounts,
final DisconnectionRequestManager disconnectionRequestManager,
final ExternalServiceCredentialsGenerator svr2CredentialGenerator,
final PhoneNumberRecoveryPasswordsManager phoneNumberRecoveryPasswordsManager,
final RegistrationRecoveryPasswordsManager registrationRecoveryPasswordsManager,
final PushNotificationManager pushNotificationManager,
final RateLimiters rateLimiters) {
this.accounts = accounts;
this.disconnectionRequestManager = disconnectionRequestManager;
this.svr2CredentialGenerator = svr2CredentialGenerator;
this.phoneNumberRecoveryPasswordsManager = phoneNumberRecoveryPasswordsManager;
this.registrationRecoveryPasswordsManager = registrationRecoveryPasswordsManager;
this.pushNotificationManager = pushNotificationManager;
this.rateLimiters = rateLimiters;
}
@@ -87,9 +86,6 @@ public class RegistrationLockVerificationManager {
final PhoneVerificationRequest.VerificationType phoneVerificationType
) throws RateLimitExceededException, RegistrationLockFailureException {
final String phoneNumber = account.getNumber()
.orElseThrow(() -> new IllegalArgumentException("account does not have a phone number"));
final Tags expiredTags = Tags.of(UserAgentTagUtil.getPlatformTag(userAgent),
Tag.of(REGISTRATION_LOCK_VERIFICATION_FLOW_TAG_NAME, flow.name()),
Tag.of(PHONE_VERIFICATION_TYPE_TAG_NAME, phoneVerificationType.name())
@@ -110,9 +106,10 @@ public class RegistrationLockVerificationManager {
}
if (StringUtils.isNotEmpty(clientRegistrationLock)) {
rateLimiters.getPinLimiter().validate(phoneNumber);
rateLimiters.getPinLimiter().validate(account.getNumber());
}
final String phoneNumber = account.getNumber();
final boolean registrationLockMatches = existingRegistrationLock.verify(clientRegistrationLock);
final boolean alreadyLocked = account.hasLockedCredentials();
@@ -139,8 +136,12 @@ public class RegistrationLockVerificationManager {
// Freezing the existing account credentials will definitively start the reglock timeout.
// Until the timeout, the current reglock can still be supplied,
// along with phone number verification, to restore access.
final List<TransactWriteItem> additionalWriteItems;
final Account updatedAccount;
if (!alreadyLocked) {
updatedAccount = accounts.update(account, Account::lockAuthTokenHash);
} else {
updatedAccount = account;
}
// The client often sends an empty registration lock token on the first request
// and sends an actual token if the server returns a 423 indicating that one is required.
@@ -149,22 +150,11 @@ 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) {
additionalWriteItems = List.of(phoneNumberRecoveryPasswordsManager.buildTransactWriteItemForRemovePassword(account.getPhoneNumberIdentifier()
.orElseThrow(() -> new AssertionError("Account with a phone number did not have a phone number identifier"))));
} else {
additionalWriteItems = Collections.emptyList();
registrationRecoveryPasswordsManager.remove(updatedAccount.getIdentifier(IdentityType.PNI));
}
final Account updatedAccount = accounts.update(account.getAccountIdentifier(), a -> {
if (!a.hasLockedCredentials()) {
a.lockAuthTokenHash();
}
a.clearAccountRecoveryPassword();
}, additionalWriteItems);
final List<Byte> deviceIds = updatedAccount.getDevices().stream().map(Device::getId).toList();
disconnectionRequestManager.requestDisconnection(updatedAccount.getAccountIdentifier(), deviceIds);
disconnectionRequestManager.requestDisconnection(updatedAccount.getUuid(), deviceIds);
try {
// Send a push notification that prompts the client to attempt login and fail due to locked credentials
@@ -186,7 +176,7 @@ public class RegistrationLockVerificationManager {
if (!existingRegistrationLock.needsFailureCredentials()) {
return null;
}
return svr2CredentialGenerator.generateForUuid(account.getAccountIdentifier());
return svr2CredentialGenerator.generateForUuid(account.getUuid());
}
}
@@ -136,11 +136,11 @@ public class BackupAuthManager {
}
if (requiresMessageRotation) {
rateLimiters.forDescriptor(RateLimiters.For.SET_BACKUP_ID).validate(account.getAccountIdentifier());
rateLimiters.forDescriptor(RateLimiters.For.SET_BACKUP_ID).validate(account.getUuid());
}
if (requiresMediaRotation && hasActiveVoucher(account)) {
rateLimiters.forDescriptor(RateLimiters.For.SET_PAID_MEDIA_BACKUP_ID).validate(account.getAccountIdentifier());
rateLimiters.forDescriptor(RateLimiters.For.SET_PAID_MEDIA_BACKUP_ID).validate(account.getUuid());
}
this.accountsManager.update(account, a ->
@@ -156,9 +156,9 @@ public class BackupAuthManager {
final boolean isPaid = hasActiveVoucher(account);
final CompletionStage<Boolean> hasSetMessagesPermits =
messagesLimiter.hasAvailablePermitsAsync(account.getAccountIdentifier(), 1);
messagesLimiter.hasAvailablePermitsAsync(account.getUuid(), 1);
final CompletionStage<Boolean> hasSetMediaPermits = isPaid
? mediaLimiter.hasAvailablePermitsAsync(account.getAccountIdentifier(), 1)
? mediaLimiter.hasAvailablePermitsAsync(account.getUuid(), 1)
: CompletableFuture.completedFuture(true);
return hasSetMessagesPermits.thenCombine(hasSetMediaPermits, (hasMessage, hasMedia) -> {
@@ -266,7 +266,7 @@ public class BackupAuthManager {
}
boolean receiptAllowed = redeemedReceiptsManager
.put(receiptSerial, receiptExpiration, receiptLevel, account.getAccountIdentifier());
.put(receiptSerial, receiptExpiration.getEpochSecond(), receiptLevel, account.getUuid());
if (!receiptAllowed) {
throw new BackupBadReceiptException("receipt serial is already redeemed");
}
@@ -342,7 +342,7 @@ public class BackupAuthManager {
* BackupVoucher.
*/
private BackupLevel configuredBackupLevel(final Account account) {
return this.experimentEnrollmentManager.isEnrolled(account.getAccountIdentifier(), BACKUP_MEDIA_EXPERIMENT_NAME)
return this.experimentEnrollmentManager.isEnrolled(account.getUuid(), BACKUP_MEDIA_EXPERIMENT_NAME)
? BackupLevel.PAID
: BackupLevel.FREE;
}
@@ -59,8 +59,6 @@ public class BackupManager {
static final String MESSAGE_BACKUP_NAME = "messageBackup";
private static final int DEFAULT_LIST_MEDIA_LIMIT = 1000;
private static final String ZK_AUTHN_COUNTER_NAME = MetricsUtil.name(BackupManager.class, "authentication");
private static final String ZK_AUTHZ_FAILURE_COUNTER_NAME = MetricsUtil.name(BackupManager.class,
"authorizationFailure");
@@ -460,19 +458,17 @@ public class BackupManager {
*
* @param backupUser An already ZK authenticated backup user
* @param cursor A cursor returned by a previous call that can be used to resume listing
* @param limit The maximum number of list results to return, or empty to use
* {@link #DEFAULT_LIST_MEDIA_LIMIT}
* @param limit The maximum number of list results to return
* @return A {@link ListMediaResult}
* @throws BackupPermissionException if the credential does not have the correct level
*/
public ListMediaResult list(
final AuthenticatedBackupUser backupUser,
final Optional<String> cursor,
final Optional<Integer> limit) throws BackupPermissionException {
final int limit) throws BackupPermissionException {
checkBackupLevel(backupUser, BackupLevel.FREE);
final RemoteStorageManager.ListResult result = remoteStorageManager
.list(cdnMediaDirectory(backupUser), cursor, limit.orElse(DEFAULT_LIST_MEDIA_LIMIT))
.toCompletableFuture().join();
final RemoteStorageManager.ListResult result =
remoteStorageManager.list(cdnMediaDirectory(backupUser), cursor, limit).toCompletableFuture().join();
return new ListMediaResult(result
.objects()
.stream()
@@ -42,7 +42,6 @@ public class Cdn3RemoteStorageManager implements RemoteStorageManager {
private final String clientId;
private final String clientSecret;
private final Map<Integer, String> sourceSchemes;
private final Duration usageRequestTimeout;
static final String CLIENT_ID_HEADER = "CF-Access-Client-Id";
static final String CLIENT_SECRET_HEADER = "CF-Access-Client-Secret";
@@ -76,7 +75,6 @@ public class Cdn3RemoteStorageManager implements RemoteStorageManager {
.withNumClients(configuration.numHttpClients())
.build();
this.sourceSchemes = configuration.sourceSchemes();
this.usageRequestTimeout = configuration.usageRequestTimeout();
}
@Override
@@ -233,7 +231,6 @@ public class Cdn3RemoteStorageManager implements RemoteStorageManager {
HttpUtils.queryParamString(Map.of("prefix", prefix).entrySet()))))
.header(CLIENT_ID_HEADER, clientId)
.header(CLIENT_SECRET_HEADER, clientSecret)
.timeout(usageRequestTimeout)
.build();
return this.storageManagerHttpClient.sendAsync(request, HttpResponse.BodyHandlers.ofInputStream())
.thenApply(response -> {
@@ -12,7 +12,6 @@ import jakarta.validation.constraints.NotNull;
import java.util.List;
import java.util.Map;
import org.whispersystems.textsecuregcm.configuration.secrets.SecretString;
import org.whispersystems.textsecuregcm.subscriptions.ReceiptLevel;
import javax.annotation.Nullable;
/**
@@ -39,7 +38,7 @@ public record AppleAppStoreConfiguration(
@NotBlank String keyId,
@NotNull SecretString encodedKey,
@NotBlank String subscriptionGroupId,
@NotNull Map<String, ReceiptLevel> productIdToLevel,
@NotNull Map<String, Long> productIdToLevel,
@NotNull List<@NotBlank String> appleRootCerts,
@Nullable String retryConfigurationName) {
}
@@ -13,7 +13,6 @@ import com.fasterxml.jackson.annotation.Nulls;
import io.dropwizard.validation.ValidationMethod;
import jakarta.validation.Valid;
import jakarta.validation.constraints.NotNull;
import org.whispersystems.textsecuregcm.subscriptions.ReceiptLevel;
import java.util.List;
import java.util.Map;
import java.util.Objects;
@@ -22,12 +21,12 @@ import java.util.stream.Collectors;
public class BadgesConfiguration {
private final List<BadgeConfiguration> badges;
private final Map<ReceiptLevel, String> receiptLevels;
private final Map<Long, String> receiptLevels;
@JsonCreator
public BadgesConfiguration(
@JsonProperty("badges") @JsonSetter(nulls = Nulls.AS_EMPTY) final List<BadgeConfiguration> badges,
@JsonProperty("receiptLevels") @JsonSetter(nulls = Nulls.AS_EMPTY) final Map<ReceiptLevel, String> receiptLevels) {
@JsonProperty("receiptLevels") @JsonSetter(nulls = Nulls.AS_EMPTY) final Map<Long, String> receiptLevels) {
this.badges = Objects.requireNonNull(badges);
this.receiptLevels = Objects.requireNonNull(receiptLevels);
}
@@ -40,7 +39,7 @@ public class BadgesConfiguration {
@Valid
@NotNull
public Map<ReceiptLevel, String> getReceiptLevels() {
public Map<Long, String> getReceiptLevels() {
return receiptLevels;
}
@@ -2,7 +2,6 @@ package org.whispersystems.textsecuregcm.configuration;
import jakarta.validation.Valid;
import jakarta.validation.constraints.NotNull;
import java.time.Duration;
import java.util.Collections;
import java.util.Map;
import org.whispersystems.textsecuregcm.configuration.secrets.SecretString;
@@ -22,8 +21,6 @@ import javax.annotation.Nullable;
* client; if `null`, uses the global default configuration
* @param retryConfigurationName The name of a retry configuration for the storage-manager http client; if
* `null`, uses the global default configuration
* @param usageRequestTimeout The per-attempt request timeout for usage requests to the storage-manager; if
* `null`, defaults to 5 minutes
*/
public record Cdn3StorageManagerConfiguration(
@NotNull String baseUri,
@@ -32,8 +29,7 @@ public record Cdn3StorageManagerConfiguration(
@NotNull Map<Integer, String> sourceSchemes,
@NotNull Integer numHttpClients,
@Nullable String circuitBreakerConfigurationName,
@Nullable String retryConfigurationName,
@NotNull Duration usageRequestTimeout) {
@Nullable String retryConfigurationName) {
public Cdn3StorageManagerConfiguration {
if (numHttpClients == null) {
@@ -42,8 +38,5 @@ public record Cdn3StorageManagerConfiguration(
if (sourceSchemes == null) {
sourceSchemes = Collections.emptyMap();
}
if (usageRequestTimeout == null) {
usageRequestTimeout = Duration.ofMinutes(5);
}
}
}
@@ -10,5 +10,6 @@ import java.time.Duration;
* Configuration for Device Check operations
*
* @param backupRedemptionDuration How long to grant backup access for redemptions via device check
* @param backupRedemptionLevel What backup level to grant redemptions via device check
*/
public record DeviceCheckConfiguration(Duration backupRedemptionDuration) {}
public record DeviceCheckConfiguration(Duration backupRedemptionDuration, long backupRedemptionLevel) {}
@@ -69,7 +69,7 @@ public class DynamoDbTables {
private final Table profilesV2;
private final Table pushChallenge;
private final Table pushNotificationExperimentSamples;
private final Table redeemedReceipts;
private final TableWithExpiration redeemedReceipts;
private final TableWithExpiration registrationRecovery;
private final Table remoteConfig;
private final Table reportMessage;
@@ -100,7 +100,7 @@ public class DynamoDbTables {
@JsonProperty("profilesV2") final Table profilesV2,
@JsonProperty("pushChallenge") final Table pushChallenge,
@JsonProperty("pushNotificationExperimentSamples") final Table pushNotificationExperimentSamples,
@JsonProperty("redeemedReceipts") final Table redeemedReceipts,
@JsonProperty("redeemedReceipts") final TableWithExpiration redeemedReceipts,
@JsonProperty("registrationRecovery") final TableWithExpiration registrationRecovery,
@JsonProperty("remoteConfig") final Table remoteConfig,
@JsonProperty("reportMessage") final Table reportMessage,
@@ -273,7 +273,7 @@ public class DynamoDbTables {
@NotNull
@Valid
public Table getRedeemedReceipts() {
public TableWithExpiration getRedeemedReceipts() {
return redeemedReceipts;
}
@@ -1,22 +0,0 @@
/*
* Copyright 2026 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.configuration;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotEmpty;
import jakarta.validation.constraints.PositiveOrZero;
import java.util.List;
import java.util.Optional;
/// Configuration for FoundationDB external clients. Primarily exists because an external client must be specified to
/// make use of the multi-threaded client feature.
///
/// @param clientLibraryPaths a list of paths to external client libraries (generally .so files on Linux). This allows
/// us to run multiple FDB client versions concurrently if needed; however, during normal operation, we expect the list
/// to be a single path pointing to the current FDB client library
/// @param threadsPerClient the number of networking threads spawned per client
public record FoundationDbExternalClientConfiguration(@NotEmpty List<@NotBlank String> clientLibraryPaths,
Optional<@PositiveOrZero Integer> threadsPerClient) {}
@@ -5,7 +5,6 @@
package org.whispersystems.textsecuregcm.configuration;
import jakarta.annotation.Nullable;
import jakarta.validation.Valid;
import jakarta.validation.constraints.AssertTrue;
import jakarta.validation.constraints.Max;
@@ -34,9 +33,7 @@ public record FoundationDbMessagesConfiguration(@NotEmpty Map<String, @Valid Fou
@NotNull Duration transactionTimeout,
@PositiveOrZero long transactionRetryLimit,
@NotNull Duration batchPriorityTransactionTimeout,
@PositiveOrZero long batchPriorityTransactionRetryLimit,
@Nullable String circuitBreakerConfigurationName,
@Nullable @Valid FoundationDbExternalClientConfiguration externalClientConfiguration) {
@PositiveOrZero long batchPriorityTransactionRetryLimit) {
public static final long DEFAULT_MAX_WATCHES_PER_CLIENT = 10_000;
public static final Duration DEFAULT_TRANSACTION_TIMEOUT = Duration.ofSeconds(1);
@@ -9,7 +9,6 @@ import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
import java.util.Map;
import org.whispersystems.textsecuregcm.configuration.secrets.SecretString;
import org.whispersystems.textsecuregcm.subscriptions.ReceiptLevel;
/**
* @param credentialsJson Service account credentials for Play Billing API
@@ -22,4 +21,4 @@ public record GooglePlayBillingConfiguration(
@NotBlank String credentialsJson,
@NotNull String packageName,
@NotBlank String applicationName,
@NotNull Map<String, ReceiptLevel> productIdToLevel) {}
@NotNull Map<String, Long> productIdToLevel) {}
@@ -7,25 +7,29 @@ package org.whispersystems.textsecuregcm.configuration;
import com.fasterxml.jackson.annotation.JsonProperty;
import jakarta.validation.constraints.NotEmpty;
import java.util.EnumMap;
import java.util.Map;
import org.whispersystems.textsecuregcm.subscriptions.PaymentProvider;
import org.whispersystems.textsecuregcm.util.EnumMapUtil;
import java.time.Duration;
import java.util.EnumMap;
import java.util.Map;
public class IssuedReceiptsTableConfiguration extends DynamoDbTables.Table {
public class IssuedReceiptsTableConfiguration extends DynamoDbTables.TableWithExpiration {
private final byte[] generator;
/// The maximum number of receipts that may be issued for a single subscription payment.
private final EnumMap<PaymentProvider, Integer> maxReceiptsPerSubscriptionPayment;
/**
* The maximum number of issued receipts the issued receipt manager should issue for a particular itemId
*/
private final EnumMap<PaymentProvider, Integer> maxIssuedReceiptsPerPaymentId;
public IssuedReceiptsTableConfiguration(
@JsonProperty("tableName") final String tableName,
@JsonProperty("expiration") final Duration expiration,
@JsonProperty("generator") final byte[] generator,
@JsonProperty("maxReceiptsPerSubscriptionPayment") final Map<PaymentProvider, Integer> maxReceiptsPerSubscriptionPayment) {
super(tableName);
@JsonProperty("maxIssuedReceiptsPerPaymentId") final Map<PaymentProvider, Integer> maxIssuedReceiptsPerPaymentId) {
super(tableName, expiration);
this.generator = generator;
this.maxReceiptsPerSubscriptionPayment = EnumMapUtil.toCompleteEnumMap(PaymentProvider.class, maxReceiptsPerSubscriptionPayment);
this.maxIssuedReceiptsPerPaymentId = EnumMapUtil.toCompleteEnumMap(PaymentProvider.class, maxIssuedReceiptsPerPaymentId);
}
@NotEmpty
@@ -33,7 +37,7 @@ public class IssuedReceiptsTableConfiguration extends DynamoDbTables.Table {
return generator;
}
public EnumMap<PaymentProvider, Integer> getMaxReceiptsPerSubscriptionPayment() {
return maxReceiptsPerSubscriptionPayment;
public EnumMap<PaymentProvider, Integer> getmaxIssuedReceiptsPerPaymentId() {
return maxIssuedReceiptsPerPaymentId;
}
}
@@ -1,20 +0,0 @@
/*
* Copyright 2026 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.configuration;
import jakarta.validation.constraints.NotEmpty;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Positive;
import java.time.Duration;
/// Configuration for one-time Signal Login purchases
///
/// @param playProductId the Google Play Billing productId clients should purchase to obtain a Signal Login
/// @param playOptionId the Google Play Billing optionId clients should purchase to obtain a Signal Login
/// @param appStoreProductId the App Store productId clients should purchase to obtain a Signal Login
public record LoginPurchaseConfiguration(
@NotEmpty String playProductId,
@NotEmpty String playOptionId,
@NotEmpty String appStoreProductId) {}
@@ -24,9 +24,10 @@ public record OneTimeDonationConfiguration(@Valid ExpiringLevelConfiguration boo
/**
* @param badge the numeric donation level ID
* @param level the badge ID associated with the level
* @param expiration the duration after which the level expires
*/
public record ExpiringLevelConfiguration(@NotEmpty String badge, Duration expiration) {
public record ExpiringLevelConfiguration(@NotEmpty String badge, @Positive long level, Duration expiration) {
}
}
@@ -18,7 +18,6 @@ public record OpenTelemetryConfiguration(
@JsonProperty Duration shutdownWaitDuration,
@JsonProperty int maxBucketCount,
@JsonProperty Map<String, Integer> maxBucketsPerMeter,
@JsonProperty boolean publishMaxGaugeForHistograms,
@JsonAnyGetter @JsonAnySetter Map<String, String> otlpConfig
) implements OtlpConfig {
@@ -1,20 +0,0 @@
/*
* Copyright 2026 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.configuration;
import jakarta.validation.constraints.NotNull;
import java.time.Duration;
public record TotpConfiguration(@NotNull Duration maxValidationDelay) {
public static TotpConfiguration DEFAULT = new TotpConfiguration(Duration.ofSeconds(15));
public TotpConfiguration {
if (maxValidationDelay == null) {
maxValidationDelay = DEFAULT.maxValidationDelay();
}
}
}
@@ -35,7 +35,7 @@ public class DynamicConfiguration {
@JsonProperty
@Valid
private DynamicPaymentsConfiguration payments = DynamicPaymentsConfiguration.DEFAULT;
private DynamicPaymentsConfiguration payments = new DynamicPaymentsConfiguration();
@JsonProperty
@Valid
@@ -85,10 +85,6 @@ public class DynamicConfiguration {
@Valid
private DynamicTurnConfiguration turn = new DynamicTurnConfiguration();
@JsonProperty
@Valid
private DynamicLoginPurchaseConfiguration loginPurchase = new DynamicLoginPurchaseConfiguration(false);
public Optional<DynamicExperimentEnrollmentConfiguration> getExperimentEnrollmentConfiguration(
final String experimentName) {
return Optional.ofNullable(experiments.get(experimentName));
@@ -158,8 +154,4 @@ public class DynamicConfiguration {
public DynamicTurnConfiguration getTurnConfiguration() {
return turn;
}
public DynamicLoginPurchaseConfiguration getLoginPurchaseConfiguration() {
return loginPurchase;
}
}
@@ -1,8 +0,0 @@
/*
* Copyright 2026 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.configuration.dynamic;
/// @param enabled whether clients may exchange a one-time purchase for a Signal Login receipt credential
public record DynamicLoginPurchaseConfiguration(boolean enabled) {}
@@ -6,23 +6,15 @@
package org.whispersystems.textsecuregcm.configuration.dynamic;
import com.fasterxml.jackson.annotation.JsonProperty;
import jakarta.validation.constraints.NotNull;
import java.util.Collections;
import java.util.List;
public record DynamicPaymentsConfiguration(@JsonProperty @NotNull List<String> disallowedPrefixes,
@JsonProperty @NotNull List<String> disallowedAsnRegions) {
public class DynamicPaymentsConfiguration {
public static DynamicPaymentsConfiguration DEFAULT =
new DynamicPaymentsConfiguration(Collections.emptyList(), Collections.emptyList());
@JsonProperty
private List<String> disallowedPrefixes = Collections.emptyList();
public DynamicPaymentsConfiguration {
if (disallowedPrefixes == null) {
disallowedPrefixes = DEFAULT.disallowedPrefixes();
}
if (disallowedAsnRegions == null) {
disallowedAsnRegions = DEFAULT.disallowedAsnRegions();
}
public List<String> getDisallowedPrefixes() {
return disallowedPrefixes;
}
}
@@ -4,7 +4,12 @@
*/
package org.whispersystems.textsecuregcm.controllers;
import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
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,13 +30,11 @@ 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;
import java.util.Base64;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.UUID;
@@ -55,19 +58,20 @@ import org.whispersystems.textsecuregcm.entities.ReserveUsernameHashResponse;
import org.whispersystems.textsecuregcm.entities.UsernameHashResponse;
import org.whispersystems.textsecuregcm.entities.UsernameLinkHandle;
import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier;
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;
import org.whispersystems.textsecuregcm.storage.PhoneNumberRecoveryPasswordsManager;
import org.whispersystems.textsecuregcm.storage.RegistrationRecoveryPasswordsManager;
import org.whispersystems.textsecuregcm.storage.UsernameHashNotAvailableException;
import org.whispersystems.textsecuregcm.storage.UsernameReservationNotFoundException;
import org.whispersystems.textsecuregcm.util.HeaderUtils;
import org.whispersystems.textsecuregcm.util.UsernameHashZkProofVerifier;
import org.whispersystems.textsecuregcm.util.Util;
import software.amazon.awssdk.services.dynamodb.model.TransactWriteItem;
@SuppressWarnings("OptionalUsedAsFieldOrParameterType")
@Path("/v1/accounts")
@@ -77,19 +81,23 @@ 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 PhoneNumberRecoveryPasswordsManager phoneNumberRecoveryPasswordsManager;
private final RegistrationRecoveryPasswordsManager registrationRecoveryPasswordsManager;
private final UsernameHashZkProofVerifier usernameHashZkProofVerifier;
public AccountController(
AccountsManager accounts,
RateLimiters rateLimiters,
PhoneNumberRecoveryPasswordsManager phoneNumberRecoveryPasswordsManager,
RegistrationRecoveryPasswordsManager registrationRecoveryPasswordsManager,
UsernameHashZkProofVerifier usernameHashZkProofVerifier) {
this.accounts = accounts;
this.rateLimiters = rateLimiters;
this.phoneNumberRecoveryPasswordsManager = phoneNumberRecoveryPasswordsManager;
this.registrationRecoveryPasswordsManager = registrationRecoveryPasswordsManager;
this.usernameHashZkProofVerifier = usernameHashZkProofVerifier;
}
@@ -158,12 +166,8 @@ public class AccountController {
public void setRegistrationLock(@Auth AuthenticatedDevice auth, @NotNull @Valid RegistrationLock accountLock) {
final SaltedTokenHash credentials = SaltedTokenHash.generateFor(accountLock.registrationLock());
try {
accounts.update(auth.accountIdentifier(),
a -> a.setRegistrationLock(credentials.hash(), credentials.salt()));
} catch (IllegalArgumentException _) {
throw new BadRequestException();
}
accounts.update(auth.accountIdentifier(),
a -> a.setRegistrationLock(credentials.hash(), credentials.salt()));
}
@DELETE
@@ -207,7 +211,7 @@ public class AccountController {
throw new ForbiddenException();
}
accounts.updateDevice(account.getAccountIdentifier(), targetDeviceId, d -> d.setName(deviceName.deviceName()));
accounts.updateDevice(account.getIdentifier(IdentityType.ACI), targetDeviceId, d -> d.setName(deviceName.deviceName()));
}
@PUT
@@ -216,19 +220,11 @@ public class AccountController {
@Produces(MediaType.APPLICATION_JSON)
public void setAccountAttributes(
@Auth AuthenticatedDevice auth,
@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));
final Collection<TransactWriteItem> additionalWriteItems =
account.getPhoneNumberIdentifier()
.flatMap(phoneNumberIdentifier -> attributes.recoveryPassword().map(recoveryPassword ->
List.of(phoneNumberRecoveryPasswordsManager.buildTransactWriteItemForStorePassword(phoneNumberIdentifier, recoveryPassword))))
.orElseGet(Collections::emptyList);
accounts.update(auth.accountIdentifier(), a -> {
final Account updatedAccount = accounts.update(auth.accountIdentifier(), a -> {
a.getDevice(auth.deviceId()).ifPresent(d -> {
d.setFetchesMessages(attributes.getFetchesMessages());
d.setName(attributes.getName());
@@ -239,22 +235,21 @@ public class AccountController {
}
});
if (StringUtils.isNotEmpty(attributes.getRegistrationLock()) && a.getNumber().isEmpty()) {
throw new BadRequestException("account does not have a phone number");
}
a.setRegistrationLockFromAttributes(attributes);
a.setUnidentifiedAccessKey(attributes.getUnidentifiedAccessKey());
a.setUnrestrictedUnidentifiedAccess(attributes.isUnrestrictedUnidentifiedAccess());
if (attributes.isDiscoverableByPhoneNumber() && a.getNumber().isEmpty()) {
throw new BadRequestException("account does not have a phone number");
}
a.setDiscoverableByPhoneNumber(attributes.isDiscoverableByPhoneNumber());
});
attributes.recoveryPassword().ifPresent(a::setAccountRecoveryPassword);
}, additionalWriteItems);
// if registration recovery password was sent to us, store it (or refresh its expiration)
attributes.recoveryPassword().ifPresent(registrationRecoveryPassword -> {
final boolean rrpCreated = registrationRecoveryPasswordsManager
.store(updatedAccount.getIdentifier(IdentityType.PNI), registrationRecoveryPassword);
Metrics.counter(RECOVERY_PASSWORD_SET_COUNTER_NAME, Tags.of(
UserAgentTagUtil.getPlatformTag(userAgent),
Tag.of("outcome", rrpCreated ? "created" : "updated")))
.increment();
});
}
@GET
@@ -394,7 +389,7 @@ public class AccountController {
throw new WebApplicationException(Response.status(422).build());
}
return accounts.getByUsernameHash(hash).thenApply(maybeAccount -> maybeAccount.map(Account::getAccountIdentifier)
return accounts.getByUsernameHash(hash).thenApply(maybeAccount -> maybeAccount.map(Account::getUuid)
.map(AciServiceIdentifier::new)
.map(AccountIdentifierResponse::new)
.orElseThrow(() -> new WebApplicationException(Status.NOT_FOUND)));
@@ -438,7 +433,7 @@ public class AccountController {
} else {
usernameLinkHandle = UUID.randomUUID();
}
updateUsernameLink(account.getAccountIdentifier(), usernameLinkHandle, encryptedUsername.usernameLinkEncryptedValue());
updateUsernameLink(account.getIdentifier(IdentityType.ACI), usernameLinkHandle, encryptedUsername.usernameLinkEncryptedValue());
return new UsernameLinkHandle(usernameLinkHandle);
}
@@ -155,13 +155,8 @@ public class AccountControllerV2 {
@Auth AuthenticatedDevice auth,
@NotNull @Valid PhoneNumberDiscoverabilityRequest phoneNumberDiscoverability) {
accountsManager.update(auth.accountIdentifier(), account -> {
if (account.getNumber().isEmpty()) {
throw new BadRequestException();
}
account.setDiscoverableByPhoneNumber(phoneNumberDiscoverability.discoverableByPhoneNumber());
});
accountsManager.update(auth.accountIdentifier(), a -> a.setDiscoverableByPhoneNumber(
phoneNumberDiscoverability.discoverableByPhoneNumber()));
}
@GET
@@ -18,18 +18,18 @@ public class AccountIdentityResponseBuilder {
private boolean storageCapable;
private Clock clock;
public AccountIdentityResponseBuilder(final Account account) {
public AccountIdentityResponseBuilder(Account account) {
this.account = account;
this.storageCapable = account.hasCapability(DeviceCapability.STORAGE);
this.clock = Clock.systemUTC();
}
public AccountIdentityResponseBuilder storageCapable(final boolean storageCapable) {
public AccountIdentityResponseBuilder storageCapable(boolean storageCapable) {
this.storageCapable = storageCapable;
return this;
}
public AccountIdentityResponseBuilder clock(final Clock clock) {
public AccountIdentityResponseBuilder clock(Clock clock) {
this.clock = clock;
return this;
}
@@ -47,14 +47,13 @@ public class AccountIdentityResponseBuilder {
.map(bv -> new Entitlements.BackupEntitlement(bv.receiptLevel(), bv.expiration()))
.orElse(null);
return new AccountIdentityResponse(account.getAccountIdentifier(),
return new AccountIdentityResponse(account.getUuid(),
account.getNumber(),
account.getPhoneNumberIdentifier(),
account.getUsernameHash().filter(h -> h.length > 0).orElse(null),
account.getUsernameLinkHandle(),
storageCapable,
new Entitlements(badges, backupEntitlement),
account.getAuthCredentialSalt().orElse(null));
new Entitlements(badges, backupEntitlement));
}
public static AccountIdentityResponse fromAccount(final Account account) {
@@ -975,7 +975,7 @@ public class ArchiveController {
final AuthenticatedBackupUser backupUser =
backupManager.authenticateBackupUser(presentation.presentation, signature.signature, userAgent);
final BackupManager.ListMediaResult listResult =
backupManager.list(backupUser, cursor, limit);
backupManager.list(backupUser, cursor, limit.orElse(1000));
return new ListResponse(listResult.media()
.stream().map(entry -> new StoredMediaObject(entry.cdn(), entry.key(), entry.length()))
.toList(),
@@ -2,7 +2,6 @@ package org.whispersystems.textsecuregcm.controllers;
import io.dropwizard.auth.Auth;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import jakarta.validation.Valid;
import jakarta.validation.constraints.NotNull;
@@ -10,7 +9,6 @@ import jakarta.ws.rs.BadRequestException;
import jakarta.ws.rs.POST;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.QueryParam;
import jakarta.ws.rs.core.MediaType;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
@@ -28,16 +26,13 @@ import org.whispersystems.textsecuregcm.limits.RateLimiters;
public class CallLinkController {
private final RateLimiters rateLimiters;
private final GenericServerSecretParams genericServerSecretParams;
private final GenericServerSecretParams genericServerSecretParamsPreV101;
public CallLinkController(
final RateLimiters rateLimiters,
final GenericServerSecretParams genericServerSecretParams,
final GenericServerSecretParams genericServerSecretParamsPreV101
final GenericServerSecretParams genericServerSecretParams
) {
this.rateLimiters = rateLimiters;
this.genericServerSecretParams = genericServerSecretParams;
this.genericServerSecretParamsPreV101 = genericServerSecretParamsPreV101;
}
@POST
@@ -57,9 +52,7 @@ public class CallLinkController {
@ApiResponse(responseCode = "429", description = "Ratelimited.")
public CreateCallLinkCredential getCreateAuth(
final @Auth AuthenticatedDevice auth,
final @NotNull @Valid GetCreateCallLinkCredentialsRequest request,
@Parameter(description = "Whether to use libsignal v0.101.0+ secret params")
final @QueryParam("v101") boolean v101
final @NotNull @Valid GetCreateCallLinkCredentialsRequest request
) throws RateLimitExceededException {
rateLimiters.getCreateCallLinkLimiter().validate(auth.accountIdentifier());
@@ -74,7 +67,7 @@ public class CallLinkController {
}
return new CreateCallLinkCredential(
createCallLinkCredentialRequest.issueCredential(new ServiceId.Aci(auth.accountIdentifier()), truncatedDayTimestamp, v101 ? genericServerSecretParams : genericServerSecretParamsPreV101).serialize(),
createCallLinkCredentialRequest.issueCredential(new ServiceId.Aci(auth.accountIdentifier()), truncatedDayTimestamp, genericServerSecretParams).serialize(),
truncatedDayTimestamp.getEpochSecond()
);
}
@@ -10,7 +10,6 @@ import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
import com.google.common.annotations.VisibleForTesting;
import io.dropwizard.auth.Auth;
import io.micrometer.core.instrument.Metrics;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.ws.rs.BadRequestException;
import jakarta.ws.rs.DefaultValue;
@@ -27,7 +26,6 @@ import java.time.Instant;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import javax.annotation.Nonnull;
import org.signal.libsignal.protocol.ServiceId;
import org.signal.libsignal.zkgroup.GenericServerSecretParams;
@@ -39,9 +37,11 @@ import org.whispersystems.textsecuregcm.auth.CertificateGenerator;
import org.whispersystems.textsecuregcm.auth.RedemptionRange;
import org.whispersystems.textsecuregcm.entities.DeliveryCertificate;
import org.whispersystems.textsecuregcm.entities.GroupCredentials;
import org.whispersystems.textsecuregcm.identity.IdentityType;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.AccountsManager;
@SuppressWarnings("OptionalUsedAsFieldOrParameterType")
@Path("/v1/certificate")
@Tag(name = "Certificate")
public class CertificateController {
@@ -50,7 +50,6 @@ public class CertificateController {
private final CertificateGenerator certificateGenerator;
private final ServerZkAuthOperations serverZkAuthOperations;
private final GenericServerSecretParams genericServerSecretParams;
private final GenericServerSecretParams genericServerSecretParamsPreV101;
private final Clock clock;
@VisibleForTesting
@@ -63,14 +62,12 @@ public class CertificateController {
@Nonnull CertificateGenerator certificateGenerator,
@Nonnull ServerZkAuthOperations serverZkAuthOperations,
@Nonnull GenericServerSecretParams genericServerSecretParams,
@Nonnull GenericServerSecretParams genericServerSecretParamsPreV101,
@Nonnull Clock clock) {
this.accountsManager = accountsManager;
this.certificateGenerator = Objects.requireNonNull(certificateGenerator);
this.serverZkAuthOperations = Objects.requireNonNull(serverZkAuthOperations);
this.genericServerSecretParams = genericServerSecretParams;
this.genericServerSecretParamsPreV101 = genericServerSecretParamsPreV101;
this.clock = Objects.requireNonNull(clock);
}
@@ -86,11 +83,8 @@ public class CertificateController {
final Account account = accountsManager.getByAccountIdentifier(auth.accountIdentifier())
.orElseThrow(() -> new WebApplicationException(Response.Status.UNAUTHORIZED));
try {
return new DeliveryCertificate(certificateGenerator.createFor(account, auth.deviceId(), includeE164));
} catch (final IllegalArgumentException _) {
throw new BadRequestException();
}
return new DeliveryCertificate(
certificateGenerator.createFor(account, auth.deviceId(), includeE164));
}
@GET
@@ -99,9 +93,7 @@ public class CertificateController {
public GroupCredentials getGroupAuthenticationCredentials(
@Auth AuthenticatedDevice auth,
@QueryParam("redemptionStartSeconds") long startSeconds,
@QueryParam("redemptionEndSeconds") long endSeconds,
@Parameter(description = "Whether to use libsignal v0.101.0+ secret params")
@QueryParam("v101") boolean v101) {
@QueryParam("redemptionEndSeconds") long endSeconds) {
final RedemptionRange redemptionRange;
try {
@@ -118,25 +110,20 @@ public class CertificateController {
final List<GroupCredentials.GroupCredential> credentials = new ArrayList<>();
final List<GroupCredentials.CallLinkAuthCredential> callLinkAuthCredentials = new ArrayList<>();
final ServiceId.Aci aci = new ServiceId.Aci(account.getAccountIdentifier());
final Optional<ServiceId.Pni> maybePni = account.getPhoneNumberIdentifier().map(ServiceId.Pni::new);
final ServiceId.Aci aci = new ServiceId.Aci(account.getIdentifier(IdentityType.ACI));
final ServiceId.Pni pni = new ServiceId.Pni(account.getIdentifier(IdentityType.PNI));
for (Instant redemption : redemptionRange) {
final AuthCredentialWithPniResponse authCredentialWithPni =
maybePni.map(pni -> serverZkAuthOperations.issueAuthCredentialWithPniZkc(aci, pni, redemption))
.orElseGet(() -> serverZkAuthOperations.issueAuthCredentialZkcWithoutPni(aci,
account.getAuthCredentialSalt()
.orElseThrow(() -> new IllegalStateException("account without PNI must have auth credential salt")),
redemption));
AuthCredentialWithPniResponse authCredentialWithPni = serverZkAuthOperations.issueAuthCredentialWithPniZkc(aci, pni, redemption);
credentials.add(new GroupCredentials.GroupCredential(
authCredentialWithPni.serialize(),
(int) redemption.getEpochSecond()));
callLinkAuthCredentials.add(new GroupCredentials.CallLinkAuthCredential(
CallLinkAuthCredentialResponse.issueCredential(aci, redemption, v101 ? genericServerSecretParams : genericServerSecretParamsPreV101).serialize(),
CallLinkAuthCredentialResponse.issueCredential(aci, redemption, genericServerSecretParams).serialize(),
redemption.getEpochSecond()));
}
return new GroupCredentials(credentials, callLinkAuthCredentials, maybePni.map(ServiceId.Pni::getRawUUID).orElse(null));
return new GroupCredentials(credentials, callLinkAuthCredentials, pni.getRawUUID());
}
}
@@ -14,7 +14,6 @@ import io.swagger.v3.oas.annotations.responses.ApiResponse;
import jakarta.validation.Valid;
import jakarta.validation.constraints.NotNull;
import jakarta.ws.rs.Consumes;
import jakarta.ws.rs.ForbiddenException;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.POST;
import jakarta.ws.rs.PUT;
@@ -30,13 +29,11 @@ import java.time.Duration;
import java.util.Base64;
import java.util.Locale;
import org.glassfish.jersey.server.ManagedAsync;
import org.signal.libsignal.zkgroup.backups.BackupLevel;
import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
import org.whispersystems.textsecuregcm.backup.BackupAuthManager;
import org.whispersystems.textsecuregcm.limits.RateLimiters;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.AccountsManager;
import org.whispersystems.textsecuregcm.storage.Device;
import org.whispersystems.textsecuregcm.storage.devicecheck.AppleDeviceCheckManager;
import org.whispersystems.textsecuregcm.storage.devicecheck.ChallengeNotFoundException;
import org.whispersystems.textsecuregcm.storage.devicecheck.DeviceCheckKeyIdNotFoundException;
@@ -62,6 +59,7 @@ public class DeviceCheckController {
private final BackupAuthManager backupAuthManager;
private final AppleDeviceCheckManager deviceCheckManager;
private final RateLimiters rateLimiters;
private final long backupRedemptionLevel;
private final Duration backupRedemptionDuration;
public DeviceCheckController(
@@ -70,11 +68,13 @@ public class DeviceCheckController {
final BackupAuthManager backupAuthManager,
final AppleDeviceCheckManager deviceCheckManager,
final RateLimiters rateLimiters,
final long backupRedemptionLevel,
final Duration backupRedemptionDuration) {
this.clock = clock;
this.accountsManager = accountsManager;
this.backupAuthManager = backupAuthManager;
this.deviceCheckManager = deviceCheckManager;
this.backupRedemptionLevel = backupRedemptionLevel;
this.backupRedemptionDuration = backupRedemptionDuration;
this.rateLimiters = rateLimiters;
}
@@ -141,10 +141,6 @@ public class DeviceCheckController {
@RequestBody(description = "The attestation data, created by [attestKey](https://developer.apple.com/documentation/devicecheck/dcappattestservice/attestkey(_:clientdatahash:completionhandler:))")
@NotNull final byte[] attestation) {
if (authenticatedDevice.deviceId() != Device.PRIMARY_ID) {
throw new ForbiddenException("Only primary devices may register attestations");
}
final Account account = accountsManager.getByAccountIdentifier(authenticatedDevice.accountIdentifier())
.orElseThrow(() -> new WebApplicationException(Response.Status.UNAUTHORIZED));
@@ -256,7 +252,7 @@ public class DeviceCheckController {
switch (request.assertionRequest().action()) {
case BACKUP -> backupAuthManager.extendBackupVoucher(
account,
new Account.BackupVoucher(BackupLevel.PAID.getValue(), clock.instant().plus(backupRedemptionDuration)));
new Account.BackupVoucher(backupRedemptionLevel, clock.instant().plus(backupRedemptionDuration)));
}
}
@@ -62,6 +62,7 @@ import org.whispersystems.textsecuregcm.entities.RemoteAttachment;
import org.whispersystems.textsecuregcm.entities.RemoteAttachmentError;
import org.whispersystems.textsecuregcm.entities.RestoreAccountRequest;
import org.whispersystems.textsecuregcm.entities.TransferArchiveUploadedRequest;
import org.whispersystems.textsecuregcm.identity.IdentityType;
import org.whispersystems.textsecuregcm.limits.RateLimitedByIp;
import org.whispersystems.textsecuregcm.limits.RateLimiters;
import org.whispersystems.textsecuregcm.metrics.DevicePlatformUtil;
@@ -71,7 +72,6 @@ import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.AccountsManager;
import org.whispersystems.textsecuregcm.storage.Device;
import org.whispersystems.textsecuregcm.storage.DeviceCapability;
import org.whispersystems.textsecuregcm.storage.DeviceIdentityInfo;
import org.whispersystems.textsecuregcm.storage.DeviceSpec;
import org.whispersystems.textsecuregcm.storage.LinkDeviceTokenAlreadyUsedException;
import org.whispersystems.textsecuregcm.storage.PersistentTimer;
@@ -196,7 +196,7 @@ public class DeviceController {
final Account account = accounts.getByAccountIdentifier(auth.accountIdentifier())
.orElseThrow(() -> new WebApplicationException(Response.Status.UNAUTHORIZED));
rateLimiters.getAllocateDeviceLimiter().validate(account.getAccountIdentifier());
rateLimiters.getAllocateDeviceLimiter().validate(account.getUuid());
if (account.getDevices().size() >= MAX_DEVICES) {
throw new DeviceLimitExceededException(account.getDevices().size(), MAX_DEVICES);
@@ -206,7 +206,7 @@ public class DeviceController {
throw new WebApplicationException(Response.Status.UNAUTHORIZED);
}
final String token = accounts.generateLinkDeviceToken(account.getAccountIdentifier());
final String token = accounts.generateLinkDeviceToken(account.getUuid());
return new LinkDeviceToken(token, AccountsManager.getLinkDeviceTokenIdentifier(token));
}
@@ -222,7 +222,7 @@ public class DeviceController {
""")
@ApiResponse(responseCode = "200", description = "The new device was linked to the calling account", useReturnTypeSchema = true)
@ApiResponse(responseCode = "403", description = "The given account was not found or the given verification code was incorrect")
@ApiResponse(responseCode = "409", description = "The new device is missing a capability required for the account")
@ApiResponse(responseCode = "409", description = "The new device is missing a capability supported by all other devices on the account")
@ApiResponse(responseCode = "411", description = "The given account already has its maximum number of linked devices")
@ApiResponse(responseCode = "422", description = "The request did not pass validation")
@ApiResponse(responseCode = "429", description = "Too many attempts", headers = @Header(
@@ -232,6 +232,7 @@ public class DeviceController {
@HeaderParam(HttpHeaders.USER_AGENT) @Nullable String userAgent,
@NotNull @Valid LinkDeviceRequest linkDeviceRequest)
throws RateLimitExceededException, DeviceLimitExceededException {
final Account account = accounts.checkDeviceLinkingToken(linkDeviceRequest.verificationCode())
.flatMap(accounts::getByAccountIdentifier)
.orElseThrow(ForbiddenException::new);
@@ -239,33 +240,17 @@ public class DeviceController {
final DeviceActivationRequest deviceActivationRequest = linkDeviceRequest.deviceActivationRequest();
final DeviceAttributes deviceAttributes = linkDeviceRequest.deviceAttributes();
rateLimiters.getVerifyDeviceLimiter().validate(account.getAccountIdentifier());
// Check the optional-phone-number capability before checking PNI keys, so we can give a better error code (since an
// older device will improperly supply PNI keys for a PNI-less account)
if (account.getPhoneNumberIdentifier().isEmpty() &&
!linkDeviceRequest.deviceAttributes().capabilities().contains(DeviceCapability.OPTIONAL_PHONE_NUMBER)) {
throw new WebApplicationException("Missing required device capability", 409);
}
rateLimiters.getVerifyDeviceLimiter().validate(account.getUuid());
final boolean allKeysValid =
PreKeySignatureValidator
.validatePreKeySignatures(account.getAccountIdentityKey(),
List.of(deviceActivationRequest.aciSignedPreKey(), deviceActivationRequest.aciPqLastResortPreKey()),
userAgent,
"link-device")
&& account.getPhoneNumberIdentityKey()
.map(pniIdentityKey ->
deviceActivationRequest.pniSignedPreKey().isPresent()
&& deviceActivationRequest.pniPqLastResortPreKey().isPresent()
&& PreKeySignatureValidator.validatePreKeySignatures(
pniIdentityKey,
List.of(deviceActivationRequest.pniSignedPreKey().get(), deviceActivationRequest.pniPqLastResortPreKey().get()),
userAgent,
"link-device"))
.orElse(
deviceActivationRequest.pniSignedPreKey().isEmpty()
&& deviceActivationRequest.pniPqLastResortPreKey().isEmpty());
PreKeySignatureValidator.validatePreKeySignatures(account.getIdentityKey(IdentityType.ACI),
List.of(deviceActivationRequest.aciSignedPreKey(), deviceActivationRequest.aciPqLastResortPreKey()),
userAgent,
"link-device")
&& PreKeySignatureValidator.validatePreKeySignatures(account.getIdentityKey(IdentityType.PNI),
List.of(deviceActivationRequest.pniSignedPreKey(), deviceActivationRequest.pniPqLastResortPreKey()),
userAgent,
"link-device");
if (!allKeysValid) {
throw new WebApplicationException(Response.status(422).build());
@@ -294,28 +279,25 @@ public class DeviceController {
}
try {
final Pair<Account, Device> accountAndDevice = accounts.addDevice(account.getAccountIdentifier(),
final Pair<Account, Device> accountAndDevice = accounts.addDevice(account.getIdentifier(IdentityType.ACI),
new DeviceSpec(deviceAttributes.name(),
authorizationHeader.getPassword(),
signalAgent,
capabilities,
new DeviceIdentityInfo(
deviceAttributes.registrationId(),
deviceActivationRequest.aciSignedPreKey(),
deviceActivationRequest.aciPqLastResortPreKey()),
account.getPhoneNumberIdentityKey().map(_ ->
new DeviceIdentityInfo(
deviceAttributes.phoneNumberIdentityRegistrationId(),
deviceActivationRequest.pniSignedPreKey().get(),
deviceActivationRequest.pniPqLastResortPreKey().get())),
deviceAttributes.registrationId(),
deviceAttributes.phoneNumberIdentityRegistrationId(),
deviceAttributes.fetchesMessages(),
deviceActivationRequest.apnToken(),
deviceActivationRequest.gcmToken()),
deviceActivationRequest.gcmToken(),
deviceActivationRequest.aciSignedPreKey(),
deviceActivationRequest.pniSignedPreKey(),
deviceActivationRequest.aciPqLastResortPreKey(),
deviceActivationRequest.pniPqLastResortPreKey()),
linkDeviceRequest.verificationCode());
return new LinkDeviceResponse(
accountAndDevice.first().getAccountIdentifier(),
accountAndDevice.first().getPhoneNumberIdentifier(),
accountAndDevice.first().getIdentifier(IdentityType.ACI),
accountAndDevice.first().getIdentifier(IdentityType.PNI),
accountAndDevice.second().getId());
} catch (final LinkDeviceTokenAlreadyUsedException e) {
throw new ForbiddenException();
@@ -41,7 +41,6 @@ import org.whispersystems.textsecuregcm.storage.AccountsManager;
import org.whispersystems.textsecuregcm.storage.DonationPermitsManager;
import org.whispersystems.textsecuregcm.storage.RedeemedReceiptsManager;
import org.whispersystems.textsecuregcm.subscriptions.ReceiptCredentialPresentationFactory;
import org.whispersystems.textsecuregcm.subscriptions.ReceiptLevel;
@Path("/v1/donation")
@Tag(name = "Donations")
@@ -118,10 +117,7 @@ public class DonationController {
final ReceiptSerial receiptSerial = receiptCredentialPresentation.getReceiptSerial();
final Instant receiptExpiration = Instant.ofEpochSecond(receiptCredentialPresentation.getReceiptExpirationTime());
final long receiptLevel = receiptCredentialPresentation.getReceiptLevel();
final String badgeId = ReceiptLevel
.lookupLevel(receiptLevel)
.map(badgesConfiguration.getReceiptLevels()::get)
.orElse(null);
final String badgeId = badgesConfiguration.getReceiptLevels().get(receiptLevel);
if (badgeId == null) {
return Response.serverError()
.entity("server does not recognize the requested receipt level")
@@ -130,7 +126,7 @@ public class DonationController {
}
final boolean receiptMatched = redeemedReceiptsManager.put(
receiptSerial, receiptExpiration, receiptLevel, auth.accountIdentifier());
receiptSerial, receiptExpiration.getEpochSecond(), receiptLevel, auth.accountIdentifier());
if (!receiptMatched) {
return Response.status(Status.BAD_REQUEST)
.entity("receipt serial is already redeemed")
@@ -108,7 +108,6 @@ public class KeysController {
@Operation(summary = "Get prekey count",
description = "Gets the number of one-time prekeys uploaded for this device and still available")
@ApiResponse(responseCode = "200", description = "Body contains the number of available one-time prekeys for the device.", useReturnTypeSchema = true)
@ApiResponse(responseCode = "400", description = "The request was malformed or the account does not support the requested identityType")
@ApiResponse(responseCode = "401", description = "Account authentication check failed.")
public CompletableFuture<PreKeyCount> getStatus(@Auth final AuthenticatedDevice auth,
@QueryParam("identity") @DefaultValue("aci") final IdentityType identityType) {
@@ -116,13 +115,12 @@ public class KeysController {
return accounts.getByAccountIdentifierAsync(auth.accountIdentifier())
.thenCompose(maybeAccount -> {
final Account account = maybeAccount.orElseThrow(() -> new WebApplicationException(Response.Status.UNAUTHORIZED));
final UUID identifier = getIdentifier(account, identityType);
final CompletableFuture<Integer> ecCountFuture =
keysManager.getEcCount(identifier, auth.deviceId());
keysManager.getEcCount(account.getIdentifier(identityType), auth.deviceId());
final CompletableFuture<Integer> pqCountFuture =
keysManager.getPqCount(identifier, auth.deviceId());
keysManager.getPqCount(account.getIdentifier(identityType), auth.deviceId());
return ecCountFuture.thenCombine(pqCountFuture, PreKeyCount::new);
});
@@ -133,7 +131,6 @@ public class KeysController {
@Produces(MediaType.APPLICATION_JSON)
@Operation(summary = "Upload new prekeys", description = "Upload new pre-keys for this device.")
@ApiResponse(responseCode = "200", description = "Indicates that new keys were successfully stored.")
@ApiResponse(responseCode = "400", description = "The request was malformed or the account does not support the requested identityType")
@ApiResponse(responseCode = "401", description = "Account authentication check failed.")
@ApiResponse(responseCode = "403", description = "Attempt to change identity key from a non-primary device.")
@ApiResponse(responseCode = "422", description = "Invalid request format.")
@@ -157,9 +154,9 @@ public class KeysController {
final Device device = account.getDevice(auth.deviceId())
.orElseThrow(() -> new WebApplicationException(Response.Status.UNAUTHORIZED));
final UUID identifier = getIdentifier(account, identityType);
final UUID identifier = account.getIdentifier(identityType);
checkSignedPreKeySignatures(setKeysRequest, getIdentityKey(account, identityType), userAgent);
checkSignedPreKeySignatures(setKeysRequest, account.getIdentityKey(identityType), userAgent);
final Tag platformTag = UserAgentTagUtil.getPlatformTag(userAgent);
final Tag primaryDeviceTag = Tag.of(PRIMARY_DEVICE_TAG_NAME, String.valueOf(auth.deviceId() == Device.PRIMARY_ID));
@@ -247,7 +244,6 @@ public class KeysController {
version byte followed by 1568 bytes of key material for a total of 1569 bytes)
""")
@ApiResponse(responseCode = "200", description = "Indicates that client and server have consistent views of repeated-use keys")
@ApiResponse(responseCode = "400", description = "The request was malformed or the account does not support the requested identityType")
@ApiResponse(responseCode = "401", description = "Account authentication check failed")
@ApiResponse(responseCode = "409", description = """
Indicates that client and server have inconsistent views of repeated-use keys or one or more repeated-use keys could
@@ -262,7 +258,7 @@ public class KeysController {
.thenCompose(maybeAccount -> {
final Account account = maybeAccount.orElseThrow(() -> new WebApplicationException(Response.Status.UNAUTHORIZED));
final UUID identifier = getIdentifier(account, checkKeysRequest.identityType());
final UUID identifier = account.getIdentifier(checkKeysRequest.identityType());
final byte deviceId = auth.deviceId();
final CompletableFuture<Optional<ECSignedPreKey>> ecSignedPreKeyFuture =
@@ -279,7 +275,7 @@ public class KeysController {
final boolean digestsMatch;
if (maybeSignedPreKey.isPresent() && maybeLastResortKey.isPresent()) {
final IdentityKey identityKey = getIdentityKey(account, checkKeysRequest.identityType());
final IdentityKey identityKey = account.getIdentityKey(checkKeysRequest.identityType());
final ECSignedPreKey ecSignedPreKey = maybeSignedPreKey.get();
final KEMSignedPreKey lastResortKey = maybeLastResortKey.get();
@@ -384,12 +380,7 @@ public class KeysController {
.fromCompletionStage(keysManager.takeDevicePreKeys(device.getId(), targetIdentifier, userAgent))
.flatMap(Mono::justOrEmpty)
.map(devicePreKeys -> new PreKeyResponseItem(
device.getId(),
switch (targetIdentifier.identityType()) {
case ACI -> device.getAccountRegistrationId();
case PNI -> device.getPhoneNumberIdentityRegistrationId()
.orElseThrow(() -> new IllegalStateException("Device on account retrieved by PNI does not have a PNI registration ID"));
},
device.getId(), device.getRegistrationId(targetIdentifier.identityType()),
devicePreKeys.ecSignedPreKey(),
devicePreKeys.ecPreKey().orElse(null),
devicePreKeys.kemSignedPreKey())))
@@ -397,11 +388,7 @@ public class KeysController {
.blockOptional()
.orElseGet(Collections::emptyList);
final IdentityKey identityKey = switch (targetIdentifier.identityType()) {
case ACI -> target.getAccountIdentityKey();
case PNI -> target.getPhoneNumberIdentityKey()
.orElseThrow(() -> new IllegalStateException("Account retrieved by PNI does not have a PNI identity key"));
};
final IdentityKey identityKey = target.getIdentityKey(targetIdentifier.identityType());
if (responseItems.isEmpty()) {
throw new WebApplicationException(Response.Status.NOT_FOUND);
@@ -437,32 +424,12 @@ public class KeysController {
final Optional<Byte> parsedTargetDeviceId = parseDeviceId(targetDeviceId);
final Optional<Integer> targetRegistrationId = parsedTargetDeviceId
.flatMap(targetAccount::getDevice)
.flatMap(device -> switch (targetIdentifier.identityType()) {
case ACI -> Optional.of(device.getAccountRegistrationId());
case PNI -> device.getPhoneNumberIdentityRegistrationId();
});
.map(device -> device.getRegistrationId(targetIdentifier.identityType()));
return RateLimitKeys.preKeyLimiterKey(
account.getAccountIdentifier(),
account.getUuid(),
authenticatedDevice.deviceId(),
targetIdentifier,
parsedTargetDeviceId, targetRegistrationId);
}
/// Get the identity of the requested `idenityType`, or throw a [BadRequestException] if `account` does not contain
/// that type.
private static UUID getIdentifier(final Account account, final IdentityType identityType) {
return switch (identityType) {
case ACI -> account.getAccountIdentifier();
case PNI -> account.getPhoneNumberIdentifier()
.orElseThrow(() -> new BadRequestException("Cannot set PNI identity keys on an account without a number"));
};
}
private static IdentityKey getIdentityKey(final Account account, final IdentityType identityType) {
return switch (identityType) {
case ACI -> account.getAccountIdentityKey();
case PNI -> account.getPhoneNumberIdentityKey()
.orElseThrow(() -> new BadRequestException("Account does not have a phone number"));
};
}
}
@@ -1,134 +0,0 @@
/*
* Copyright 2026 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.controllers;
import io.dropwizard.auth.Auth;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.headers.Header;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import jakarta.validation.Valid;
import jakarta.validation.constraints.NotNull;
import jakarta.ws.rs.BadRequestException;
import jakarta.ws.rs.Consumes;
import jakarta.ws.rs.ForbiddenException;
import jakarta.ws.rs.POST;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
import java.io.IOException;
import java.util.Optional;
import org.glassfish.jersey.server.ManagedAsync;
import org.signal.libsignal.zkgroup.InvalidInputException;
import org.signal.libsignal.zkgroup.VerificationFailedException;
import org.signal.libsignal.zkgroup.receipts.ReceiptCredentialRequest;
import org.signal.libsignal.zkgroup.receipts.ReceiptCredentialResponse;
import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
import org.whispersystems.textsecuregcm.mappers.SubscriptionExceptionMapper;
import org.whispersystems.textsecuregcm.storage.DynamicConfigurationManager;
import org.whispersystems.textsecuregcm.subscriptions.LoginPurchaseManager;
import org.whispersystems.textsecuregcm.subscriptions.PaymentProvider;
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionInvalidArgumentsException;
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionNotFoundException;
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionPaymentRequiredException;
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionReceiptAlreadyRedeemedException;
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionReceiptRequestedForOpenPaymentException;
@Path("/v1/login-purchase")
@io.swagger.v3.oas.annotations.tags.Tag(name = "LoginPurchase")
public class LoginPurchaseController {
private final LoginPurchaseManager loginPurchaseManager;
private final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager;
public LoginPurchaseController(
final LoginPurchaseManager loginPurchaseManager,
final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager) {
this.loginPurchaseManager = loginPurchaseManager;
this.dynamicConfigurationManager = dynamicConfigurationManager;
}
public record CreateLoginReceiptCredentialRequest(
@NotNull String purchaseIdentifier,
@NotNull byte[] receiptCredentialRequest,
@NotNull PaymentProvider paymentProvider) {
}
public record CreateLoginReceiptCredentialResponse(byte[] receiptCredentialResponse) {
}
@POST
@Path("/receipt_credentials")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@Operation(summary = "Create a receipt credential for a completed one-time login purchase",
description = """
Verify a completed one-time purchase with the payment provider and issue a receipt credential that can be
redeemed for a login.
This endpoint must be called on an unauthenticated connection. Retries for the same purchaseIdentifier MUST
use the same receiptCredentialRequest.
Callers must validate that the generated receipt credential has the
following properties:
- Level == 300 (The login level)
- ExpirationTime % 86400 == 0
- ExpirationTime == PurchaseTime + (5 * 366 * 86400) +/- (7 * 86400)
""")
@ApiResponse(responseCode = "200", description = "Successfully created receipt",
content = @Content(schema = @Schema(implementation = CreateLoginReceiptCredentialResponse.class)))
@ApiResponse(responseCode = "204", description = "The purchase is still pending with the payment provider. The client may retry later.")
@ApiResponse(responseCode = "400", description = """
Invalid request: malformed request, failed zkgroup verification, unsupported paymentProvider, the provided
purchase identifier not for a Signal Login, or login purchases are not currently enabled.
""")
@ApiResponse(responseCode = "402", description = "The purchase did not complete successfully. The body may include ChargeFailure details.",
content = @Content(schema = @Schema(
nullable = true,
implementation = SubscriptionExceptionMapper.ChargeFailureResponse.class)))
@ApiResponse(responseCode = "403", description = "The request was made on an authenticated channel")
@ApiResponse(responseCode = "404", description = "The payment provider has no purchase with the provided purchaseIdentifier")
@ApiResponse(responseCode = "409", description = "The purchase was already redeemed for a receipt credential, but with a different receipt credential request")
@ApiResponse(responseCode = "429", description = "Too many attempts", headers = @Header(
name = "Retry-After",
description = "If present, a positive integer indicating the number of seconds before a subsequent attempt could succeed"))
@ManagedAsync
public Response createLoginReceiptCredential(
@Auth final Optional<AuthenticatedDevice> authenticatedAccount,
@NotNull @Valid final CreateLoginReceiptCredentialRequest request)
throws IOException, SubscriptionPaymentRequiredException, SubscriptionInvalidArgumentsException, SubscriptionNotFoundException, RateLimitExceededException, SubscriptionReceiptAlreadyRedeemedException {
if (!dynamicConfigurationManager.getConfiguration().getLoginPurchaseConfiguration().enabled()) {
throw new BadRequestException("login purchases are not enabled");
}
if (authenticatedAccount.isPresent()) {
throw new ForbiddenException("must not use authenticated connection for login purchase operations");
}
final ReceiptCredentialRequest receiptCredentialRequest;
try {
receiptCredentialRequest = new ReceiptCredentialRequest(request.receiptCredentialRequest);
} catch (final InvalidInputException e) {
throw new BadRequestException("invalid receipt credential request", e);
}
try {
final ReceiptCredentialResponse receiptCredentialResponse = loginPurchaseManager.generateReceipt(
request.paymentProvider, request.purchaseIdentifier, receiptCredentialRequest);
return Response.ok(
new CreateLoginReceiptCredentialResponse(receiptCredentialResponse.serialize()))
.build();
} catch (SubscriptionReceiptRequestedForOpenPaymentException e) {
return Response.noContent().build();
} catch (VerificationFailedException e) {
throw new BadRequestException("receipt credential request failed verification", e);
}
}
}
@@ -263,7 +263,7 @@ public class MessageController {
final Account destination =
accountsManager.getByServiceIdentifier(destinationIdentifier).orElseThrow(NotFoundException::new);
rateLimiters.getMessagesLimiter().validate(source.accountIdentifier(), destination.getAccountIdentifier());
rateLimiters.getMessagesLimiter().validate(source.accountIdentifier(), destination.getUuid());
sendIndividualMessage(destination,
destinationIdentifier,
@@ -335,7 +335,7 @@ public class MessageController {
final Account destination = accountsManager.getByServiceIdentifier(destinationIdentifier).orElseThrow(() ->
new WebApplicationException(Response.ok(new SendMessageResponse(false)).build()));
rateLimiters.getStoriesLimiter().validate(destination.getAccountIdentifier());
rateLimiters.getStoriesLimiter().validate(destination.getUuid());
sendIndividualMessage(destination,
destinationIdentifier,
@@ -605,7 +605,7 @@ public class MessageController {
CompletableFuture.allOf(resolvedRecipients.values()
.stream()
.map(account -> account.getAccountIdentifier())
.map(account -> account.getIdentifier(IdentityType.ACI))
.map(accountIdentifier ->
rateLimiters.getStoriesLimiter().validateAsync(accountIdentifier).toCompletableFuture())
.toList()
@@ -740,17 +740,15 @@ public class MessageController {
final Optional<UUID> sourceAci;
final Optional<UUID> sourcePni;
boolean sourceAccountDeleted = false;
if (source.startsWith("+")) {
sourceNumber = Optional.of(source);
final Optional<Account> maybeAccount = accountsManager.getByE164(source);
if (maybeAccount.isPresent()) {
sourceAci = maybeAccount.map(Account::getAccountIdentifier);
sourcePni = maybeAccount.flatMap(Account::getPhoneNumberIdentifier);
sourceAci = maybeAccount.map(Account::getUuid);
sourcePni = maybeAccount.map(Account::getPhoneNumberIdentifier);
} else {
sourcePni = Optional.ofNullable(phoneNumberIdentifiers.getPhoneNumberIdentifier(source).join());
sourceAci = sourcePni.flatMap(accountsManager::findRecentlyDeletedAccountIdentifier);
sourceAccountDeleted = true;
}
} else {
sourceAci = Optional.of(UUID.fromString(source));
@@ -762,14 +760,13 @@ public class MessageController {
sourcePni = accountsManager.findRecentlyDeletedPhoneNumberIdentifier(sourceAci.get());
sourceNumber = sourcePni.flatMap(pni ->
Util.getCanonicalNumber(phoneNumberIdentifiers.getPhoneNumber(pni).join()));
sourceAccountDeleted = true;
} else {
sourceNumber = sourceAccount.flatMap(Account::getNumber);
sourcePni = sourceAccount.flatMap(Account::getPhoneNumberIdentifier);
sourceNumber = sourceAccount.map(Account::getNumber);
sourcePni = sourceAccount.map(Account::getPhoneNumberIdentifier);
}
}
final UUID spamReporterUuid = auth.accountIdentifier();
UUID spamReporterUuid = auth.accountIdentifier();
// spam report token is optional, but if provided ensure it is non-empty.
final Optional<byte[]> maybeSpamReportToken =
@@ -777,7 +774,7 @@ public class MessageController {
.flatMap(r -> Optional.ofNullable(r.token()))
.filter(t -> t.length > 0);
reportMessageManager.report(sourceNumber, sourceAci, sourcePni, messageGuid, spamReporterUuid, maybeSpamReportToken, userAgent, sourceAccountDeleted);
reportMessageManager.report(sourceNumber, sourceAci, sourcePni, messageGuid, spamReporterUuid, maybeSpamReportToken, userAgent);
return Response.status(Status.ACCEPTED)
.build();
@@ -350,8 +350,8 @@ public class OneTimeDonationController {
}
final Optional<PaymentDetails> maybePaymentDetails = (switch (request.processor) {
case STRIPE -> stripeManager.claimOneTimePurchase(request.paymentIntentId);
case BRAINTREE -> braintreeManager.claimOneTimePurchase(request.paymentIntentId);
case STRIPE -> stripeManager.getPaymentDetails(request.paymentIntentId);
case BRAINTREE -> braintreeManager.getPaymentDetails(request.paymentIntentId);
case GOOGLE_PLAY_BILLING -> throw new BadRequestException("cannot use play billing for one-time donations");
case APPLE_APP_STORE -> throw new BadRequestException("cannot use app store purchases for one-time donations");
});
@@ -383,21 +383,21 @@ public class OneTimeDonationController {
} catch (final InvalidInputException e) {
throw new BadRequestException("invalid receipt credential request", e);
}
final Instant paidAt = oneTimeDonationsManager.getPaidAt(request.processor, paymentDetails.id(), paymentDetails.created());
try {
issuedReceiptsManager.recordIssuance(paymentDetails.id(), request.processor,
receiptCredentialRequest, clock.instant());
} catch (WriteConflictException _) {
throw new WebApplicationException(Response.Status.CONFLICT);
}
final Instant paidAt = oneTimeDonationsManager.getPaidAt(paymentDetails.id(), paymentDetails.created());
final Instant expiration = paidAt
.plus(levelDetails.levelExpiration())
.truncatedTo(ChronoUnit.DAYS)
.plus(1, ChronoUnit.DAYS);
try {
issuedReceiptsManager.recordOneTimeIssuance(paymentDetails.id(), request.processor,
receiptCredentialRequest, expiration);
} catch (WriteConflictException _) {
throw new WebApplicationException(Response.Status.CONFLICT);
}
final ReceiptCredentialResponse receiptCredentialResponse;
try {
receiptCredentialResponse = zkReceiptOperations.issueReceiptCredential(
receiptCredentialRequest, expiration.getEpochSecond(), levelDetails.level().getValue());
receiptCredentialRequest, expiration.getEpochSecond(), levelDetails.level());
} catch (final VerificationFailedException e) {
throw new BadRequestException("receipt credential request failed verification", e);
}
@@ -50,7 +50,6 @@ import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executor;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import javax.annotation.Nullable;
import org.glassfish.jersey.server.ManagedAsync;
@@ -65,7 +64,6 @@ import org.signal.libsignal.zkgroup.profiles.ExpiringProfileKeyCredentialRespons
import org.signal.libsignal.zkgroup.profiles.ProfileKeyCommitment;
import org.signal.libsignal.zkgroup.profiles.ProfileKeyCredentialRequest;
import org.signal.libsignal.zkgroup.profiles.ServerZkProfileOperations;
import org.whispersystems.textsecuregcm.asn.AsnInfoProvider;
import org.whispersystems.textsecuregcm.auth.Anonymous;
import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
import org.whispersystems.textsecuregcm.auth.GroupSendTokenHeader;
@@ -82,7 +80,6 @@ import org.whispersystems.textsecuregcm.entities.CreateProfileRequest;
import org.whispersystems.textsecuregcm.entities.ExpiringProfileKeyCredentialProfileResponse;
import org.whispersystems.textsecuregcm.entities.ProfileAvatarUploadAttributes;
import org.whispersystems.textsecuregcm.entities.VersionedProfileResponse;
import org.whispersystems.textsecuregcm.filters.RemoteAddressFilter;
import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier;
import org.whispersystems.textsecuregcm.identity.IdentityType;
import org.whispersystems.textsecuregcm.identity.PniServiceIdentifier;
@@ -111,7 +108,6 @@ public class ProfileController {
private final RateLimiters rateLimiters;
private final ProfilesManager profilesManager;
private final AccountsManager accountsManager;
private final Supplier<AsnInfoProvider> asnInfoProviderSupplier;
private final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager;
private final ProfileBadgeConverter profileBadgeConverter;
private final Map<String, BadgeConfiguration> badgeConfigurationMap;
@@ -128,27 +124,25 @@ public class ProfileController {
private static final String DUPLICATE_AUTHENTICATION_COUNTER_NAME = name(ProfileController.class, "duplicateAuthentication");
public ProfileController(
final Clock clock,
final RateLimiters rateLimiters,
final AccountsManager accountsManager,
final ProfilesManager profilesManager,
final Supplier<AsnInfoProvider> asnInfoProviderSupplier,
final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager,
final ProfileBadgeConverter profileBadgeConverter,
final BadgesConfiguration badgesConfiguration,
final PostPolicyGenerator policyGenerator,
final ServerSecretParams serverSecretParams,
final ServerZkProfileOperations zkProfileOperations,
final Executor batchIdentityCheckExecutor) {
Clock clock,
RateLimiters rateLimiters,
AccountsManager accountsManager,
ProfilesManager profilesManager,
DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager,
ProfileBadgeConverter profileBadgeConverter,
BadgesConfiguration badgesConfiguration,
PostPolicyGenerator policyGenerator,
ServerSecretParams serverSecretParams,
ServerZkProfileOperations zkProfileOperations,
Executor batchIdentityCheckExecutor) {
this.clock = clock;
this.rateLimiters = rateLimiters;
this.accountsManager = accountsManager;
this.profilesManager = profilesManager;
this.asnInfoProviderSupplier = asnInfoProviderSupplier;
this.dynamicConfigurationManager = dynamicConfigurationManager;
this.profileBadgeConverter = profileBadgeConverter;
this.badgeConfigurationMap = badgesConfiguration.getBadges().stream()
.collect(Collectors.toMap(BadgeConfiguration::getId, Function.identity()));
this.badgeConfigurationMap = badgesConfiguration.getBadges().stream().collect(Collectors.toMap(
BadgeConfiguration::getId, Function.identity()));
this.serverSecretParams = serverSecretParams;
this.zkProfileOperations = zkProfileOperations;
this.policyGenerator = policyGenerator;
@@ -167,12 +161,10 @@ public class ProfileController {
description = "If the request changed the avatar, the response body contains an upload form.")))
@ApiResponse(responseCode = "400", description = "Invalid create profile request.")
@ApiResponse(responseCode = "401", description = "Account authentication check failed.")
@ApiResponse(responseCode = "403", description = "The request contained a payment address, but payments are not supported in the region of the account’s phone number or the caller's ASN if the account does not have a phone number.")
@ApiResponse(responseCode = "403", description = "The request contained a payment address, but payments are not supported in the region of the account’s phone number.")
@ApiResponse(responseCode = "412", description = "The requesting account has the profiles_v2 capability")
@ApiResponse(responseCode = "422", description = "Invalid request format")
public Response setProfile(@Auth AuthenticatedDevice auth,
@NotNull @Valid CreateProfileRequest request,
@Context final ContainerRequestContext requestContext) {
public Response setProfile(@Auth AuthenticatedDevice auth, @NotNull @Valid CreateProfileRequest request) {
final Account account = accountsManager.getByAccountIdentifier(auth.accountIdentifier())
.orElseThrow(() -> new WebApplicationException(Response.Status.UNAUTHORIZED));
@@ -184,12 +176,7 @@ public class ProfileController {
final Optional<VersionedProfileV1> currentProfile =
profilesManager.getV1(auth.accountIdentifier(), request.version());
final String remoteAddress = (String) requestContext.getProperty(RemoteAddressFilter.REMOTE_ADDRESS_ATTRIBUTE_NAME);
if (request.paymentAddress() != null &&
request.paymentAddress().length != 0 &&
ProfileHelper.isPaymentAddressUpdateForbidden(account, Optional.empty(), currentProfile, remoteAddress, asnInfoProviderSupplier.get(), dynamicConfigurationManager)) {
if (request.paymentAddress() != null && request.paymentAddress().length != 0 && ProfileHelper.isPaymentAddressUpdateForbidden(account, Optional.empty(), currentProfile, dynamicConfigurationManager)) {
return Response.status(Response.Status.FORBIDDEN).build();
}
@@ -211,7 +198,7 @@ public class ProfileController {
currentAvatar.ifPresent(profilesManager::deleteAvatar);
}
accountsManager.update(account.getAccountIdentifier(), a -> {
accountsManager.update(account.getIdentifier(IdentityType.ACI), a -> {
final List<AccountBadge> updatedBadges = request.badges()
.map(badges -> ProfileHelper.mergeBadgeIdsWithExistingAccountBadges(clock, badgeConfigurationMap, badges, a.getBadges()))
@@ -258,7 +245,7 @@ public class ProfileController {
return buildVersionedProfileResponse(targetAccount,
version,
maybeRequester.map(requester -> ProfileHelper.isSelfProfileRequest(requester.getAccountIdentifier(), accountIdentifier)).orElse(false),
maybeRequester.map(requester -> ProfileHelper.isSelfProfileRequest(requester.getUuid(), accountIdentifier)).orElse(false),
false,
containerRequestContext);
}
@@ -299,7 +286,7 @@ public class ProfileController {
.orElseThrow(() -> new WebApplicationException(Response.Status.UNAUTHORIZED)));
final Account targetAccount = verifyPermissionToReceiveProfile(maybeRequester, accessKey, accountIdentifier, "credentialRequest", userAgent);
final boolean isSelf = maybeRequester.map(requester -> ProfileHelper.isSelfProfileRequest(requester.getAccountIdentifier(), accountIdentifier)).orElse(false);
final boolean isSelf = maybeRequester.map(requester -> ProfileHelper.isSelfProfileRequest(requester.getUuid(), accountIdentifier)).orElse(false);
return buildExpiringProfileKeyCredentialProfileResponse(targetAccount,
version,
@@ -354,7 +341,7 @@ public class ProfileController {
}
return switch (identifier.identityType()) {
case ACI -> buildBaseProfileResponseForAccountIdentity(targetAccount,
maybeRequester.map(requester -> ProfileHelper.isSelfProfileRequest(requester.getAccountIdentifier(), identifier)).orElse(false),
maybeRequester.map(requester -> ProfileHelper.isSelfProfileRequest(requester.getUuid(), identifier)).orElse(false),
containerRequestContext);
case PNI -> buildBaseProfileResponseForPhoneNumberIdentity(targetAccount);
};
@@ -414,17 +401,11 @@ public class ProfileController {
final Optional<Account> maybeAccount = accountsManager.getByServiceIdentifier(identifier);
maybeAccount.ifPresent(account -> {
final Optional<IdentityKey> maybeIdentityKey = switch (identifier.identityType()) {
case ACI -> Optional.of(account.getAccountIdentityKey());
case PNI -> account.getPhoneNumberIdentityKey();
};
if (maybeIdentityKey.isEmpty()) {
final IdentityKey identityKey = account.getIdentityKey(identifier.identityType());
if (identityKey == null) {
return;
}
final IdentityKey identityKey = maybeIdentityKey.get();
md.reset();
byte[] digest = md.digest(identityKey.serialize());
byte[] fingerprint = Util.truncate(digest, 4);
@@ -445,13 +426,13 @@ public class ProfileController {
final ExpiringProfileKeyCredentialResponse expiringProfileKeyCredentialResponse;
if (account.getCurrentProfileVersion().map(v -> HexFormat.of().formatHex(v).equals(version)).orElse(false)) {
expiringProfileKeyCredentialResponse = profilesManager.getV1(account.getAccountIdentifier(), version)
expiringProfileKeyCredentialResponse = profilesManager.getV1(account.getUuid(), version)
.map(profile -> {
final ExpiringProfileKeyCredentialResponse profileKeyCredentialResponse;
try {
profileKeyCredentialResponse = ProfileHelper.getExpiringProfileKeyCredential(
new ProfileKeyCredentialRequest(HexFormat.of().parseHex(encodedCredentialRequest)),
new ProfileKeyCommitment(profile.commitment()), new ServiceId.Aci(account.getAccountIdentifier()),
new ProfileKeyCommitment(profile.commitment()), new ServiceId.Aci(account.getUuid()),
zkProfileOperations);
} catch (VerificationFailedException | InvalidInputException e) {
throw new BadRequestException(e);
@@ -474,7 +455,7 @@ public class ProfileController {
final boolean hasCredentialRequest,
final ContainerRequestContext containerRequestContext) {
final Optional<VersionedProfileV1> maybeProfile = profilesManager.getV1(account.getAccountIdentifier(), version);
final Optional<VersionedProfileV1> maybeProfile = profilesManager.getV1(account.getUuid(), version);
if (maybeProfile.isEmpty()) {
// this can happen if an account re-registers, which includes some device-transfer scenarios
@@ -509,7 +490,7 @@ public class ProfileController {
final boolean isSelf,
final ContainerRequestContext containerRequestContext) {
return new BaseProfileResponse(account.getAccountIdentityKey(),
return new BaseProfileResponse(account.getIdentityKey(IdentityType.ACI),
account.getUnidentifiedAccessKey().map(UnidentifiedAccessChecksum::generateFor).orElse(null),
account.isUnrestrictedUnidentifiedAccess(),
getAccountCapabilities(account),
@@ -517,18 +498,16 @@ public class ProfileController {
HeaderUtils.getAcceptableLanguagesForRequest(containerRequestContext),
account.getBadges(),
isSelf),
new AciServiceIdentifier(account.getAccountIdentifier()));
new AciServiceIdentifier(account.getUuid()));
}
private BaseProfileResponse buildBaseProfileResponseForPhoneNumberIdentity(final Account account) {
return new BaseProfileResponse(account.getPhoneNumberIdentityKey()
.orElseThrow(() -> new IllegalStateException("Account retrieved by PNI does not have PNI identity key")),
return new BaseProfileResponse(account.getIdentityKey(IdentityType.PNI),
null,
false,
getAccountCapabilities(account),
Collections.emptyList(),
new PniServiceIdentifier(account.getPhoneNumberIdentifier()
.orElseThrow(() -> new IllegalStateException("Account retrieved by PNI does not have PNI"))));
new PniServiceIdentifier(account.getPhoneNumberIdentifier()));
}
/**
@@ -558,7 +537,7 @@ public class ProfileController {
}
if (maybeRequester.isPresent()) {
rateLimiters.getProfileLimiter().validate(maybeRequester.get().getAccountIdentifier());
rateLimiters.getProfileLimiter().validate(maybeRequester.get().getUuid());
}
final Optional<Account> maybeTargetAccount = accountsManager.getByServiceIdentifier(accountIdentifier);
@@ -13,8 +13,6 @@ 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.enums.ParameterIn;
import io.swagger.v3.oas.annotations.headers.Header;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
@@ -36,19 +34,12 @@ import jakarta.ws.rs.core.Context;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
import java.io.IOException;
import java.time.Clock;
import java.time.Duration;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Optional;
import java.util.UUID;
import javax.annotation.Nullable;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.signal.libsignal.zkgroup.InvalidInputException;
import org.signal.libsignal.zkgroup.VerificationFailedException;
import org.signal.libsignal.zkgroup.receipts.ReceiptCredentialPresentation;
import org.signal.libsignal.zkgroup.receipts.ServerZkReceiptOperations;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.auth.BasicAuthorizationHeader;
@@ -58,7 +49,6 @@ import org.whispersystems.textsecuregcm.auth.RecoveryPasswordVerificationFailedE
import org.whispersystems.textsecuregcm.auth.RegistrationLockFailureException;
import org.whispersystems.textsecuregcm.auth.RegistrationLockVerificationManager;
import org.whispersystems.textsecuregcm.auth.UnverifiedRegistrationSessionException;
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
import org.whispersystems.textsecuregcm.entities.AccountCreationResponse;
import org.whispersystems.textsecuregcm.entities.AccountIdentityResponse;
import org.whispersystems.textsecuregcm.entities.PhoneVerificationRequest;
@@ -71,13 +61,7 @@ import org.whispersystems.textsecuregcm.spam.RegistrationFraudChecker;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.AccountsManager;
import org.whispersystems.textsecuregcm.storage.DeviceCapability;
import org.whispersystems.textsecuregcm.storage.DeviceIdentityInfo;
import org.whispersystems.textsecuregcm.storage.DeviceSpec;
import org.whispersystems.textsecuregcm.storage.DynamicConfigurationManager;
import org.whispersystems.textsecuregcm.storage.PhoneNumberRecoveryPasswordsManager;
import org.whispersystems.textsecuregcm.storage.ReceiptAlreadyRedeemedException;
import org.whispersystems.textsecuregcm.subscriptions.ReceiptCredentialPresentationFactory;
import org.whispersystems.textsecuregcm.subscriptions.ReceiptLevel;
import org.whispersystems.textsecuregcm.util.HeaderUtils;
import org.whispersystems.textsecuregcm.util.Util;
@@ -100,10 +84,6 @@ public class RegistrationController {
private final RegistrationLockVerificationManager registrationLockVerificationManager;
private final RateLimiters rateLimiters;
private final RegistrationFraudChecker registrationFraudChecker;
private final ReceiptCredentialPresentationFactory receiptCredentialPresentationFactory;
private final ServerZkReceiptOperations serverZkReceiptOperations;
private final Clock clock;
private final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager;
private static final Logger logger = LoggerFactory.getLogger(RegistrationController.class);
@@ -111,21 +91,13 @@ public class RegistrationController {
final PhoneVerificationTokenManager phoneVerificationTokenManager,
final RegistrationLockVerificationManager registrationLockVerificationManager,
final RateLimiters rateLimiters,
final RegistrationFraudChecker registrationFraudChecker,
final ReceiptCredentialPresentationFactory receiptCredentialPresentationFactory,
final ServerZkReceiptOperations serverZkReceiptOperations,
final Clock clock,
final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager) {
final RegistrationFraudChecker registrationFraudChecker) {
this.accounts = accounts;
this.phoneVerificationTokenManager = phoneVerificationTokenManager;
this.registrationLockVerificationManager = registrationLockVerificationManager;
this.rateLimiters = rateLimiters;
this.registrationFraudChecker = registrationFraudChecker;
this.receiptCredentialPresentationFactory = receiptCredentialPresentationFactory;
this.serverZkReceiptOperations = serverZkReceiptOperations;
this.clock = clock;
this.dynamicConfigurationManager = dynamicConfigurationManager;
}
@POST
@@ -140,8 +112,7 @@ public class RegistrationController {
3. success \n
""")
@ApiResponse(responseCode = "200", description = "Account creation succeeded", useReturnTypeSchema = true)
@ApiResponse(responseCode = "400", description = "Invalid session ID or receipt credential presentation")
@ApiResponse(responseCode = "401", description = "The session identified in the request is not verified, or the receipt credential presented fails verification, is expired, or is already redeemed")
@ApiResponse(responseCode = "401", description = "The session identified in the request is not verified")
@ApiResponse(responseCode = "403", description = "Verification failed for the provided Registration Recovery Password")
@ApiResponse(responseCode = "409", description = "The caller has not explicitly elected to skip transferring data from another device, but a device transfer is technically possible")
@ApiResponse(responseCode = "422", description = "The request did not pass validation")
@@ -149,23 +120,8 @@ public class RegistrationController {
@ApiResponse(responseCode = "429", description = "Too many attempts", headers = @Header(
name = "Retry-After",
description = "If present, an positive integer indicating the number of seconds before a subsequent attempt could succeed"))
@ApiResponse(responseCode = "441", description = "A valid one-time password (TOTP) is required, but either no password was provided or it was incorrect")
@ApiResponse(responseCode = "499", description = "Client must support post-quantum ratchet")
public AccountCreationResponse register(
@Parameter(
in = ParameterIn.HEADER,
name = HttpHeaders.AUTHORIZATION,
description = """
The basic auth header. For accounts with a phone number, the username must be the e164-formatted number that
is being registered. For accounts without a phone number, the username is ignored on a fresh registration
(it must be present, however, so any string that can't be parsed as an e164-formatted phone number or UUID
is acceptable; "__no_number__" is recommended). For account recovery (re-registration) by ACI, it must be
set to the ACI of the account being recovered. In all cases, the password is the password to be used for
primary device authentication.
""",
required = true,
schema = @Schema(type = "string")
)
@HeaderParam(HttpHeaders.AUTHORIZATION) @NotNull final BasicAuthorizationHeader authorizationHeader,
@HeaderParam(HeaderUtils.X_SIGNAL_AGENT) final String signalAgent,
@HeaderParam(HttpHeaders.USER_AGENT) final String userAgent,
@@ -173,6 +129,9 @@ public class RegistrationController {
@Context final ContainerRequestContext requestContext)
throws RateLimitExceededException, InterruptedException, RegistrationLockFailureException {
final String number = authorizationHeader.getUsername();
final String password = authorizationHeader.getPassword();
if (!registrationRequest.isEverySignedKeyValid(userAgent)) {
throw new WebApplicationException("Invalid signature", 422);
}
@@ -184,47 +143,7 @@ public class RegistrationController {
throw new WebApplicationException("Missing required device capability", 499);
}
final AccountCreationResponse response;
if (registrationRequest.receiptCredentialPresentation() != null && registrationRequest.receiptCredentialPresentation().length > 0) {
// A receipt credential presentation will only be present if the caller is trying to register a new account
// without a phone number, in which case we can (and must) ignore the "username" in the authentication header.
response = registerAccountWithoutNumber(authorizationHeader.getPassword(), registrationRequest, userAgent, signalAgent);
} else {
// The caller is either trying to register a new account with a phone number or recover an account by ACI. Either
// way, the "username" from the auth header is meaningful.
@Nullable UUID recoveredAccountIdentifier;
try {
recoveredAccountIdentifier = UUID.fromString(authorizationHeader.getUsername());
} catch (final IllegalArgumentException _) {
// The provided username is either a phone number or a nonsense string (for registration without a phone number)
recoveredAccountIdentifier = null;
}
if (recoveredAccountIdentifier != null) {
response = recoverAccount(recoveredAccountIdentifier, authorizationHeader.getPassword(), registrationRequest, userAgent, signalAgent);
} else {
response = registerAccountWithNumber(authorizationHeader.getUsername(), authorizationHeader.getPassword(), registrationRequest, requestContext, userAgent, signalAgent);
}
}
return response;
}
private AccountCreationResponse registerAccountWithNumber(
final String number,
final String password,
final RegistrationRequest registrationRequest,
final ContainerRequestContext requestContext,
final String userAgent,
final String signalAgent)
throws RateLimitExceededException, InterruptedException, RegistrationLockFailureException {
if (registrationRequest.pniIdentityKey() == null) {
// RegistrationRequest checks that either all phone number-associated information is present or all is absent
throw new WebApplicationException("PNI keys and registration ID must be provided", 422);
}
rateLimiters.getRegistrationLimiter().validate(number);
final PhoneVerificationRequest.VerificationType verificationType;
try {
@@ -245,8 +164,6 @@ public class RegistrationController {
throw new ForbiddenException("recovery password could not be verified");
}
rateLimiters.getRegistrationLimiter().validate(number);
// There can be at most one existing account for a set of numbers in the same equivalence class, so it's sufficient
// to find the first one.
final Optional<Account> existingAccount = Util.getAlternateForms(number)
@@ -269,16 +186,14 @@ public class RegistrationController {
}
if (existingAccount.isPresent()) {
assert existingAccount.get().getNumber().isPresent();
registrationLockVerificationManager.verifyRegistrationLock(existingAccount.get(),
registrationRequest.accountAttributes().getRegistrationLock(),
userAgent, RegistrationLockVerificationManager.Flow.REGISTRATION, verificationType);
checkTotp(existingAccount.get(), registrationRequest.totp());
}
final Account account = accounts.create(number,
registrationRequest.accountAttributes(),
existingAccount.map(Account::getBadges).orElseGet(ArrayList::new),
registrationRequest.aciIdentityKey(),
registrationRequest.pniIdentityKey(),
new DeviceSpec(
@@ -286,18 +201,15 @@ public class RegistrationController {
password,
signalAgent,
registrationRequest.accountAttributes().getCapabilities(),
new DeviceIdentityInfo(
registrationRequest.accountAttributes().getRegistrationId(),
registrationRequest.deviceActivationRequest().aciSignedPreKey(),
registrationRequest.deviceActivationRequest().aciPqLastResortPreKey()),
Optional.of(new DeviceIdentityInfo(
registrationRequest.accountAttributes().getPhoneNumberIdentityRegistrationId().get(),
// We've already validated the presence of PNI keys by this point
registrationRequest.deviceActivationRequest().pniSignedPreKey().get(),
registrationRequest.deviceActivationRequest().pniPqLastResortPreKey().get())),
registrationRequest.accountAttributes().getRegistrationId(),
registrationRequest.accountAttributes().getPhoneNumberIdentityRegistrationId(),
registrationRequest.accountAttributes().getFetchesMessages(),
registrationRequest.deviceActivationRequest().apnToken(),
registrationRequest.deviceActivationRequest().gcmToken()),
registrationRequest.deviceActivationRequest().gcmToken(),
registrationRequest.deviceActivationRequest().aciSignedPreKey(),
registrationRequest.deviceActivationRequest().pniSignedPreKey(),
registrationRequest.deviceActivationRequest().aciPqLastResortPreKey(),
registrationRequest.deviceActivationRequest().pniPqLastResortPreKey()),
userAgent);
if (verificationType == PhoneVerificationRequest.VerificationType.SESSION) {
@@ -324,195 +236,4 @@ public class RegistrationController {
return new AccountCreationResponse(identityResponse, existingAccount.isPresent());
}
private AccountCreationResponse registerAccountWithoutNumber(
final String password,
final RegistrationRequest registrationRequest,
final String userAgent,
final String signalAgent) {
if (!dynamicConfigurationManager.getConfiguration().getLoginPurchaseConfiguration().enabled()) {
throw new BadRequestException("login purchases are not enabled");
}
registrationRequest.accountAttributes().recoveryPassword()
.filter(ArrayUtils::isNotEmpty)
.orElseThrow(() -> new WebApplicationException("Account recovery password is required", 422));
final ReceiptCredentialPresentation receiptCredentialPresentation;
try {
receiptCredentialPresentation = receiptCredentialPresentationFactory
.build(registrationRequest.receiptCredentialPresentation());
} catch (InvalidInputException _) {
throw new BadRequestException("Invalid receipt credential presentation");
}
try {
serverZkReceiptOperations.verifyReceiptCredentialPresentation(receiptCredentialPresentation);
} catch (VerificationFailedException _) {
throw new NotAuthorizedException("Receipt credential presentation verification failed");
}
final Instant receiptExpiration = Instant.ofEpochSecond(receiptCredentialPresentation.getReceiptExpirationTime());
if (clock.instant().isAfter(receiptExpiration)) {
throw new NotAuthorizedException("Receipt is already expired");
}
final long receiptLevel = receiptCredentialPresentation.getReceiptLevel();
if (receiptLevel != ReceiptLevel.LOGIN.getValue()) {
throw new BadRequestException("Invalid receipt level");
}
try {
final Account account = accounts.create(
registrationRequest.accountAttributes(),
registrationRequest.aciIdentityKey(),
receiptCredentialPresentation,
new DeviceSpec(
registrationRequest.accountAttributes().getName(),
password,
signalAgent,
registrationRequest.accountAttributes().getCapabilities(),
new DeviceIdentityInfo(registrationRequest.accountAttributes().getRegistrationId(), registrationRequest.deviceActivationRequest()
.aciSignedPreKey(), registrationRequest.deviceActivationRequest().aciPqLastResortPreKey()),
Optional.empty(),
registrationRequest.accountAttributes().getFetchesMessages(),
registrationRequest.deviceActivationRequest().apnToken(),
registrationRequest.deviceActivationRequest().gcmToken()),
userAgent);
Metrics.counter(ACCOUNT_CREATED_COUNTER_NAME, Tags.of(UserAgentTagUtil.getPlatformTag(userAgent),
Tag.of(VERIFICATION_TYPE_TAG_NAME, registrationRequest.verificationType().name())))
.increment();
final AccountIdentityResponse accountIdentityResponse = new AccountIdentityResponseBuilder(account).build();
return new AccountCreationResponse(accountIdentityResponse, false);
} catch (ReceiptAlreadyRedeemedException _) {
throw new NotAuthorizedException("Receipt already redeemed");
}
}
private AccountCreationResponse recoverAccount(final UUID accountIdentifier,
final String password,
final RegistrationRequest registrationRequest,
final String userAgent,
final String signalAgent) throws RegistrationLockFailureException, RateLimitExceededException {
if (!dynamicConfigurationManager.getConfiguration().getLoginPurchaseConfiguration().enabled()) {
throw new BadRequestException("login purchases are not enabled");
}
if (ArrayUtils.isEmpty(registrationRequest.recoveryPassword())) {
throw new BadRequestException("Recovery password required for authentication when recovering an account by identifier");
}
if (registrationRequest.accountAttributes().recoveryPassword().isEmpty()) {
throw new BadRequestException("Recovery password required for for storage when recovering an account by identifier");
}
if (registrationRequest.pniIdentityKey() == null) {
throw new BadRequestException("Must specify a PNI-associated identity key when recovering an account by identifier");
}
final Account existingAccount = accounts.getByAccountIdentifier(accountIdentifier)
.orElseThrow(ForbiddenException::new);
final boolean passwordVerified = existingAccount.getAccountRecoveryPassword()
.map(saltedRecoveryPasswordHash -> PhoneNumberRecoveryPasswordsManager.verify(saltedRecoveryPasswordHash, registrationRequest.recoveryPassword()))
.orElse(false);
if (!passwordVerified) {
throw new ForbiddenException();
}
checkTotp(existingAccount, registrationRequest.totp());
if (!registrationRequest.skipDeviceTransfer() && existingAccount.hasCapability(DeviceCapability.TRANSFER)) {
// If a device transfer is possible, clients must explicitly opt out of a transfer (i.e. after prompting the user)
// before we'll let them recover an account and start "from scratch"
throw new WebApplicationException(Response.status(409, "device transfer available").build());
}
final Account reclaimedAccount = existingAccount.getNumber().isPresent()
? recoverAccountWithPhoneNumber(existingAccount, registrationRequest, password, userAgent, signalAgent)
: recoverAccountWithoutPhoneNumber(existingAccount, registrationRequest, password, userAgent, signalAgent);
Metrics.counter(ACCOUNT_CREATED_COUNTER_NAME, Tags.of(UserAgentTagUtil.getPlatformTag(userAgent),
Tag.of(VERIFICATION_TYPE_TAG_NAME, registrationRequest.verificationType().name())))
.increment();
return new AccountCreationResponse(new AccountIdentityResponseBuilder(reclaimedAccount)
.storageCapable(existingAccount.hasCapability(DeviceCapability.STORAGE))
.build(), true);
}
private Account recoverAccountWithoutPhoneNumber(final Account existingAccount,
final RegistrationRequest registrationRequest,
final String password,
final String userAgent,
final String signalAgent) {
return accounts.recover(existingAccount,
registrationRequest.accountAttributes(),
registrationRequest.aciIdentityKey(),
Optional.empty(),
new DeviceSpec(
registrationRequest.accountAttributes().getName(),
password,
signalAgent,
registrationRequest.accountAttributes().getCapabilities(),
new DeviceIdentityInfo(
registrationRequest.accountAttributes().getRegistrationId(),
registrationRequest.deviceActivationRequest().aciSignedPreKey(),
registrationRequest.deviceActivationRequest().aciPqLastResortPreKey()),
Optional.empty(),
registrationRequest.accountAttributes().getFetchesMessages(),
registrationRequest.deviceActivationRequest().apnToken(),
registrationRequest.deviceActivationRequest().gcmToken()),
userAgent);
}
private Account recoverAccountWithPhoneNumber(final Account existingAccount,
final RegistrationRequest registrationRequest,
final String password,
final String userAgent,
final String signalAgent) throws RegistrationLockFailureException, RateLimitExceededException {
registrationLockVerificationManager.verifyRegistrationLock(existingAccount,
registrationRequest.accountAttributes().getRegistrationLock(),
userAgent,
RegistrationLockVerificationManager.Flow.REGISTRATION,
PhoneVerificationRequest.VerificationType.RECOVERY_PASSWORD);
assert registrationRequest.pniIdentityKey() != null;
return accounts.recover(existingAccount,
registrationRequest.accountAttributes(),
registrationRequest.aciIdentityKey(),
Optional.of(registrationRequest.pniIdentityKey()),
new DeviceSpec(
registrationRequest.accountAttributes().getName(),
password,
signalAgent,
registrationRequest.accountAttributes().getCapabilities(),
new DeviceIdentityInfo(
registrationRequest.accountAttributes().getRegistrationId(),
registrationRequest.deviceActivationRequest().aciSignedPreKey(),
registrationRequest.deviceActivationRequest().aciPqLastResortPreKey()),
Optional.of(new DeviceIdentityInfo(
registrationRequest.accountAttributes().getPhoneNumberIdentityRegistrationId().get(),
// We've already validated the presence of PNI keys by this point
registrationRequest.deviceActivationRequest().pniSignedPreKey().orElseThrow(),
registrationRequest.deviceActivationRequest().pniPqLastResortPreKey().orElseThrow())),
registrationRequest.accountAttributes().getFetchesMessages(),
registrationRequest.deviceActivationRequest().apnToken(),
registrationRequest.deviceActivationRequest().gcmToken()),
userAgent);
}
private void checkTotp(final Account account, @Nullable final Integer totp) throws RateLimitExceededException {
rateLimiters.getCheckTotpLimiter().validate(account.getAccountIdentifier());
if (!accounts.verifyTotp(account, clock.instant(), totp)) {
throw new WebApplicationException(441);
}
}
}
@@ -5,6 +5,7 @@
package org.whispersystems.textsecuregcm.controllers;
import com.google.common.annotations.VisibleForTesting;
import io.dropwizard.auth.Auth;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
@@ -21,21 +22,45 @@ import jakarta.ws.rs.core.EntityTag;
import jakarta.ws.rs.core.HttpHeaders;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.HexFormat;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import javax.annotation.Nullable;
import org.apache.commons.lang3.tuple.Pair;
import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
import org.whispersystems.textsecuregcm.entities.RemoteConfigurationResponse;
import org.whispersystems.textsecuregcm.storage.RemoteConfig;
import org.whispersystems.textsecuregcm.storage.RemoteConfigsManager;
import org.whispersystems.textsecuregcm.util.Conversions;
import org.whispersystems.textsecuregcm.util.Util;
import org.whispersystems.textsecuregcm.util.ua.ClientPlatform;
import org.whispersystems.textsecuregcm.util.ua.UnrecognizedUserAgentException;
import org.whispersystems.textsecuregcm.util.ua.UserAgentUtil;
@Path("/v2/config")
@Tag(name = "Remote Config")
public class RemoteConfigController {
private final RemoteConfigsManager remoteConfigsManager;
private final Map<String, String> globalConfig;
public RemoteConfigController(RemoteConfigsManager remoteConfigsManager) {
private static final String GLOBAL_CONFIG_PREFIX = "global.";
private static final Set<String> PLATFORM_PREFIXES = Arrays.stream(ClientPlatform.values())
.map(p -> p.name().toLowerCase())
.collect(Collectors.toSet());
public RemoteConfigController(RemoteConfigsManager remoteConfigsManager, Map<String, String> globalConfig) {
this.remoteConfigsManager = remoteConfigsManager;
this.globalConfig = globalConfig;
}
@GET
@@ -63,17 +88,69 @@ public class RemoteConfigController {
@HeaderParam(HttpHeaders.USER_AGENT)
String userAgent
) {
final String platformPrefix = platformPrefix(userAgent);
final List<RemoteConfig> remoteConfigs = remoteConfigsManager.getAll();
final Map<String, String> configs = remoteConfigsManager.getConfigForAccount(auth.accountIdentifier(), userAgent);
try {
MessageDigest digest = MessageDigest.getInstance("SHA-256");
final EntityTag newETag = new EntityTag(HexFormat.of().toHexDigits(configs.hashCode()));
if (newETag.equals(eTag)) {
return Response.notModified(eTag).build();
final Map<String, String> configs = Stream.concat(
remoteConfigs.stream()
.filter(config -> {
final String firstNameComponent = config.getName().split("\\.", 2)[0];
return firstNameComponent.equals(platformPrefix) || !PLATFORM_PREFIXES.contains(firstNameComponent);
})
.map(
config -> {
final byte[] hashKey = config.getHashKey() != null
? config.getHashKey().getBytes(StandardCharsets.UTF_8)
: config.getName().getBytes(StandardCharsets.UTF_8);
boolean inBucket = isInBucket(digest, auth.accountIdentifier(), hashKey, config.getPercentage(), config.getUuids());
final String value = inBucket ? config.getValue() : config.getDefaultValue();
return Pair.of(config.getName(), value == null ? String.valueOf(inBucket) : value);
}),
globalConfig.entrySet().stream()
.map(e -> Pair.of(GLOBAL_CONFIG_PREFIX + e.getKey(), e.getValue())))
.collect(Collectors.toMap(Pair::getLeft, Pair::getRight));
final EntityTag newETag = new EntityTag(HexFormat.of().toHexDigits(configs.hashCode()));
if (newETag.equals(eTag)) {
return Response.notModified(eTag).build();
}
return Response.ok(new RemoteConfigurationResponse(configs))
.tag(newETag)
.build();
} catch (NoSuchAlgorithmException e) {
throw new AssertionError(e);
}
}
private static String platformPrefix(final String userAgent) {
try {
return UserAgentUtil.parseUserAgentString(userAgent).platform().name().toLowerCase();
} catch (UnrecognizedUserAgentException e) {
return null;
}
}
@VisibleForTesting
public static boolean isInBucket(MessageDigest digest, UUID uid, byte[] hashKey, int configPercentage,
Set<UUID> uuidsInBucket) {
if (uuidsInBucket.contains(uid)) {
return true;
}
return Response.ok(new RemoteConfigurationResponse(configs))
.tag(newETag)
.build();
ByteBuffer bb = ByteBuffer.allocate(16);
bb.putLong(uid.getMostSignificantBits());
bb.putLong(uid.getLeastSignificantBits());
digest.update(bb.array());
byte[] hash = digest.digest(hashKey);
int bucket = (int) (Util.ensureNonNegativeLong(Conversions.byteArrayToLong(hash)) % 100);
return bucket < configPercentage;
}
}
@@ -28,7 +28,6 @@ import java.time.Clock;
import java.time.Duration;
import java.time.Instant;
import java.util.Comparator;
import java.util.HashSet;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
@@ -119,14 +118,14 @@ public class SecureValueRecovery2Controller {
@HeaderParam(HttpHeaders.USER_AGENT) final String userAgent,
@NotNull @Valid final AuthCheckRequest request) {
final List<ExternalServiceCredentialsSelector.CredentialInfo> credentials = ExternalServiceCredentialsSelector.check(
new HashSet<>(request.tokens()),
request.tokens(),
backupServiceCredentialGenerator,
MAX_AGE.getSeconds());
// the username associated with the provided number
final Optional<String> matchingUsername = accountsManager
.getByE164(request.number())
.map(Account::getAccountIdentifier)
.map(Account::getUuid)
.map(backupServiceCredentialGenerator::generateForUuid)
.map(ExternalServiceCredentials::username);
@@ -49,6 +49,7 @@ import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
import jakarta.ws.rs.core.Response.Status;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.math.BigDecimal;
import java.time.Clock;
import java.time.Instant;
@@ -65,7 +66,6 @@ import org.signal.libsignal.zkgroup.receipts.ReceiptCredentialResponse;
import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
import org.whispersystems.textsecuregcm.auth.DonationPermitHeader;
import org.whispersystems.textsecuregcm.badges.BadgeTranslator;
import org.whispersystems.textsecuregcm.configuration.LoginPurchaseConfiguration;
import org.whispersystems.textsecuregcm.configuration.OneTimeDonationConfiguration;
import org.whispersystems.textsecuregcm.configuration.SubscriptionConfiguration;
import org.whispersystems.textsecuregcm.configuration.SubscriptionLevelConfiguration;
@@ -91,7 +91,6 @@ import org.whispersystems.textsecuregcm.subscriptions.LevelConfiguration;
import org.whispersystems.textsecuregcm.subscriptions.PaymentMethod;
import org.whispersystems.textsecuregcm.subscriptions.PaymentProvider;
import org.whispersystems.textsecuregcm.subscriptions.ProcessorCustomer;
import org.whispersystems.textsecuregcm.subscriptions.ReceiptLevel;
import org.whispersystems.textsecuregcm.subscriptions.StripeManager;
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionException;
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionInvalidArgumentsException;
@@ -107,7 +106,6 @@ public class SubscriptionController {
private final Clock clock;
private final SubscriptionConfiguration subscriptionConfiguration;
private final OneTimeDonationConfiguration oneTimeDonationConfiguration;
private final LoginPurchaseConfiguration loginPurchaseConfiguration;
private final SubscriptionManager subscriptionManager;
private final StripeManager stripeManager;
private final BraintreeManager braintreeManager;
@@ -126,7 +124,6 @@ public class SubscriptionController {
Clock clock,
SubscriptionConfiguration subscriptionConfiguration,
OneTimeDonationConfiguration oneTimeDonationConfiguration,
LoginPurchaseConfiguration loginPurchaseConfiguration,
SubscriptionManager subscriptionManager,
StripeManager stripeManager,
BraintreeManager braintreeManager,
@@ -140,7 +137,6 @@ public class SubscriptionController {
this.clock = Objects.requireNonNull(clock);
this.subscriptionConfiguration = Objects.requireNonNull(subscriptionConfiguration);
this.oneTimeDonationConfiguration = Objects.requireNonNull(oneTimeDonationConfiguration);
this.loginPurchaseConfiguration = Objects.requireNonNull(loginPurchaseConfiguration);
this.stripeManager = Objects.requireNonNull(stripeManager);
this.braintreeManager = Objects.requireNonNull(braintreeManager);
this.googlePlayBillingManager = Objects.requireNonNull(googlePlayBillingManager);
@@ -171,10 +167,6 @@ public class SubscriptionController {
buildDonationLevelsConfiguration(subscriptionConfiguration, oneTimeDonationConfiguration, badgeTranslator,
acceptableLanguages),
new BackupConfiguration(backupLevels, subscriptionConfiguration.getbackupFreeTierMediaDuration().toDays()),
new LoginConfiguration(ReceiptLevel.LOGIN.getValue(),
loginPurchaseConfiguration.playProductId(),
loginPurchaseConfiguration.playOptionId(),
loginPurchaseConfiguration.appStoreProductId()),
oneTimeDonationConfiguration.sepaMaximumEuros());
}
@@ -540,22 +532,9 @@ public class SubscriptionController {
Map<Long, LevelConfiguration> levels,
@Schema(description = "Backup specific configuration")
BackupConfiguration backup,
@Schema(description = "Signal Login specific configuration")
LoginConfiguration login,
@Schema(description = "The maximum value of a one-time donation SEPA transaction")
BigDecimal sepaMaximumEuros) {}
@Schema(description = "Configuration for one-time Signal Login purchases")
public record LoginConfiguration(
@Schema(description = "The receipt level associated with a Signal Login purchase")
long level,
@Schema(description = "The play billing productID associated with a Signal Login purchase")
String playProductId,
@Schema(description = "The play billing optionID to use to purchase a Signal Login")
String playOptionId,
@Schema(description = "The App Store productID associated with a Signal Login purchase")
String appStoreProductId) {}
public record BackupConfiguration(
@Schema(description = "A map of numeric backup level IDs to level-specific backup configuration")
Map<String, BackupLevelConfiguration> levels,
@@ -97,7 +97,7 @@ import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.AccountsManager;
import org.whispersystems.textsecuregcm.storage.DynamicConfigurationManager;
import org.whispersystems.textsecuregcm.storage.PhoneNumberIdentifiers;
import org.whispersystems.textsecuregcm.storage.PhoneNumberRecoveryPasswordsManager;
import org.whispersystems.textsecuregcm.storage.RegistrationRecoveryPasswordsManager;
import org.whispersystems.textsecuregcm.storage.VerificationSessionManager;
import org.whispersystems.textsecuregcm.telephony.CarrierData;
import org.whispersystems.textsecuregcm.telephony.CarrierDataException;
@@ -139,7 +139,7 @@ public class VerificationController {
private final VerificationSessionManager verificationSessionManager;
private final PushNotificationManager pushNotificationManager;
private final RegistrationCaptchaManager registrationCaptchaManager;
private final PhoneNumberRecoveryPasswordsManager phoneNumberRecoveryPasswordsManager;
private final RegistrationRecoveryPasswordsManager registrationRecoveryPasswordsManager;
private final PhoneNumberIdentifiers phoneNumberIdentifiers;
private final RateLimiters rateLimiters;
private final AccountsManager accountsManager;
@@ -153,7 +153,7 @@ public class VerificationController {
final VerificationSessionManager verificationSessionManager,
final PushNotificationManager pushNotificationManager,
final RegistrationCaptchaManager registrationCaptchaManager,
final PhoneNumberRecoveryPasswordsManager phoneNumberRecoveryPasswordsManager,
final RegistrationRecoveryPasswordsManager registrationRecoveryPasswordsManager,
final PhoneNumberIdentifiers phoneNumberIdentifiers,
final RateLimiters rateLimiters,
final AccountsManager accountsManager,
@@ -166,7 +166,7 @@ public class VerificationController {
this.verificationSessionManager = verificationSessionManager;
this.pushNotificationManager = pushNotificationManager;
this.registrationCaptchaManager = registrationCaptchaManager;
this.phoneNumberRecoveryPasswordsManager = phoneNumberRecoveryPasswordsManager;
this.registrationRecoveryPasswordsManager = registrationRecoveryPasswordsManager;
this.phoneNumberIdentifiers = phoneNumberIdentifiers;
this.rateLimiters = rateLimiters;
this.accountsManager = accountsManager;
@@ -666,7 +666,7 @@ public class VerificationController {
accountsManager.getByE164(registrationServiceSession.number())
.filter(existingAccount ->
experimentEnrollmentManager.isEnrolled(existingAccount.getAccountIdentifier(), VERIFICATION_CODE_PUSH_NOTIFICATION_EXPERIMENT_NAME))
experimentEnrollmentManager.isEnrolled(existingAccount.getIdentifier(IdentityType.ACI), VERIFICATION_CODE_PUSH_NOTIFICATION_EXPERIMENT_NAME))
.ifPresent(existingAccount -> {
try {
pushNotificationManager.sendVerificationCodeRequestedNotifications(existingAccount, clock.instant());
@@ -749,10 +749,7 @@ public class VerificationController {
// the RRP. It's possible the client will not actually be able to register (e.g. failed reglock challenge), and
// so we will have removed the RRP unnecessarily. The impact of this is low, since the owner of the RRP
// can always just fallback to session-based verification.
//
// Note that we do not remove the recovery password from the account itself because re-creation is imminent, and
// that process will overwrite the recovery password (along with the rest of the account record).
existingRRP = phoneNumberRecoveryPasswordsManager.remove(phoneNumberIdentifiers.getPhoneNumberIdentifier(registrationServiceSession.number()).join());
existingRRP = registrationRecoveryPasswordsManager.remove(phoneNumberIdentifiers.getPhoneNumberIdentifier(registrationServiceSession.number()).join());
}
Optional<Account> maybeExistingAccount;
@@ -827,10 +824,7 @@ public class VerificationController {
// the RRP. It's possible the client will not actually be able to register (e.g. failed reglock challenge), and
// so we will have removed the RRP unnecessarily. The impact of this is low, since the owner of the RRP
// can always just fallback to session-based verification.
//
// Note that we do not remove the recovery password from the account itself because re-creation is imminent, and
// that process will overwrite the recovery password (along with the rest of the account record).
phoneNumberRecoveryPasswordsManager.remove(phoneNumberIdentifiers.getPhoneNumberIdentifier(registrationServiceSession.number()).join());
registrationRecoveryPasswordsManager.remove(phoneNumberIdentifiers.getPhoneNumberIdentifier(registrationServiceSession.number()).join());
}
return registrationServiceSession;
@@ -14,7 +14,6 @@ import jakarta.validation.constraints.AssertTrue;
import java.util.Optional;
import java.util.Set;
import javax.annotation.Nullable;
import org.apache.commons.lang3.ArrayUtils;
import org.whispersystems.textsecuregcm.auth.UnidentifiedAccessUtil;
import org.whispersystems.textsecuregcm.storage.DeviceCapability;
import org.whispersystems.textsecuregcm.util.ByteArrayAdapter;
@@ -53,17 +52,15 @@ public class AccountAttributes {
public AccountAttributes(
final boolean fetchesMessages,
final int registrationId,
final Integer phoneNumberIdentifierRegistrationId,
final int phoneNumberIdentifierRegistrationId,
final byte[] name,
final String registrationLock,
final boolean discoverableByPhoneNumber,
final Set<DeviceCapability> capabilities,
@Nullable final byte[] recoveryPassword) {
final Set<DeviceCapability> capabilities) {
this.deviceAttributes = new DeviceAttributes(fetchesMessages, registrationId, phoneNumberIdentifierRegistrationId, name, capabilities);
this.registrationLock = registrationLock;
this.discoverableByPhoneNumber = discoverableByPhoneNumber;
this.recoveryPassword = recoveryPassword;
}
public boolean getFetchesMessages() {
@@ -74,8 +71,8 @@ public class AccountAttributes {
return deviceAttributes.registrationId();
}
public Optional<Integer> getPhoneNumberIdentityRegistrationId() {
return Optional.ofNullable(deviceAttributes.phoneNumberIdentityRegistrationId());
public int getPhoneNumberIdentityRegistrationId() {
return deviceAttributes.phoneNumberIdentityRegistrationId();
}
public byte[] getName() {
@@ -104,7 +101,7 @@ public class AccountAttributes {
}
public Optional<byte[]> recoveryPassword() {
return Optional.ofNullable(recoveryPassword).filter(ArrayUtils::isNotEmpty);
return Optional.ofNullable(recoveryPassword);
}
@VisibleForTesting
@@ -131,11 +128,6 @@ public class AccountAttributes {
return this;
}
public AccountAttributes setDiscoverableByPhoneNumber(final boolean discoverableByPhoneNumber) {
this.discoverableByPhoneNumber = discoverableByPhoneNumber;
return this;
}
@AssertTrue
@Schema(hidden = true)
public boolean isUnrestrictedUakValid() {
@@ -13,7 +13,6 @@ import io.swagger.v3.oas.annotations.media.Schema;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.List;
import java.util.Optional;
import java.util.UUID;
import javax.annotation.Nullable;
import org.whispersystems.textsecuregcm.storage.AccountBadge;
@@ -37,24 +36,21 @@ public record AccountDataReportResponse(UUID reportId,
builder.append(String.format("""
Report ID: %s
Report timestamp: %s
""",
reportId,
reportTimestamp.truncatedTo(ChronoUnit.SECONDS)));
// account
builder.append("# Account\n");
data.account.phoneNumber().ifPresent(phoneNumber -> {
builder.append(String.format("""
Phone number: %s
Find account by phone number: %s
""",
phoneNumber,
data.account.findAccountByPhoneNumber()));
});
builder.append(String.format("Allow sealed sender from anyone: %s%n", data.account.allowSealedSenderFromAnyone()));
builder.append(String.format("""
# Account
Phone number: %s
Allow sealed sender from anyone: %s
Find account by phone number: %s
""",
data.account.phoneNumber(),
data.account.allowSealedSenderFromAnyone(),
data.account.findAccountByPhoneNumber()));
// badges
builder.append("Badges:");
@@ -97,10 +93,9 @@ public record AccountDataReportResponse(UUID reportId,
}
public record AccountDataReport(Optional<String> phoneNumber,
List<BadgeDataReport> badges,
boolean allowSealedSenderFromAnyone,
public record AccountDataReport(String phoneNumber, List<BadgeDataReport> badges, boolean allowSealedSenderFromAnyone,
boolean findAccountByPhoneNumber) {
}
public record DeviceDataReport(byte id,
@@ -8,7 +8,6 @@ package org.whispersystems.textsecuregcm.entities;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import io.swagger.v3.oas.annotations.media.Schema;
import java.util.Optional;
import java.util.UUID;
import javax.annotation.Nullable;
import org.whispersystems.textsecuregcm.util.ByteArrayBase64UrlAdapter;
@@ -17,11 +16,11 @@ public record AccountIdentityResponse(
@Schema(description = "the account identifier for this account")
UUID uuid,
@Schema(description = "the phone number associated with this account; may be null if this account does not have a phone number")
Optional<String> number,
@Schema(description = "the phone number associated with this account")
String number,
@Schema(description = "the account identifier for this account's phone-number identity; may be null if this account does not have a phone number")
Optional<UUID> pni,
@Schema(description = "the account identifier for this account's phone-number identity")
UUID pni,
@Schema(description = "a hash of this account's username, if set")
@JsonSerialize(using = ByteArrayBase64UrlAdapter.Serializing.class)
@@ -35,8 +34,5 @@ public record AccountIdentityResponse(
boolean storageCapable,
@Schema(description = "entitlements for this account and their current expirations")
Entitlements entitlements,
@Schema(description = "salt to generate PNI auth credentials for accounts without a phone number; null if this account has a phone number")
@Nullable byte[] authCredentialSalt) {
Entitlements entitlements) {
}
@@ -1,8 +1,10 @@
package org.whispersystems.textsecuregcm.entities;
import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.validation.Valid;
import jakarta.validation.constraints.NotNull;
import java.util.Optional;
public record DeviceActivationRequest(
@@ -13,10 +15,12 @@ public record DeviceActivationRequest(
""")
ECSignedPreKey aciSignedPreKey,
@Schema(requiredMode = Schema.RequiredMode.NOT_REQUIRED, description = """
If the account has a phone number, a signed EC pre-key to be associated with this account's PNI.
@NotNull
@Valid
@Schema(requiredMode = Schema.RequiredMode.REQUIRED, description = """
A signed EC pre-key to be associated with this account's PNI.
""")
Optional<@Valid ECSignedPreKey> pniSignedPreKey,
ECSignedPreKey pniSignedPreKey,
@NotNull
@Valid
@@ -25,10 +29,12 @@ public record DeviceActivationRequest(
""")
KEMSignedPreKey aciPqLastResortPreKey,
@Schema(requiredMode = Schema.RequiredMode.NOT_REQUIRED, description = """
If the account has a phone number, a signed Kyber-1024 "last resort" pre-key to be associated with this account's PNI.
@NotNull
@Valid
@Schema(requiredMode = Schema.RequiredMode.REQUIRED, description = """
A signed Kyber-1024 "last resort" pre-key to be associated with this account's PNI.
""")
Optional<@Valid KEMSignedPreKey> pniPqLastResortPreKey,
KEMSignedPreKey pniPqLastResortPreKey,
@Schema(requiredMode = Schema.RequiredMode.NOT_REQUIRED, description = """
An APNs token set for the account's primary device. If provided, the account's primary
@@ -13,7 +13,6 @@ import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.validation.constraints.AssertTrue;
import jakarta.validation.constraints.Size;
import java.util.Optional;
import java.util.Set;
import javax.annotation.Nullable;
import org.whispersystems.textsecuregcm.storage.DeviceCapability;
@@ -25,16 +24,16 @@ public record DeviceAttributes(
int registrationId,
@JsonProperty("pniRegistrationId")
@Nullable
Integer phoneNumberIdentityRegistrationId,
@JsonProperty("pniRegistrationId") int phoneNumberIdentityRegistrationId,
@JsonSerialize(using = ByteArrayAdapter.Serializing.class)
@JsonDeserialize(using = ByteArrayAdapter.Deserializing.class)
@Size(max = 225)
byte[] name,
@JsonSerialize(using = DeviceCapabilityAdapter.Serializer.class)
@JsonDeserialize(using = DeviceCapabilityAdapter.Deserializer.class)
@Nullable
Set<DeviceCapability> capabilities) {
@@ -42,7 +41,6 @@ public record DeviceAttributes(
@AssertTrue
@Schema(hidden = true)
public boolean isEachRegistrationIdValid() {
return validRegistrationId(registrationId) &&
(phoneNumberIdentityRegistrationId == null || validRegistrationId(phoneNumberIdentityRegistrationId));
return validRegistrationId(registrationId) && validRegistrationId(phoneNumberIdentityRegistrationId);
}
}
@@ -8,6 +8,7 @@ package org.whispersystems.textsecuregcm.entities;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import io.swagger.v3.oas.annotations.media.Schema;
import org.whispersystems.textsecuregcm.identity.IdentityType;
import org.whispersystems.textsecuregcm.storage.Device;
import org.whispersystems.textsecuregcm.util.ByteArrayAdapter;
import org.whispersystems.textsecuregcm.util.ByteArrayBase64WithPaddingAdapter;
@@ -32,10 +33,7 @@ public record DeviceInfo(long id,
byte[] createdAtCiphertext) {
public static DeviceInfo forDevice(final Device device) {
return new DeviceInfo(device.getId(),
device.getName(),
device.getLastSeen(),
device.getAccountRegistrationId(),
device.getCreatedAtCiphertext());
return new DeviceInfo(device.getId(), device.getName(), device.getLastSeen(), device.getRegistrationId(
IdentityType.ACI), device.getCreatedAtCiphertext());
}
}
@@ -6,6 +6,7 @@ package org.whispersystems.textsecuregcm.entities;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.google.protobuf.ByteString;
import com.webauthn4j.converter.jackson.deserializer.json.ByteArrayBase64Deserializer;
import io.micrometer.core.instrument.Metrics;
import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.validation.constraints.AssertTrue;
@@ -18,13 +19,12 @@ import javax.annotation.Nullable;
import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier;
import org.whispersystems.textsecuregcm.identity.ServiceIdentifier;
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
import org.whispersystems.textsecuregcm.util.ByteArrayAdapter;
public record IncomingMessage(int type,
byte destinationDeviceId,
int destinationRegistrationId,
@JsonDeserialize(using = ByteArrayAdapter.Deserializing.class)
@JsonDeserialize(using = ByteArrayBase64Deserializer.class)
@NotNull
// Note that max size is validated elsewhere in the interest of controlling responses and
// reporting additional metrics.
@@ -33,9 +33,9 @@ public record LinkDeviceRequest(@Schema(requiredMode = Schema.RequiredMode.REQUI
public LinkDeviceRequest(@JsonProperty("verificationCode") String verificationCode,
@JsonProperty("accountAttributes") DeviceAttributes deviceAttributes,
@JsonProperty("aciSignedPreKey") @NotNull @Valid ECSignedPreKey aciSignedPreKey,
@JsonProperty("pniSignedPreKey") Optional<@Valid ECSignedPreKey> pniSignedPreKey,
@JsonProperty("pniSignedPreKey") @NotNull @Valid ECSignedPreKey pniSignedPreKey,
@JsonProperty("aciPqLastResortPreKey") @NotNull @Valid KEMSignedPreKey aciPqLastResortPreKey,
@JsonProperty("pniPqLastResortPreKey") Optional<@Valid KEMSignedPreKey> pniPqLastResortPreKey,
@JsonProperty("pniPqLastResortPreKey") @NotNull @Valid KEMSignedPreKey pniPqLastResortPreKey,
@JsonProperty("apnToken") Optional<@Valid ApnRegistrationId> apnToken,
@JsonProperty("gcmToken") Optional<@Valid GcmRegistrationId> gcmToken) {
@@ -5,8 +5,7 @@
package org.whispersystems.textsecuregcm.entities;
import java.util.Optional;
import java.util.UUID;
public record LinkDeviceResponse(UUID uuid, Optional<UUID> pni, byte deviceId) {
public record LinkDeviceResponse(UUID uuid, UUID pni, byte deviceId) {
}
@@ -10,52 +10,31 @@ import static org.apache.commons.lang3.StringUtils.isNotBlank;
import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.validation.constraints.AssertTrue;
import jakarta.ws.rs.ClientErrorException;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.http.HttpStatus;
public interface PhoneVerificationRequest {
enum VerificationType {
SESSION,
RECOVERY_PASSWORD,
RECEIPT_CREDENTIAL
RECOVERY_PASSWORD
}
String sessionId();
byte[] recoveryPassword();
default byte[] receiptCredentialPresentation() {
return null;
}
// for the @AssertTrue to work with bean validation, method name must follow 'isSmth()'/'getSmth()' naming convention
@AssertTrue
@Schema(hidden = true)
default boolean isValid() {
// exactly one of sessionId/recoveryPassword/receiptCredentialPresentation should be present
return presentVerificationTypes().size() == 1;
// checking that exactly one of sessionId/recoveryPassword is non-empty
return isNotBlank(sessionId()) ^ (recoveryPassword() != null && recoveryPassword().length > 0);
}
default PhoneVerificationRequest.VerificationType verificationType() {
return presentVerificationTypes().get(0);
}
default List<VerificationType> presentVerificationTypes() {
final List<VerificationType> types = new ArrayList<>(1);
if (isNotBlank(sessionId())) {
types.add(VerificationType.SESSION);
}
if (ArrayUtils.isNotEmpty(recoveryPassword())) {
types.add(VerificationType.RECOVERY_PASSWORD);
}
if (ArrayUtils.isNotEmpty(receiptCredentialPresentation())) {
types.add(VerificationType.RECEIPT_CREDENTIAL);
}
return types;
return isNotBlank(sessionId()) ? PhoneVerificationRequest.VerificationType.SESSION
: PhoneVerificationRequest.VerificationType.RECOVERY_PASSWORD;
}
default byte[] decodeSessionId() {
@@ -22,6 +22,7 @@ public abstract class PreKeySignatureValidator {
final Collection<SignedPreKey<?>> signedPreKeys,
@Nullable final String userAgent,
final String context) {
final boolean success = signedPreKeys.stream().allMatch(signedPreKey -> signedPreKey.signatureValid(identityKey));
if (!success) {
@@ -15,51 +15,25 @@ import jakarta.validation.Valid;
import jakarta.validation.constraints.AssertTrue;
import jakarta.validation.constraints.NotNull;
import java.util.List;
import java.util.stream.Stream;
import javax.annotation.Nullable;
import jakarta.validation.constraints.PositiveOrZero;
import org.apache.commons.lang3.ArrayUtils;
import org.signal.libsignal.protocol.IdentityKey;
import org.whispersystems.textsecuregcm.util.ByteArrayAdapter;
import org.whispersystems.textsecuregcm.util.IdentityKeyAdapter;
public record RegistrationRequest(@Schema(requiredMode = Schema.RequiredMode.NOT_REQUIRED, description = """
The ID of an existing verification session as it appears in a verification session
metadata object. Must be provided if `recoveryPassword` and `receiptCredentialPresentation`
are not provided; must not be provided if `recoveryPassword` or `receiptCredentialPresentation`
is provided.
metadata object. Must be provided if `recoveryPassword` is not provided; must not be
provided if `recoveryPassword` is provided.
""")
@Nullable
String sessionId,
@JsonDeserialize(using = ByteArrayAdapter.Deserializing.class)
@Schema(requiredMode = Schema.RequiredMode.NOT_REQUIRED, description = """
A base64-encoded registration recovery password. Must be provided if `sessionId` and
`receiptCredentialPresentation` are not provided; must not be provided if `sessionId`
or `receiptCredentialPresentation` is provided. Registration recovery passwords must
be specified when reclaiming an account by account identifier.
A base64-encoded registration recovery password. Must be provided if `sessionId` is
not provided; must not be provided if `sessionId` is provided
""")
@Nullable
byte[] recoveryPassword,
@JsonDeserialize(using = ByteArrayAdapter.Deserializing.class)
@Schema(requiredMode = Schema.RequiredMode.NOT_REQUIRED, description = """
A base64-encoded receipt credential presentation that allows for redeeming a Signal Login.
Must be provided if `sessionId` and `recoveryPassword` are not provided;
must not be provided if `sessionId` or `recoveryPassword` is provided. Must not be
provided if recovering a previously used account.
""")
@Nullable
byte[] receiptCredentialPresentation,
@Schema(requiredMode = Schema.RequiredMode.NOT_REQUIRED, description = """
A TOTP one-time password; required if recovering an account that has TOTP keys. Must
not be provided if `receiptCredentialPresentation` is provided.
""")
@PositiveOrZero
@Nullable
Integer totp,
@NotNull
@Valid
@Schema(requiredMode = Schema.RequiredMode.REQUIRED)
@@ -84,17 +58,13 @@ public record RegistrationRequest(@Schema(requiredMode = Schema.RequiredMode.NOT
@JsonDeserialize(using = IdentityKeyAdapter.Deserializer.class)
IdentityKey aciIdentityKey,
@NotNull
@Valid
@Schema(requiredMode = Schema.RequiredMode.NOT_REQUIRED, description = """
@Schema(requiredMode = Schema.RequiredMode.REQUIRED, description = """
The PNI-associated identity key for the account, encoded as a base64 string.
Must be provided for an account with a phone number or when recovering an account by
ID (even if the recovered account does not have a phone number, in which case
PNI-associated key material will be ignored). Must be absent when registering an
account without a phone number.
""")
@JsonSerialize(using = IdentityKeyAdapter.Serializer.class)
@JsonDeserialize(using = IdentityKeyAdapter.Deserializer.class)
@Nullable
IdentityKey pniIdentityKey,
@NotNull
@@ -105,18 +75,14 @@ public record RegistrationRequest(@Schema(requiredMode = Schema.RequiredMode.NOT
public boolean isEverySignedKeyValid(@Nullable final String userAgent) {
if (deviceActivationRequest().aciSignedPreKey() == null ||
deviceActivationRequest().aciPqLastResortPreKey() == null) {
return false;
}
final boolean allPniPresentOrAllAbsent = ((pniIdentityKey == null) == deviceActivationRequest().pniSignedPreKey().isEmpty())
&& ((pniIdentityKey == null) == deviceActivationRequest().pniPqLastResortPreKey().isEmpty());
if (!allPniPresentOrAllAbsent) {
deviceActivationRequest().pniSignedPreKey() == null ||
deviceActivationRequest().aciPqLastResortPreKey() == null ||
deviceActivationRequest().pniPqLastResortPreKey() == null) {
return false;
}
return PreKeySignatureValidator.validatePreKeySignatures(aciIdentityKey(), List.of(deviceActivationRequest().aciSignedPreKey(), deviceActivationRequest().aciPqLastResortPreKey()), userAgent, "register")
&& (pniIdentityKey == null || PreKeySignatureValidator.validatePreKeySignatures(pniIdentityKey(), List.of(deviceActivationRequest().pniSignedPreKey().get(), deviceActivationRequest().pniPqLastResortPreKey().get()), userAgent, "register"));
&& PreKeySignatureValidator.validatePreKeySignatures(pniIdentityKey(), List.of(deviceActivationRequest().pniSignedPreKey(), deviceActivationRequest().pniPqLastResortPreKey()), userAgent, "register");
}
@VisibleForTesting
@@ -132,24 +98,4 @@ public record RegistrationRequest(@Schema(requiredMode = Schema.RequiredMode.NOT
return deviceActivationRequest().apnToken().isPresent() ^ deviceActivationRequest().gcmToken().isPresent();
}
}
@VisibleForTesting
@AssertTrue
@Schema(hidden = true)
boolean isAllOrNoPhoneNumberInformationProvided() {
final boolean expectPresence = pniIdentityKey != null;
return Stream.of(pniIdentityKey != null,
accountAttributes().getPhoneNumberIdentityRegistrationId().isPresent(),
deviceActivationRequest().pniSignedPreKey().isPresent(),
deviceActivationRequest().pniPqLastResortPreKey().isPresent())
.allMatch(present -> present == expectPresence);
}
@VisibleForTesting
@AssertTrue
@Schema(hidden = true)
boolean isMfaAbsentWhenUsingReceipt() {
return ArrayUtils.isEmpty(receiptCredentialPresentation) || totp == null;
}
}
@@ -65,7 +65,7 @@ abstract class IdleDevicePushNotificationExperiment implements PushNotificationE
} else {
pushTokenType = null;
}
return new DeviceLastSeenState(true, device.getAccountRegistrationId(), hasPushToken(device), device.getLastSeen(), pushTokenType);
return new DeviceLastSeenState(true, device.getRegistrationId(IdentityType.ACI), hasPushToken(device), device.getLastSeen(), pushTokenType);
} else {
return DeviceLastSeenState.MISSING_DEVICE_STATE;
}
@@ -27,7 +27,6 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.grpc.RequestAttributesUtil;
import org.whispersystems.textsecuregcm.util.InetAddressRange;
import org.whispersystems.textsecuregcm.util.logging.ImpossibleEvents;
public class ExternalRequestFilter implements Filter, ServerInterceptor {
@@ -86,7 +85,7 @@ public class ExternalRequestFilter implements Filter, ServerInterceptor {
if (response instanceof HttpServletResponse hsr) {
hsr.setStatus(404);
} else {
ImpossibleEvents.logImpossible(logger, "response was an unexpected type: {}", response.getClass());
logger.warn("response was an unexpected type: {}", response.getClass());
}
return;
}
@@ -15,7 +15,6 @@ import java.io.IOException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.util.HttpServletRequestUtil;
import org.whispersystems.textsecuregcm.util.logging.ImpossibleEvents;
/**
* Sets a {@link HttpServletRequest} attribute (that will also be available as a
@@ -37,7 +36,7 @@ public class RemoteAddressFilter implements Filter {
request.setAttribute(REMOTE_ADDRESS_ATTRIBUTE_NAME, remoteAddress);
} else {
ImpossibleEvents.logImpossible(logger, "request was of unexpected type: {}", request.getClass());
logger.warn("request was of unexpected type: {}", request.getClass());
}
chain.doFilter(request, response);
@@ -67,7 +67,7 @@ public class AccountsAnonymousGrpcService extends SimpleAccountsAnonymousGrpc.Ac
return accountsManager.getByUsernameHash(request.getUsernameHash().toByteArray()).join()
.map(account -> LookupUsernameHashResponse.newBuilder()
.setServiceIdentifier(GrpcServiceIdentifierUtil.toGrpcServiceIdentifier(new AciServiceIdentifier(account.getAccountIdentifier())))
.setServiceIdentifier(GrpcServiceIdentifierUtil.toGrpcServiceIdentifier(new AciServiceIdentifier(account.getUuid())))
.build())
.orElseGet(() -> LookupUsernameHashResponse.newBuilder().setNotFound(NotFound.getDefaultInstance()).build());
}
@@ -12,9 +12,6 @@ import java.security.SecureRandom;
import java.time.Clock;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HexFormat;
import java.util.List;
import java.util.Map;
@@ -30,8 +27,6 @@ import org.signal.chat.account.ClearRegistrationLockRequest;
import org.signal.chat.account.ClearRegistrationLockResponse;
import org.signal.chat.account.ConfigureUnidentifiedAccessRequest;
import org.signal.chat.account.ConfigureUnidentifiedAccessResponse;
import org.signal.chat.account.ConfirmTotpKeyRequest;
import org.signal.chat.account.ConfirmTotpKeyResponse;
import org.signal.chat.account.ConfirmUsernameHashRequest;
import org.signal.chat.account.ConfirmUsernameHashResponse;
import org.signal.chat.account.DeleteAccountRequest;
@@ -41,8 +36,6 @@ import org.signal.chat.account.DeleteUsernameHashResponse;
import org.signal.chat.account.DeleteUsernameLinkRequest;
import org.signal.chat.account.DeleteUsernameLinkResponse;
import org.signal.chat.account.ExternalServiceCredentials;
import org.signal.chat.account.GenerateTotpKeyRequest;
import org.signal.chat.account.GenerateTotpKeyResponse;
import org.signal.chat.account.GetAccountDataReportRequest;
import org.signal.chat.account.GetAccountDataReportResponse;
import org.signal.chat.account.GetAccountIdentityRequest;
@@ -51,12 +44,7 @@ import org.signal.chat.account.GetCapabilitiesRequest;
import org.signal.chat.account.GetCapabilitiesResponse;
import org.signal.chat.account.GetEntitlementsRequest;
import org.signal.chat.account.GetEntitlementsResponse;
import org.signal.chat.account.ListMfaKeysRequest;
import org.signal.chat.account.ListMfaKeysResponse;
import org.signal.chat.account.ListMfaKeysResponse.MfaKeyMetadata.MfaKeyType;
import org.signal.chat.account.RegistrationLockFailure;
import org.signal.chat.account.RemoveMfaKeyRequest;
import org.signal.chat.account.RemoveMfaKeyResponse;
import org.signal.chat.account.ReserveUsernameHashRequest;
import org.signal.chat.account.ReserveUsernameHashResponse;
import org.signal.chat.account.SetDiscoverableByPhoneNumberRequest;
@@ -65,15 +53,12 @@ import org.signal.chat.account.SetRegistrationLockRequest;
import org.signal.chat.account.SetRegistrationLockResponse;
import org.signal.chat.account.SetRegistrationRecoveryPasswordRequest;
import org.signal.chat.account.SetRegistrationRecoveryPasswordResponse;
import org.signal.chat.account.SetMfaKeyMetadataRequest;
import org.signal.chat.account.SetMfaKeyMetadataResponse;
import org.signal.chat.account.SetUsernameLinkRequest;
import org.signal.chat.account.SetUsernameLinkResponse;
import org.signal.chat.account.SetZkCredentialKeyRequest;
import org.signal.chat.account.SetZkCredentialKeyResponse;
import org.signal.chat.account.SimpleAccountsGrpc;
import org.signal.chat.account.StaleDevices;
import org.signal.chat.account.TotpParameters;
import org.signal.chat.account.UsernameNotAvailable;
import org.signal.chat.common.AccountIdentifiers;
import org.signal.chat.errors.FailedPrecondition;
@@ -88,6 +73,7 @@ import org.whispersystems.textsecuregcm.auth.InvalidRegistrationSessionException
import org.whispersystems.textsecuregcm.auth.RecoveryPasswordVerificationFailedException;
import org.whispersystems.textsecuregcm.auth.RegistrationLockFailureException;
import org.whispersystems.textsecuregcm.auth.SaltedTokenHash;
import org.whispersystems.textsecuregcm.auth.UnidentifiedAccessUtil;
import org.whispersystems.textsecuregcm.auth.UnverifiedRegistrationSessionException;
import org.whispersystems.textsecuregcm.auth.grpc.AuthenticatedDevice;
import org.whispersystems.textsecuregcm.auth.grpc.AuthenticationUtil;
@@ -100,28 +86,21 @@ import org.whispersystems.textsecuregcm.entities.IncomingMessage;
import org.whispersystems.textsecuregcm.entities.KEMSignedPreKey;
import org.whispersystems.textsecuregcm.entities.MessageProtos;
import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier;
import org.whispersystems.textsecuregcm.identity.IdentityType;
import org.whispersystems.textsecuregcm.identity.PniServiceIdentifier;
import org.whispersystems.textsecuregcm.limits.RateLimiters;
import org.whispersystems.textsecuregcm.push.MessageTooLargeException;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.AccountsManager;
import org.whispersystems.textsecuregcm.storage.AnnotatedMfaKey;
import org.whispersystems.textsecuregcm.storage.AnnotatedTotpKey;
import org.whispersystems.textsecuregcm.storage.ChangeNumberManager;
import org.whispersystems.textsecuregcm.storage.DeviceCapability;
import org.whispersystems.textsecuregcm.storage.PhoneNumberRecoveryPasswordsManager;
import org.whispersystems.textsecuregcm.storage.TooManyMfaKeysException;
import org.whispersystems.textsecuregcm.storage.TooManyTotpKeysException;
import org.whispersystems.textsecuregcm.storage.TotpKey;
import org.whispersystems.textsecuregcm.storage.RegistrationRecoveryPasswordsManager;
import org.whispersystems.textsecuregcm.storage.UsernameHashNotAvailableException;
import org.whispersystems.textsecuregcm.storage.UsernameReservationNotFoundException;
import org.whispersystems.textsecuregcm.util.NoStackTraceRuntimeException;
import org.whispersystems.textsecuregcm.util.RegistrationIdValidator;
import org.whispersystems.textsecuregcm.util.SystemMapper;
import org.whispersystems.textsecuregcm.util.UUIDUtil;
import org.whispersystems.textsecuregcm.util.UsernameHashZkProofVerifier;
import software.amazon.awssdk.services.dynamodb.model.TransactWriteItem;
import javax.annotation.Nullable;
public class AccountsGrpcService extends SimpleAccountsGrpc.AccountsImplBase {
@@ -130,24 +109,21 @@ public class AccountsGrpcService extends SimpleAccountsGrpc.AccountsImplBase {
private final AccountsManager accountsManager;
private final RateLimiters rateLimiters;
private final UsernameHashZkProofVerifier usernameHashZkProofVerifier;
private final PhoneNumberRecoveryPasswordsManager phoneNumberRecoveryPasswordsManager;
private final RegistrationRecoveryPasswordsManager registrationRecoveryPasswordsManager;
private final Clock clock;
private final ChangeNumberManager changeNumberManager;
private static class MfaKeyNotFoundException extends NoStackTraceRuntimeException {
}
public AccountsGrpcService(final AccountsManager accountsManager,
final RateLimiters rateLimiters,
final UsernameHashZkProofVerifier usernameHashZkProofVerifier,
final PhoneNumberRecoveryPasswordsManager phoneNumberRecoveryPasswordsManager,
final RegistrationRecoveryPasswordsManager registrationRecoveryPasswordsManager,
final Clock clock,
final ChangeNumberManager changeNumberManager) {
this.accountsManager = accountsManager;
this.rateLimiters = rateLimiters;
this.usernameHashZkProofVerifier = usernameHashZkProofVerifier;
this.phoneNumberRecoveryPasswordsManager = phoneNumberRecoveryPasswordsManager;
this.registrationRecoveryPasswordsManager = registrationRecoveryPasswordsManager;
this.clock = clock;
this.changeNumberManager = changeNumberManager;
}
@@ -198,14 +174,10 @@ public class AccountsGrpcService extends SimpleAccountsGrpc.AccountsImplBase {
final SaltedTokenHash credentials =
SaltedTokenHash.generateFor(formatRegistrationLock(request.getRegistrationLock().toByteArray()));
try {
accountsManager.update(AuthenticationUtil.requireAuthenticatedDevice().accountIdentifier(),
account -> account.setRegistrationLock(credentials.hash(), credentials.salt()));
accountsManager.update(AuthenticationUtil.requireAuthenticatedDevice().accountIdentifier(),
account -> account.setRegistrationLock(credentials.hash(), credentials.salt()));
return SetRegistrationLockResponse.getDefaultInstance();
} catch (IllegalArgumentException _) {
throw GrpcExceptions.invalidArguments(null);
}
return SetRegistrationLockResponse.getDefaultInstance();
}
@Override
@@ -263,6 +235,7 @@ public class AccountsGrpcService extends SimpleAccountsGrpc.AccountsImplBase {
return ConfirmUsernameHashResponse.newBuilder()
.setConfirmedUsernameHash(ConfirmUsernameHashResponse.ConfirmedUsernameHash.newBuilder()
.setUsernameHash(ByteString.copyFrom(updatedAccount.getUsernameHash().orElseThrow()))
.setUsernameLinkHandle(UUIDUtil.toByteString(updatedAccount.getUsernameLinkHandle())))
.build();
} catch (final UsernameHashNotAvailableException e) {
@@ -304,7 +277,7 @@ public class AccountsGrpcService extends SimpleAccountsGrpc.AccountsImplBase {
? account.getUsernameLinkHandle()
: UUID.randomUUID();
accountsManager.update(account.getAccountIdentifier(),
accountsManager.update(account.getIdentifier(IdentityType.ACI),
a -> a.setUsernameLinkDetails(linkHandle, request.getUsernameCiphertext().toByteArray()));
return responseBuilder.setUsernameLinkHandle(UUIDUtil.toByteString(linkHandle)).build();
@@ -341,29 +314,15 @@ public class AccountsGrpcService extends SimpleAccountsGrpc.AccountsImplBase {
@Override
public SetDiscoverableByPhoneNumberResponse setDiscoverableByPhoneNumber(final SetDiscoverableByPhoneNumberRequest request) {
accountsManager.update(AuthenticationUtil.requireAuthenticatedDevice().accountIdentifier(),
account -> {
if (account.getNumber().isEmpty()) {
throw GrpcExceptions.invalidArguments("account does not have a phone number");
}
account.setDiscoverableByPhoneNumber(request.getDiscoverableByPhoneNumber());
});
account -> account.setDiscoverableByPhoneNumber(request.getDiscoverableByPhoneNumber()));
return SetDiscoverableByPhoneNumberResponse.getDefaultInstance();
}
@Override
public SetRegistrationRecoveryPasswordResponse setRegistrationRecoveryPassword(final SetRegistrationRecoveryPasswordRequest request) {
final Account account = getAuthenticatedAccount();
final byte[] recoveryPassword = request.getRegistrationRecoveryPassword().toByteArray();
final Collection<TransactWriteItem> additionalWriteItems = account.getPhoneNumberIdentifier()
.map(phoneNumberIdentifier ->
List.of(phoneNumberRecoveryPasswordsManager.buildTransactWriteItemForStorePassword(phoneNumberIdentifier, recoveryPassword)))
.orElseGet(Collections::emptyList);
// TODO Once we retire `AccountController`, replace this with a new `AccountsManager#setRecoveryPassword` method
accountsManager.update(account.getAccountIdentifier(), a -> a.setAccountRecoveryPassword(recoveryPassword), additionalWriteItems);
registrationRecoveryPasswordsManager.store(getAuthenticatedAccount().getIdentifier(IdentityType.PNI),
request.getRegistrationRecoveryPassword().toByteArray());
return SetRegistrationRecoveryPasswordResponse.getDefaultInstance();
}
@@ -559,149 +518,11 @@ public class AccountsGrpcService extends SimpleAccountsGrpc.AccountsImplBase {
return GetCapabilitiesResponse.newBuilder().setCapabilities(builder.build()).build();
}
@Override
public GenerateTotpKeyResponse generateTotpKey(final GenerateTotpKeyRequest request) {
try {
final Account account = getAuthenticatedAccount();
if (account.getNumber().isPresent()) {
throw GrpcExceptions.invalidArguments("TOTP keys may not be generated for an account with a number");
}
final TotpKey pendingTotpKey =
accountsManager.generatePendingTotpKey(AuthenticationUtil.requireAuthenticatedDevice().accountIdentifier());
return GenerateTotpKeyResponse.newBuilder()
.setKeyGenerated(GenerateTotpKeyResponse.KeyGenerated.newBuilder()
.setKey(ByteString.copyFrom(pendingTotpKey.getEncoded()))
.setTotpParameters(toGrpcTotpParameters(pendingTotpKey.totpParameters()))
.build())
.build();
} catch (final TooManyTotpKeysException _) {
return GenerateTotpKeyResponse.newBuilder()
.setTooManyTotpKeys(FailedPrecondition.getDefaultInstance())
.build();
} catch (final TooManyMfaKeysException _) {
return GenerateTotpKeyResponse.newBuilder()
.setTooManyMfaKeys(FailedPrecondition.getDefaultInstance())
.build();
}
}
@Override
public ConfirmTotpKeyResponse confirmTotpKey(final ConfirmTotpKeyRequest request) {
try {
final Account account = getAuthenticatedAccount();
if (account.getNumber().isPresent()) {
throw GrpcExceptions.invalidArguments("TOTP keys may not be added to an account with a number");
}
final Optional<Byte> maybeConfirmedTotpKeyId =
accountsManager.confirmPendingTotpKey(
AuthenticationUtil.requireAuthenticatedDevice().accountIdentifier(),
request.getOneTimePassword(),
clock.instant(),
request.getMetadataCiphertext().toByteArray());
return maybeConfirmedTotpKeyId.map(keyId -> ConfirmTotpKeyResponse.newBuilder()
.setKeyConfirmed(ConfirmTotpKeyResponse.KeyConfirmed.newBuilder()
.setKeyId(keyId)
.build())
.build()).orElseGet(() -> ConfirmTotpKeyResponse.newBuilder()
.setOneTimePasswordNotVerified(FailedPrecondition.getDefaultInstance())
.build());
} catch (TooManyMfaKeysException _) {
return ConfirmTotpKeyResponse.newBuilder()
.setTooManyMfaKeys(FailedPrecondition.getDefaultInstance())
.build();
}
}
@Override
public ListMfaKeysResponse listMfaKeys(final ListMfaKeysRequest request) {
final ListMfaKeysResponse.Builder responseBuilder = ListMfaKeysResponse.newBuilder();
getAuthenticatedAccount().getMfaKeys().forEach((keyId, mfaKey) -> {
assert mfaKey.metadataCiphertext() != null;
responseBuilder.putKeys(
keyId,
ListMfaKeysResponse.MfaKeyMetadata.newBuilder()
.setMetadataCiphertext(ByteString.copyFrom(mfaKey.metadataCiphertext()))
.setType(switch (mfaKey) {
case AnnotatedTotpKey _ -> MfaKeyType.MFA_KEY_TYPE_TOTP;
}).build());
});
return responseBuilder.build();
}
@Override
public SetMfaKeyMetadataResponse setMfaKeyMetadata(final SetMfaKeyMetadataRequest request) {
final byte keyId = validateMfaKeyId(request.getKeyId());
try {
accountsManager.update(AuthenticationUtil.requireAuthenticatedDevice().accountIdentifier(), account -> {
final Map<Byte, AnnotatedMfaKey> mfaKeys = new HashMap<>(account.getMfaKeys());
@Nullable final AnnotatedMfaKey existingKey = mfaKeys.get(keyId);
if (existingKey == null) {
throw new MfaKeyNotFoundException();
}
mfaKeys.put(keyId, existingKey.withMetadataCiphertext(request.getMetadataCiphertext().toByteArray()));
account.setMfaKeys(mfaKeys);
});
return SetMfaKeyMetadataResponse.newBuilder()
.setMetadataUpdated(SetMfaKeyMetadataResponse.MetadataUpdated.getDefaultInstance())
.build();
} catch (final MfaKeyNotFoundException _) {
return SetMfaKeyMetadataResponse.newBuilder()
.setKeyNotFound(NotFound.getDefaultInstance())
.build();
}
}
@Override
public RemoveMfaKeyResponse removeMfaKey(final RemoveMfaKeyRequest request) {
final byte keyId = validateMfaKeyId(request.getKeyId());
accountsManager.update(AuthenticationUtil.requireAuthenticatedDevice().accountIdentifier(), account -> {
final Map<Byte, AnnotatedMfaKey> mfaKeys = new HashMap<>(account.getMfaKeys());
mfaKeys.remove(keyId);
account.setMfaKeys(mfaKeys);
});
return RemoveMfaKeyResponse.getDefaultInstance();
}
private byte validateMfaKeyId(final int keyId) {
if (keyId < 0 || keyId > Account.MAX_MFA_KEY_ID) {
throw GrpcExceptions.invalidArguments("MFA key ID out of range");
}
return (byte) keyId;
}
private static TotpParameters toGrpcTotpParameters(final org.whispersystems.textsecuregcm.storage.TotpParameters totpParameters) {
return TotpParameters.newBuilder()
.setAlgorithm(totpParameters.algorithm())
.setPasswordLength(totpParameters.passwordLength())
.setTimeStepSeconds(Math.toIntExact(totpParameters.timeStep().toSeconds()))
.build();
}
private static AccountIdentifiers buildAccountIdentifiers(final Account account) {
final AccountIdentifiers.Builder accountIdentifiersBuilder = AccountIdentifiers.newBuilder()
.addServiceIdentifiers(GrpcServiceIdentifierUtil.toGrpcServiceIdentifier(new AciServiceIdentifier(account.getAccountIdentifier())));
account.getPhoneNumberIdentifier()
.map(phoneNumberIdentifier -> GrpcServiceIdentifierUtil.toGrpcServiceIdentifier(new PniServiceIdentifier(phoneNumberIdentifier)))
.ifPresent(accountIdentifiersBuilder::addServiceIdentifiers);
account.getNumber().ifPresent(accountIdentifiersBuilder::setE164);
.addServiceIdentifiers(GrpcServiceIdentifierUtil.toGrpcServiceIdentifier(new AciServiceIdentifier(account.getUuid())))
.addServiceIdentifiers(GrpcServiceIdentifierUtil.toGrpcServiceIdentifier(new PniServiceIdentifier(account.getPhoneNumberIdentifier())))
.setE164(account.getNumber());
account.getUsernameHash().ifPresent(usernameHash ->
accountIdentifiersBuilder.setUsernameHash(ByteString.copyFrom(usernameHash)));
@@ -743,7 +564,7 @@ public class AccountsGrpcService extends SimpleAccountsGrpc.AccountsImplBase {
}
private static StatusRuntimeException invalidSignatureException(final String fieldName) {
return GrpcExceptions.fieldViolation(fieldName, "pre-key signature did not match PNI identity key");
return GrpcExceptions.fieldViolation(fieldName, "pre-key signature did not match PNI identity key");
}
private static <T, U> Map<Byte, U> transformDeviceMap(final Map<Integer, T> byDeviceId, final Function<T, U> f) {
@@ -265,7 +265,7 @@ public class BackupsAnonymousGrpcService extends SimpleBackupsAnonymousGrpc.Back
final BackupManager.ListMediaResult listResult = backupManager.list(
backupUser,
request.hasCursor() ? Optional.of(request.getCursor()) : Optional.empty(),
request.hasLimit() ? Optional.of(request.getLimit()) : Optional.empty());
request.getLimit());
final ListMediaResponse.ListResult.Builder builder = ListMediaResponse.ListResult.newBuilder();
for (BackupManager.StorageDescriptorWithLength sd : listResult.media()) {
builder.addPage(ListMediaResponse.ListEntry.newBuilder()
@@ -14,7 +14,6 @@ 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 java.util.HashSet;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.TimeUnit;
@@ -35,15 +34,15 @@ public class CredentialsAnonymousGrpcService extends SimpleCredentialsAnonymousG
@Override
public CheckSvrCredentialsResponse checkSvrCredentials(final CheckSvrCredentialsRequest request) {
final List<String> tokens = request.getPasswordsList().stream().distinct().toList();
final List<String> tokens = request.getPasswordsList();
final List<ExternalServiceCredentialsSelector.CredentialInfo> credentials = ExternalServiceCredentialsSelector.check(
new HashSet<>(tokens),
tokens,
svrCredentialsGenerator,
MAX_SVR_PASSWORD_AGE_SECONDS);
// the username associated with the provided number
final Optional<String> maybeUsername = accountsManager.getByE164(request.getNumber())
.map(Account::getAccountIdentifier)
.map(Account::getUuid)
.map(svrCredentialsGenerator::generateForUuid)
.map(ExternalServiceCredentials::username);
@@ -10,7 +10,6 @@ import java.time.Clock;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.Map;
import java.util.Optional;
import java.util.UUID;
import org.signal.chat.credentials.ExternalServiceType;
import org.signal.chat.credentials.GetCreateCallLinkCredentialsRequest;
@@ -25,7 +24,6 @@ import org.signal.chat.credentials.SimpleCredentialsGrpc;
import org.signal.libsignal.protocol.ServiceId;
import org.signal.libsignal.zkgroup.GenericServerSecretParams;
import org.signal.libsignal.zkgroup.InvalidInputException;
import org.signal.libsignal.zkgroup.auth.AuthCredentialWithPniResponse;
import org.signal.libsignal.zkgroup.auth.ServerZkAuthOperations;
import org.signal.libsignal.zkgroup.calllinks.CallLinkAuthCredentialResponse;
import org.signal.libsignal.zkgroup.calllinks.CreateCallLinkCredentialRequest;
@@ -36,6 +34,7 @@ import org.whispersystems.textsecuregcm.auth.RedemptionRange;
import org.whispersystems.textsecuregcm.auth.grpc.AuthenticatedDevice;
import org.whispersystems.textsecuregcm.auth.grpc.AuthenticationUtil;
import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
import org.whispersystems.textsecuregcm.identity.IdentityType;
import org.whispersystems.textsecuregcm.limits.RateLimiters;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.AccountsManager;
@@ -94,16 +93,12 @@ public class CredentialsGrpcService extends SimpleCredentialsGrpc.CredentialsImp
final Account account = accountsManager.getByAccountIdentifier(authenticatedDevice.accountIdentifier())
.orElseThrow(() -> GrpcExceptions.invalidCredentials("invalid credentials"));
final GetDeliveryCertificateResponse.Builder responseBuilder = GetDeliveryCertificateResponse.newBuilder()
return GetDeliveryCertificateResponse.newBuilder()
.setCertificateWithE164(ByteString.copyFrom(
certificateGenerator.createFor(account, authenticatedDevice.deviceId(), true)))
.setCertificateWithoutE164(ByteString.copyFrom(
certificateGenerator.createFor(account, authenticatedDevice.deviceId(), false)));
if (account.getNumber().isPresent()) {
responseBuilder.setCertificateWithE164(ByteString.copyFrom(
certificateGenerator.createFor(account, authenticatedDevice.deviceId(), true)));
}
return responseBuilder.build();
certificateGenerator.createFor(account, authenticatedDevice.deviceId(), false)))
.build();
}
@Override
@@ -122,26 +117,17 @@ public class CredentialsGrpcService extends SimpleCredentialsGrpc.CredentialsImp
accountsManager.getByAccountIdentifier(AuthenticationUtil.requireAuthenticatedDevice().accountIdentifier())
.orElseThrow(() -> GrpcExceptions.invalidCredentials("invalid credentials"));
final ServiceId.Aci aci = new ServiceId.Aci(account.getAccountIdentifier());
final Optional<ServiceId.Pni> maybePni = account.getPhoneNumberIdentifier().map(ServiceId.Pni::new);
final ServiceId.Aci aci = new ServiceId.Aci(account.getIdentifier(IdentityType.ACI));
final ServiceId.Pni pni = new ServiceId.Pni(account.getIdentifier(IdentityType.PNI));
final GetGroupCredentialsResponse.Builder responseBuilder = GetGroupCredentialsResponse.newBuilder();
maybePni.ifPresent(pni -> responseBuilder.setPni(UUIDUtil.toByteString(pni.getRawUUID())));
final GetGroupCredentialsResponse.Builder responseBuilder = GetGroupCredentialsResponse.newBuilder()
.setPni(UUIDUtil.toByteString(pni.getRawUUID()));
for (final Instant redemption : redemptionRange) {
final AuthCredentialWithPniResponse authCredentialWithPniResponse =
maybePni.map(pni ->
serverZkAuthOperations.issueAuthCredentialWithPniZkc(aci, pni, redemption))
.orElseGet(() -> serverZkAuthOperations.issueAuthCredentialZkcWithoutPni(aci,
account.getAuthCredentialSalt()
.orElseThrow(
() -> new IllegalStateException("account without PNI must have auth credential salt")),
redemption));
responseBuilder.addGroupCredentials(GetGroupCredentialsResponse.CredentialAndRedemptionTime.newBuilder()
.setRedemptionTimeSeconds(redemption.getEpochSecond())
.setCredential(ByteString.copyFrom(
authCredentialWithPniResponse.serialize()))
serverZkAuthOperations.issueAuthCredentialWithPniZkc(aci, pni, redemption).serialize()))
.build());
responseBuilder.addCallLinkAuthCredentials(GetGroupCredentialsResponse.CredentialAndRedemptionTime.newBuilder()
@@ -20,7 +20,6 @@ public class DeviceCapabilityUtil {
case DEVICE_CAPABILITY_SPARSE_POST_QUANTUM_RATCHET -> DeviceCapability.SPARSE_POST_QUANTUM_RATCHET;
case DEVICE_CAPABILITY_PROFILES_V2 -> DeviceCapability.PROFILES_V2;
case DEVICE_CAPABILITY_USERNAME_CHANGE_SYNC_MESSAGE -> DeviceCapability.USERNAME_CHANGE_SYNC_MESSAGE;
case DEVICE_CAPABILITY_OPTIONAL_PHONE_NUMBER -> DeviceCapability.OPTIONAL_PHONE_NUMBER;
case DEVICE_CAPABILITY_UNSPECIFIED, UNRECOGNIZED ->
throw GrpcExceptions.invalidArguments("unrecognized device capability");
};
@@ -34,7 +33,6 @@ public class DeviceCapabilityUtil {
case SPARSE_POST_QUANTUM_RATCHET -> org.signal.chat.common.DeviceCapability.DEVICE_CAPABILITY_SPARSE_POST_QUANTUM_RATCHET;
case PROFILES_V2 -> org.signal.chat.common.DeviceCapability.DEVICE_CAPABILITY_PROFILES_V2;
case USERNAME_CHANGE_SYNC_MESSAGE -> org.signal.chat.common.DeviceCapability.DEVICE_CAPABILITY_USERNAME_CHANGE_SYNC_MESSAGE;
case OPTIONAL_PHONE_NUMBER -> org.signal.chat.common.DeviceCapability.DEVICE_CAPABILITY_OPTIONAL_PHONE_NUMBER;
};
}
}
@@ -54,7 +54,7 @@ public class DevicesGrpcService extends SimpleDevicesGrpc.DevicesImplBase {
GetDevicesResponse.LinkedDevice.newBuilder()
.setId(device.getId())
.setLastSeen(device.getLastSeen())
.setRegistrationId(device.getAccountRegistrationId())
.setRegistrationId(device.getRegistrationId(IdentityType.ACI))
.setCreatedAtCiphertext(ByteString.copyFrom(device.getCreatedAtCiphertext()));
if (device.getName() != null) {
@@ -104,7 +104,7 @@ public class DevicesGrpcService extends SimpleDevicesGrpc.DevicesImplBase {
return SetDeviceNameResponse.newBuilder().setTargetDeviceNotFound(NotFound.getDefaultInstance()).build();
}
accountsManager.updateDevice(account.getAccountIdentifier(), deviceId, device -> device.setName(request.getName().toByteArray()));
accountsManager.updateDevice(account.getIdentifier(IdentityType.ACI), deviceId, device -> device.setName(request.getName().toByteArray()));
return SetDeviceNameResponse.newBuilder().setSuccess(Empty.getDefaultInstance()).build();
}
@@ -141,7 +141,7 @@ public class DevicesGrpcService extends SimpleDevicesGrpc.DevicesImplBase {
// Unlike FCM tokens, we need current "last updated" timestamps for APNs tokens and so update device records
// unconditionally if it's an APNS request
if (request.hasApnsTokenRequest() || !Objects.equals(device.getGcmId(), fcmToken)) {
accountsManager.updateDevice(account.getAccountIdentifier(), authenticatedDevice.deviceId(), d -> {
accountsManager.updateDevice(account.getIdentifier(IdentityType.ACI), authenticatedDevice.deviceId(), d -> {
d.setApnId(apnsToken);
d.setGcmId(fcmToken);
d.setFetchesMessages(false);
@@ -29,7 +29,6 @@ import org.whispersystems.textsecuregcm.storage.AccountsManager;
import org.whispersystems.textsecuregcm.storage.DonationPermitsManager;
import org.whispersystems.textsecuregcm.storage.RedeemedReceiptsManager;
import org.whispersystems.textsecuregcm.subscriptions.ReceiptCredentialPresentationFactory;
import org.whispersystems.textsecuregcm.subscriptions.ReceiptLevel;
public class DonationsGrpcService extends SimpleDonationsGrpc.DonationsImplBase {
@@ -74,17 +73,14 @@ public class DonationsGrpcService extends SimpleDonationsGrpc.DonationsImplBase
final ReceiptSerial receiptSerial = receiptCredentialPresentation.getReceiptSerial();
final Instant receiptExpiration = Instant.ofEpochSecond(receiptCredentialPresentation.getReceiptExpirationTime());
final long receiptLevel = receiptCredentialPresentation.getReceiptLevel();
final String badgeId = ReceiptLevel
.lookupLevel(receiptLevel)
.map(badgesConfiguration.getReceiptLevels()::get)
.orElse(null);
final String badgeId = badgesConfiguration.getReceiptLevels().get(receiptLevel);
if (badgeId == null) {
// Since the receipt presentation checked out, the server messed up because it doesn't recognize a receipt level it previously issued.
LOGGER.error("Server doesn't recognize previously issued receipt level; please check badgesConfiguration for issues");
throw GrpcExceptions.unavailable("server does not recognize the requested receipt level");
}
final boolean receiptMatched = redeemedReceiptsManager.put(
receiptSerial, receiptExpiration, receiptLevel, authenticatedDevice.accountIdentifier());
receiptSerial, receiptExpiration.getEpochSecond(), receiptLevel, authenticatedDevice.accountIdentifier());
if (!receiptMatched) {
return RedeemReceiptResponse.newBuilder()
.setAlreadyRedeemed(FailedPrecondition.newBuilder()
@@ -15,7 +15,6 @@ import io.grpc.StatusRuntimeException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.util.ExceptionUtils;
import org.whispersystems.textsecuregcm.util.logging.ImpossibleEvents;
import java.io.IOException;
import java.io.UncheckedIOException;
@@ -60,10 +59,6 @@ public class ErrorMappingInterceptor implements ServerInterceptor {
log.warn("RPC {} encountered IOException", call.getMethodDescriptor().getFullMethodName(), e);
yield GrpcExceptions.unavailable();
}
case IllegalStateException e -> {
ImpossibleEvents.logImpossible(log, e.getMessage(), e);
yield GrpcExceptions.unavailable();
}
case null -> {
log.error("RPC {} finished with status UNKNOWN: {}",
call.getMethodDescriptor().getFullMethodName(), status.getDescription());
@@ -72,7 +67,7 @@ public class ErrorMappingInterceptor implements ServerInterceptor {
default -> {
log.error("RPC {} finished with status UNKNOWN",
call.getMethodDescriptor().getFullMethodName(), status.getCause());
yield GrpcExceptions.unavailable();
yield GrpcExceptions.unavailable(status.getCause().getMessage());
}
};
super.close(statusException.getStatus(), statusException.getTrailers());
@@ -18,7 +18,6 @@ import org.whispersystems.textsecuregcm.WhisperServerConfiguration;
import org.whispersystems.textsecuregcm.auth.ExternalServiceCredentialsGenerator;
import org.whispersystems.textsecuregcm.configuration.DirectoryV2ClientConfiguration;
import org.whispersystems.textsecuregcm.configuration.PaymentsServiceConfiguration;
import org.whispersystems.textsecuregcm.configuration.SecureStorageServiceConfiguration;
import org.whispersystems.textsecuregcm.configuration.SecureValueRecoveryConfiguration;
public enum ExternalServiceDefinitions {
@@ -49,7 +48,7 @@ public enum ExternalServiceDefinitions {
.build();
}),
STORAGE(ExternalServiceType.EXTERNAL_SERVICE_TYPE_STORAGE, (chatConfig, _) -> {
final SecureStorageServiceConfiguration cfg = chatConfig.getSecureStorageServiceConfiguration();
final PaymentsServiceConfiguration cfg = chatConfig.getPaymentsServiceConfiguration();
return ExternalServiceCredentialsGenerator
.builder(cfg.userAuthenticationTokenSharedSecret())
.prependUsername(true)
@@ -10,7 +10,6 @@ import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.time.Clock;
import java.util.Arrays;
import java.util.Optional;
import java.util.concurrent.Flow;
import org.signal.chat.errors.FailedUnidentifiedAuthorization;
import org.signal.chat.errors.NotFound;
@@ -95,17 +94,14 @@ public class KeysAnonymousGrpcService extends SimpleKeysAnonymousGrpc.KeysAnonym
request.getFingerprint().toByteArray()))
.flatMap(serviceIdentifierAndFingerprint -> Mono.fromFuture(
() -> accountsManager.getByServiceIdentifierAsync(serviceIdentifierAndFingerprint.getT1()))
.map(maybeAccount -> maybeAccount.flatMap(
account -> switch (serviceIdentifierAndFingerprint.getT1().identityType()) {
case ACI -> Optional.of(account.getAccountIdentityKey());
case PNI -> account.getPhoneNumberIdentityKey();
}))
.flatMap(Mono::justOrEmpty)
.filter(identityKey -> !fingerprintMatches(identityKey, serviceIdentifierAndFingerprint.getT2()))
.map(identityKey -> CheckIdentityKeyResponse.newBuilder()
.filter(account -> !fingerprintMatches(account.getIdentityKey(serviceIdentifierAndFingerprint.getT1()
.identityType()), serviceIdentifierAndFingerprint.getT2()))
.map(account -> CheckIdentityKeyResponse.newBuilder()
.setTargetIdentifier(
GrpcServiceIdentifierUtil.toGrpcServiceIdentifier(serviceIdentifierAndFingerprint.getT1()))
.setIdentityKey(ByteString.copyFrom(identityKey.serialize()))
.setIdentityKey(ByteString.copyFrom(account.getIdentityKey(serviceIdentifierAndFingerprint.getT1()
.identityType()).serialize()))
.build())));
}
@@ -6,12 +6,13 @@
package org.whispersystems.textsecuregcm.grpc;
import com.google.protobuf.ByteString;
import io.grpc.StatusRuntimeException;
import java.util.Arrays;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import io.grpc.StatusRuntimeException;
import org.signal.chat.common.EcPreKey;
import org.signal.chat.common.EcSignedPreKey;
import org.signal.chat.common.KemSignedPreKey;
@@ -21,14 +22,15 @@ import org.signal.libsignal.protocol.IdentityKey;
import org.signal.libsignal.protocol.InvalidKeyException;
import org.signal.libsignal.protocol.ecc.ECPublicKey;
import org.signal.libsignal.protocol.kem.KEMPublicKey;
import org.whispersystems.textsecuregcm.auth.UnidentifiedAccessChecksum;
import org.whispersystems.textsecuregcm.entities.ECPreKey;
import org.whispersystems.textsecuregcm.entities.ECSignedPreKey;
import org.whispersystems.textsecuregcm.entities.KEMSignedPreKey;
import org.whispersystems.textsecuregcm.auth.UnidentifiedAccessChecksum;
import org.whispersystems.textsecuregcm.identity.IdentityType;
import org.whispersystems.textsecuregcm.identity.ServiceIdentifier;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.Device;
import org.whispersystems.textsecuregcm.storage.DeviceCapability;
import org.whispersystems.textsecuregcm.storage.KeyIdUtil;
import org.whispersystems.textsecuregcm.storage.KeysManager;
@@ -72,14 +74,8 @@ class KeysGrpcHelper {
return Optional.empty();
}
final IdentityKey identityKey = switch (targetServiceIdentifier.identityType()) {
case ACI -> targetAccount.getAccountIdentityKey();
case PNI -> targetAccount.getPhoneNumberIdentityKey()
.orElseThrow(() -> new IllegalArgumentException("Target account does not have a PNI identity key"));
};
final AccountPreKeyBundles.Builder preKeyBundlesBuilder = AccountPreKeyBundles.newBuilder()
.setIdentityKey(ByteString.copyFrom(identityKey.serialize()))
.setIdentityKey(ByteString.copyFrom(targetAccount.getIdentityKey(targetServiceIdentifier.identityType()).serialize()))
.setUnrestrictedUnidentifiedAccess(targetServiceIdentifier.identityType() == IdentityType.ACI && targetAccount.isUnrestrictedUnidentifiedAccess());
// Set the UAK hash if the account has a UAK and we're targeting an ACI. PNIs don't allow unidentified access.
@@ -93,11 +89,6 @@ class KeysGrpcHelper {
preKeysByDeviceId.forEach((deviceId, devicePreKeys) -> {
final Device device = targetAccount.getDevice(deviceId).orElseThrow();
final int registrationId = switch (targetServiceIdentifier.identityType()) {
case ACI -> device.getAccountRegistrationId();
case PNI -> device.getPhoneNumberIdentityRegistrationId()
.orElseThrow(() -> new IllegalArgumentException("Device does not have a PNI registration ID"));
};
final DevicePreKeyBundle.Builder builder = DevicePreKeyBundle.newBuilder()
.setEcSignedPreKey(EcSignedPreKey.newBuilder()
@@ -108,7 +99,7 @@ class KeysGrpcHelper {
.setKeyId(KeyIdUtil.toUnsignedInt(devicePreKeys.kemSignedPreKey().keyId()))
.setPublicKey(ByteString.copyFrom(devicePreKeys.kemSignedPreKey().serializedPublicKey()))
.setSignature(ByteString.copyFrom(devicePreKeys.kemSignedPreKey().signature())))
.setRegistrationId(registrationId);
.setRegistrationId(device.getRegistrationId(targetServiceIdentifier.identityType()));
devicePreKeys.ecPreKey().ifPresent(ecPreKey -> builder.setEcOneTimePreKey(EcPreKey.newBuilder()
.setKeyId(KeyIdUtil.toUnsignedInt(ecPreKey.keyId()))
@@ -60,21 +60,17 @@ public class KeysGrpcService extends SimpleKeysGrpc.KeysImplBase {
final AuthenticatedDevice authenticatedDevice = AuthenticationUtil.requireAuthenticatedDevice();
final Account account = getAuthenticatedAccount(authenticatedDevice.accountIdentifier());
final UUID aci = account.getAccountIdentifier();
final CompletableFuture<Integer> aciEcKeyCountFuture =
keysManager.getEcCount(aci, authenticatedDevice.deviceId());
keysManager.getEcCount(account.getIdentifier(IdentityType.ACI), authenticatedDevice.deviceId());
final CompletableFuture<Integer> pniEcKeyCountFuture = account.getPhoneNumberIdentifier()
.map(pni -> keysManager.getEcCount(pni, authenticatedDevice.deviceId()))
.orElseGet(() -> CompletableFuture.completedFuture(0));
final CompletableFuture<Integer> pniEcKeyCountFuture =
keysManager.getEcCount(account.getIdentifier(IdentityType.PNI), authenticatedDevice.deviceId());
final CompletableFuture<Integer> aciKemKeyCountFuture =
keysManager.getPqCount(aci, authenticatedDevice.deviceId());
keysManager.getPqCount(account.getIdentifier(IdentityType.ACI), authenticatedDevice.deviceId());
final CompletableFuture<Integer> pniKemKeyCountFuture = account.getPhoneNumberIdentifier()
.map(pni -> keysManager.getPqCount(pni, authenticatedDevice.deviceId()))
.orElseGet(() -> CompletableFuture.completedFuture(0));
final CompletableFuture<Integer> pniKemKeyCountFuture =
keysManager.getPqCount(account.getIdentifier(IdentityType.PNI), authenticatedDevice.deviceId());
CompletableFuture.allOf(aciEcKeyCountFuture, pniEcKeyCountFuture, aciKemKeyCountFuture, pniKemKeyCountFuture).join();
@@ -103,10 +99,7 @@ public class KeysGrpcService extends SimpleKeysGrpc.KeysImplBase {
final Optional<Integer> targetRegistrationId = maybeTargetAccount
.filter(_ -> request.hasDeviceId())
.flatMap(targetAccount -> targetAccount.getDevice(deviceId))
.flatMap(device -> switch (targetIdentifier.identityType()) {
case ACI -> Optional.of(device.getAccountRegistrationId());
case PNI -> device.getPhoneNumberIdentityRegistrationId();
});
.map(device -> device.getRegistrationId(targetIdentifier.identityType()));
final String rateLimitKey = RateLimitKeys.preKeyLimiterKey(
authenticatedDevice.accountIdentifier(),
@@ -161,19 +154,11 @@ public class KeysGrpcService extends SimpleKeysGrpc.KeysImplBase {
final Account account = getAuthenticatedAccount(authenticatedAccountUuid);
final IdentityKey identityKey = switch (identityType) {
case ACI -> account.getAccountIdentityKey();
case PNI -> account.getPhoneNumberIdentityKey()
.orElseThrow(() -> new IllegalArgumentException("Account does not have a PNI identity key"));
};
final UUID identifier = getIdentifier(account, identityType);
final List<K> preKeys = requestPreKeys.stream()
.map(requestPreKey -> extractPreKeyFunction.apply(requestPreKey, identityKey))
.map(requestPreKey -> extractPreKeyFunction.apply(requestPreKey, account.getIdentityKey(identityType)))
.toList();
storeKeysFunction.apply(identifier, preKeys).join();
storeKeysFunction.apply(account.getIdentifier(identityType), preKeys).join();
}
@Override
@@ -181,10 +166,15 @@ public class KeysGrpcService extends SimpleKeysGrpc.KeysImplBase {
final AuthenticatedDevice authenticatedDevice = AuthenticationUtil.requireAuthenticatedDevice();
storeRepeatedUseKey(authenticatedDevice.accountIdentifier(),
IdentityTypeUtil.fromGrpcIdentityType(request.getIdentityType()),
request.getIdentityType(),
request.getSignedPreKey(),
(preKey, identityKey) -> KeysGrpcHelper.checkEcSignedPreKey(preKey, identityKey, INVALID_PUBLIC_KEY_EXCEPTION, INVALID_SIGNATURE_EXCEPTION),
(identifier, signedPreKey) -> keysManager.storeEcSignedPreKeys(identifier, authenticatedDevice.deviceId(), signedPreKey));
(account, signedPreKey) -> {
final IdentityType identityType = IdentityTypeUtil.fromGrpcIdentityType(request.getIdentityType());
final UUID identifier = account.getIdentifier(identityType);
return keysManager.storeEcSignedPreKeys(identifier, authenticatedDevice.deviceId(), signedPreKey);
});
return SetPreKeyResponse.getDefaultInstance();
}
@@ -194,46 +184,36 @@ public class KeysGrpcService extends SimpleKeysGrpc.KeysImplBase {
final AuthenticatedDevice authenticatedDevice = AuthenticationUtil.requireAuthenticatedDevice();
storeRepeatedUseKey(authenticatedDevice.accountIdentifier(),
IdentityTypeUtil.fromGrpcIdentityType(request.getIdentityType()),
request.getIdentityType(),
request.getSignedPreKey(),
(preKey, identityKey) -> KeysGrpcHelper.checkKemSignedPreKey(preKey, identityKey, INVALID_PUBLIC_KEY_EXCEPTION, INVALID_SIGNATURE_EXCEPTION),
(identifier, lastResortKey) -> keysManager.storePqLastResort(identifier, authenticatedDevice.deviceId(), lastResortKey));
(account, lastResortKey) -> {
final UUID identifier =
account.getIdentifier(IdentityTypeUtil.fromGrpcIdentityType(request.getIdentityType()));
return keysManager.storePqLastResort(identifier, authenticatedDevice.deviceId(), lastResortKey);
});
return SetPreKeyResponse.getDefaultInstance();
}
private <K, R> void storeRepeatedUseKey(final UUID authenticatedAccountUuid,
final IdentityType identityType,
final org.signal.chat.common.IdentityType identityType,
final R storeKeyRequest,
final BiFunction<R, IdentityKey, K> extractKeyFunction,
final BiFunction<UUID, K, CompletableFuture<Void>> storeKeyFunction) {
final BiFunction<Account, K, CompletableFuture<Void>> storeKeyFunction) {
final Account account = getAuthenticatedAccount(authenticatedAccountUuid);
final IdentityKey identityKey = switch (identityType) {
case ACI -> account.getAccountIdentityKey();
case PNI -> account.getPhoneNumberIdentityKey()
.orElseThrow(() -> GrpcExceptions.invalidArguments("account does not have a PNI identity key"));
};
final UUID identifier = getIdentifier(account, identityType);
final IdentityKey identityKey = account.getIdentityKey(IdentityTypeUtil.fromGrpcIdentityType(identityType));
final K key = extractKeyFunction.apply(storeKeyRequest, identityKey);
storeKeyFunction.apply(identifier, key).join();
storeKeyFunction.apply(account, key).join();
}
private Account getAuthenticatedAccount(final UUID authenticatedAccountId) {
return accountsManager.getByAccountIdentifier(authenticatedAccountId)
.orElseThrow(() -> GrpcExceptions.invalidCredentials("invalid credentials"));
}
/// Get the identity of the requested `idenityType`, or throw an invalid arguments status if `account` does not
/// contain that type.
private static UUID getIdentifier(Account account, IdentityType identityType) {
return switch (identityType) {
case ACI -> account.getAccountIdentifier();
case PNI -> account.getPhoneNumberIdentifier()
.orElseThrow(() -> GrpcExceptions.invalidArguments("PNI identity type not allowed for an account without a phone number"));
};
}
}
@@ -1,97 +0,0 @@
/*
* Copyright 2026 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.grpc;
import com.google.protobuf.ByteString;
import java.io.IOException;
import org.signal.chat.errors.FailedPrecondition;
import org.signal.chat.errors.NotFound;
import org.signal.chat.purchase.CreateLoginReceiptCredentialRequest;
import org.signal.chat.purchase.CreateLoginReceiptCredentialResponse;
import org.signal.chat.purchase.PaymentRequired;
import org.signal.chat.purchase.SimpleLoginPurchaseGrpc;
import org.signal.libsignal.zkgroup.InvalidInputException;
import org.signal.libsignal.zkgroup.VerificationFailedException;
import org.signal.libsignal.zkgroup.receipts.ReceiptCredentialRequest;
import org.signal.libsignal.zkgroup.receipts.ReceiptCredentialResponse;
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
import org.whispersystems.textsecuregcm.storage.DynamicConfigurationManager;
import org.whispersystems.textsecuregcm.subscriptions.LoginPurchaseManager;
import org.whispersystems.textsecuregcm.subscriptions.PaymentProvider;
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionChargeFailurePaymentRequiredException;
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionInvalidArgumentsException;
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionNotFoundException;
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionPaymentRequiredException;
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionReceiptAlreadyRedeemedException;
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionReceiptRequestedForOpenPaymentException;
public class LoginPurchaseGrpcService extends SimpleLoginPurchaseGrpc.LoginPurchaseImplBase {
private final LoginPurchaseManager loginPurchaseManager;
private final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager;
public LoginPurchaseGrpcService(
final LoginPurchaseManager loginPurchaseManager,
final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager) {
this.loginPurchaseManager = loginPurchaseManager;
this.dynamicConfigurationManager = dynamicConfigurationManager;
}
@Override
public CreateLoginReceiptCredentialResponse createLoginReceiptCredential(
final CreateLoginReceiptCredentialRequest request) throws IOException, RateLimitExceededException {
if (!dynamicConfigurationManager.getConfiguration().getLoginPurchaseConfiguration().enabled()) {
throw GrpcExceptions.invalidArguments("method not allowed");
}
final PaymentProvider paymentProvider = PaymentProvider.fromProto(request.getProcessor())
.orElseThrow(() -> GrpcExceptions.fieldViolation("payment_provider", "Unrecognized payment provider"));
final ReceiptCredentialRequest receiptCredentialRequest;
try {
receiptCredentialRequest = new ReceiptCredentialRequest(request.getReceiptCredentialRequest().toByteArray());
} catch (final InvalidInputException e) {
throw GrpcExceptions.fieldViolation("receipt_credential_request", "invalid receipt credential request");
}
try {
final ReceiptCredentialResponse receiptCredentialResponse = loginPurchaseManager.generateReceipt(
paymentProvider, request.getPurchaseIdentifier(), receiptCredentialRequest);
return CreateLoginReceiptCredentialResponse.newBuilder()
.setResult(CreateLoginReceiptCredentialResponse.CreateLoginReceiptCredentialResult.newBuilder()
.setReceiptCredentialResponse(ByteString.copyFrom(receiptCredentialResponse.serialize())))
.build();
} catch (final SubscriptionReceiptRequestedForOpenPaymentException e) {
return CreateLoginReceiptCredentialResponse.newBuilder()
.setPaymentStillProcessing(FailedPrecondition.getDefaultInstance())
.build();
} catch (final SubscriptionChargeFailurePaymentRequiredException e) {
return CreateLoginReceiptCredentialResponse.newBuilder()
.setPaymentRequired(PaymentRequired.newBuilder()
.setChargeFailure(SubscriptionsUtil.toChargeFailure(e.getProcessor(), e.getChargeFailure())))
.build();
} catch (final SubscriptionPaymentRequiredException e) {
return CreateLoginReceiptCredentialResponse.newBuilder()
.setPaymentRequired(PaymentRequired.getDefaultInstance())
.build();
} catch (final SubscriptionNotFoundException e) {
return CreateLoginReceiptCredentialResponse.newBuilder()
.setPaymentNotFound(NotFound.getDefaultInstance())
.build();
} catch (final SubscriptionReceiptAlreadyRedeemedException e) {
return CreateLoginReceiptCredentialResponse.newBuilder()
.setReceiptAlreadyIssued(FailedPrecondition.getDefaultInstance())
.build();
} catch (final SubscriptionInvalidArgumentsException e) {
throw GrpcExceptions.invalidArguments(e.errorDetail().orElse(""));
} catch (final VerificationFailedException e) {
throw GrpcExceptions.fieldViolation("receipt_credential_request",
"receipt credential request failed verification");
}
}
}
@@ -130,7 +130,7 @@ public class MessageDispatcher {
final Device device,
final Flux<UUID> acknowledgedMessageGuids) {
final MessageStream messageStream = messagesManager.getMessages(account.getAccountIdentifier(), device);
final MessageStream messageStream = messagesManager.getMessages(account.getIdentifier(IdentityType.ACI), device);
@Nullable final UserAgent userAgent = UserAgentUtil.maybeParseUserAgentString(userAgentString);
final PendingAcknowledgementTracker pendingAcknowledgementTracker = new PendingAcknowledgementTracker(messageMetrics, userAgent);
@@ -213,7 +213,7 @@ public class MessageDispatcher {
/// If the device potentially has more messages available, schedule a push notification.
private void maybeSchedulePush(final Account account, final Device device) {
messagesManager.mayHaveMessages(account.getAccountIdentifier(), device)
messagesManager.mayHaveMessages(account.getIdentifier(IdentityType.ACI), device)
.thenAccept(mayHaveMessages -> {
if (mayHaveMessages) {
pushNotificationScheduler.scheduleDelayedNotification(account, device,
@@ -232,15 +232,15 @@ public class MessageDispatcher {
messageMetrics.measureMessageStreamDisplaced(MessageMetrics.GRPC_CHANNEL, userAgent, false);
sink.error(GrpcExceptions.invalidCredentials("reauthentication required"));
};
disconnectionRequestManager.addListener(account.getAccountIdentifier(), device.getId(), listener);
sink.onDispose(() -> disconnectionRequestManager.removeListener(account.getAccountIdentifier(), device.getId(), listener));
disconnectionRequestManager.addListener(account.getUuid(), device.getId(), listener);
sink.onDispose(() -> disconnectionRequestManager.removeListener(account.getUuid(), device.getId(), listener));
});
}
private void recordDeliveryAttempt(final Account account, final Device device, final String userAgent,
final Signal<? extends MessageStreamEntry> firstEntry) {
if (firstEntry.get() instanceof MessageStreamEntry.Envelope(final MessageProtos.Envelope message)) {
messageDeliveryLoopMonitor.recordDeliveryAttempt(account.getAccountIdentifier(),
messageDeliveryLoopMonitor.recordDeliveryAttempt(account.getIdentifier(IdentityType.ACI),
device.getId(),
UUIDUtil.fromByteString(message.getServerGuid()),
userAgent,
@@ -143,7 +143,7 @@ public class MessagesAnonymousGrpcService extends SimpleMessagesAnonymousGrpc.Me
final Account destination = maybeDestination.get();
rateLimiters.getStoriesLimiter().validate(destination.getAccountIdentifier());
rateLimiters.getStoriesLimiter().validate(destination.getIdentifier(IdentityType.ACI));
return sendIndividualMessage(destination,
destinationServiceIdentifier,
Loaded 100 of 367 files, more files were not shown because too many files have changed in this diff. Show more