mirror of
https://github.com/signalapp/Signal-Server.git
synced 2026-12-01 07:46:47 +00:00
Compare commits
124
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
33bf9ccae5 | ||
|
|
2321f42e20 | ||
|
|
355d95c6c6 | ||
|
|
3dde05de8a | ||
|
|
1ed282a790 | ||
|
|
d1ec5d7d9c | ||
|
|
c09e167f3f | ||
|
|
eaa3c5f20f | ||
|
|
eb0ffb0c4d | ||
|
|
31b34ed06f | ||
|
|
b247fc24c1 | ||
|
|
56a91f104e | ||
|
|
461fce800a | ||
|
|
7f08e8bf4e | ||
|
|
08ca97ba00 | ||
|
|
4577a4aa9b | ||
|
|
8fac5de9af | ||
|
|
1dd7383af0 | ||
|
|
5f66f1c51d | ||
|
|
867ec4a3df | ||
|
|
a5f2f7f3e5 | ||
|
|
4c2cd0c999 | ||
|
|
14fb2fb29d | ||
|
|
c612bd4b73 | ||
|
|
4157cadf44 | ||
|
|
0cabb53aed | ||
|
|
f04e716347 | ||
|
|
558649ba65 | ||
|
|
43dc9d11fd | ||
|
|
9547655a9c | ||
|
|
547bde4869 | ||
|
|
fe1082d8ba | ||
|
|
7c77dd20bc | ||
|
|
f0370b75af | ||
|
|
ed08d1dc23 | ||
|
|
369ca0b514 | ||
|
|
218a1cd75f | ||
|
|
b04e41803a | ||
|
|
e92c3bb8aa | ||
|
|
2bcecc7f7d | ||
|
|
e8979082a7 | ||
|
|
5c99b03eb2 | ||
|
|
9814fee556 | ||
|
|
5b18ecafaa | ||
|
|
f31fb14667 | ||
|
|
c6d6469008 | ||
|
|
863057d659 | ||
|
|
2b3a6e1aa5 | ||
|
|
38ca4e6b27 | ||
|
|
65bc5e3257 | ||
|
|
ec5613b92a | ||
|
|
e77d3cb9cb | ||
|
|
02e6fb0ecf | ||
|
|
fbf53cd3e8 | ||
|
|
4bcf33d666 | ||
|
|
31b0a096f4 | ||
|
|
1b303cbf01 | ||
|
|
bb76feff71 | ||
|
|
c155696488 | ||
|
|
446c4b2553 | ||
|
|
662c040bd0 | ||
|
|
8a48910d6c | ||
|
|
7375db1c7a | ||
|
|
93083f2ca9 | ||
|
|
8d37c148d6 | ||
|
|
3ca228c0e3 | ||
|
|
85d81271ce | ||
|
|
b2a450b264 | ||
|
|
7946caa817 | ||
|
|
3ac7a2f356 | ||
|
|
2f482f68f7 | ||
|
|
0786627bef | ||
|
|
bc7cd0cc95 | ||
|
|
48954c9f62 | ||
|
|
336e0472f6 | ||
|
|
df026777c4 | ||
|
|
c7bcaac310 | ||
|
|
1366fbba8a | ||
|
|
40601b8297 | ||
|
|
3aed88d8cf | ||
|
|
15129c4ec9 | ||
|
|
af0565c9ad | ||
|
|
341fe88853 | ||
|
|
a5457f81b9 | ||
|
|
e09a9c1707 | ||
|
|
178f6452bb | ||
|
|
a8a4a70a68 | ||
|
|
ae04fae1b9 | ||
|
|
150a4952a1 | ||
|
|
17a824954e | ||
|
|
48fd25f01e | ||
|
|
2c18e4aa1f | ||
|
|
f8e049bb6c | ||
|
|
8ba7da0568 | ||
|
|
30c642324a | ||
|
|
647b25b87c | ||
|
|
e7ec47aa25 | ||
|
|
7d39f2952b | ||
|
|
7ec1f78406 | ||
|
|
9d601047c8 | ||
|
|
d99515e31e | ||
|
|
edce40958b | ||
|
|
4d431fbdbf | ||
|
|
fcf12face8 | ||
|
|
e36e740bc0 | ||
|
|
10c98c5f87 | ||
|
|
8d0ea9f67a | ||
|
|
9870accbae | ||
|
|
6610c37fea | ||
|
|
2d705a23f5 | ||
|
|
5c29072212 | ||
|
|
af6e2c2f2b | ||
|
|
713ab0314e | ||
|
|
3201ab324e | ||
|
|
5eb1a76e99 | ||
|
|
132c9531e1 | ||
|
|
a86cd5dcf5 | ||
|
|
65175c16d0 | ||
|
|
f6ea81cf5e | ||
|
|
1c12a9a258 | ||
|
|
b63f176ad7 | ||
|
|
d69a5f1f33 | ||
|
|
101fa4010d | ||
|
|
fba6037e3a |
No files matched your search
+28
-1
@@ -10,9 +10,36 @@ updates:
|
||||
update-types: [ minor, patch ]
|
||||
|
||||
- package-ecosystem: maven
|
||||
directory: /
|
||||
directories: [ "**/*" ]
|
||||
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)
|
||||
|
||||
@@ -12,7 +12,7 @@ jobs:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
- uses: actions/setup-java@03ad4de0992f5dab5e18fcb136590ce7c4a0ac95 # v5.6.0
|
||||
- uses: actions/setup-java@b6effb05e454b25005698d916606bdc6ffcbf961 # v5.7.0
|
||||
with:
|
||||
distribution: 'temurin'
|
||||
java-version-file: .java-version
|
||||
|
||||
@@ -20,7 +20,7 @@ jobs:
|
||||
issues: write
|
||||
steps:
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
- uses: actions/setup-java@03ad4de0992f5dab5e18fcb136590ce7c4a0ac95 # v5.6.0
|
||||
- uses: actions/setup-java@b6effb05e454b25005698d916606bdc6ffcbf961 # v5.7.0
|
||||
with:
|
||||
distribution: 'temurin'
|
||||
java-version-file: .java-version
|
||||
|
||||
@@ -50,7 +50,7 @@ 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@03ad4de0992f5dab5e18fcb136590ce7c4a0ac95 # v5.6.0
|
||||
uses: actions/setup-java@b6effb05e454b25005698d916606bdc6ffcbf961 # v5.7.0
|
||||
with:
|
||||
distribution: 'temurin'
|
||||
java-version-file: .java-version
|
||||
|
||||
@@ -10,10 +10,6 @@
|
||||
<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>
|
||||
@@ -39,7 +35,6 @@
|
||||
<dependency>
|
||||
<groupId>org.eclipse.jetty.http2</groupId>
|
||||
<artifactId>jetty-http2-client-transport</artifactId>
|
||||
<version>${jetty.http2-client.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
|
||||
@@ -13,12 +13,14 @@ 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.VerificationSessionManager;
|
||||
import org.whispersystems.textsecuregcm.storage.VerificationSessions;
|
||||
import software.amazon.awssdk.auth.credentials.AwsCredentialsProvider;
|
||||
@@ -36,6 +38,8 @@ public class IntegrationTools {
|
||||
|
||||
private final ChangeNumberWaitingPeriods changeNumberWaitingPeriods;
|
||||
|
||||
private final RedeemedReceiptsManager redeemedReceiptsManager;
|
||||
|
||||
public static IntegrationTools create(final Config config) {
|
||||
final AwsCredentialsProvider credentialsProvider = DefaultCredentialsProvider.builder().build();
|
||||
|
||||
@@ -55,7 +59,8 @@ public class IntegrationTools {
|
||||
new PhoneNumberRecoveryPasswordsManager(phoneNumberRecoveryPasswords),
|
||||
new VerificationSessionManager(verificationSessions),
|
||||
new PhoneNumberIdentifiers(dynamoDbAsyncClient, config.dynamoDbTables().phoneNumberIdentifiers()),
|
||||
new ChangeNumberWaitingPeriods(config.dynamoDbTables().changeNumberWaitingPeriods(), dynamoDbClient)
|
||||
new ChangeNumberWaitingPeriods(config.dynamoDbTables().changeNumberWaitingPeriods(), dynamoDbClient),
|
||||
new RedeemedReceiptsManager(Clock.systemUTC(), config.dynamoDbTables().redeemedReceipts(), dynamoDbClient)
|
||||
);
|
||||
}
|
||||
|
||||
@@ -63,11 +68,13 @@ public class IntegrationTools {
|
||||
final PhoneNumberRecoveryPasswordsManager phoneNumberRecoveryPasswordsManager,
|
||||
final VerificationSessionManager verificationSessionManager,
|
||||
final PhoneNumberIdentifiers phoneNumberIdentifiers,
|
||||
final ChangeNumberWaitingPeriods changeNumberWaitingPeriods) {
|
||||
final ChangeNumberWaitingPeriods changeNumberWaitingPeriods,
|
||||
final RedeemedReceiptsManager redeemedReceiptsManager) {
|
||||
this.phoneNumberRecoveryPasswordsManager = phoneNumberRecoveryPasswordsManager;
|
||||
this.verificationSessionManager = verificationSessionManager;
|
||||
this.phoneNumberIdentifiers = phoneNumberIdentifiers;
|
||||
this.changeNumberWaitingPeriods = changeNumberWaitingPeriods;
|
||||
this.redeemedReceiptsManager = redeemedReceiptsManager;
|
||||
}
|
||||
|
||||
public void populateRecoveryPassword(final String phoneNumber, final byte[] password) {
|
||||
@@ -87,4 +94,8 @@ public class IntegrationTools {
|
||||
public void clearChangeNumberWaitingPeriod(TestUser user) {
|
||||
changeNumberWaitingPeriods.delete(user.aciUuid());
|
||||
}
|
||||
|
||||
public void deleteRedeemedReceipt(final ReceiptSerial receiptSerial) {
|
||||
redeemedReceiptsManager.deleteReceipt(receiptSerial);
|
||||
}
|
||||
}
|
||||
@@ -49,6 +49,13 @@ 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.entities.AccountAttributes;
|
||||
@@ -83,6 +90,49 @@ public final class 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 newRegisteredUser(final String number) {
|
||||
final byte[] registrationPassword = populateRandomRecoveryPassword(number);
|
||||
final String accountPassword = Base64.getEncoder().encodeToString(randomBytes(32));
|
||||
@@ -96,14 +146,16 @@ 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),
|
||||
generateSignedECPreKey(2, pniIdentityKeyPair),
|
||||
Optional.of(generateSignedECPreKey(2, pniIdentityKeyPair)),
|
||||
generateSignedKEMPreKey(3, aciIdentityKeyPair),
|
||||
generateSignedKEMPreKey(4, pniIdentityKeyPair),
|
||||
Optional.of(generateSignedKEMPreKey(4, pniIdentityKeyPair)),
|
||||
Optional.empty(),
|
||||
Optional.empty()));
|
||||
|
||||
@@ -145,6 +197,10 @@ 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,
|
||||
|
||||
@@ -5,6 +5,7 @@
|
||||
|
||||
package org.signal.integration;
|
||||
|
||||
import jakarta.annotation.Nullable;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import org.apache.commons.lang3.tuple.Pair;
|
||||
@@ -22,10 +23,12 @@ public class TestDevice {
|
||||
public static TestDevice create(
|
||||
final byte deviceId,
|
||||
final IdentityKeyPair aciIdentityKeyPair,
|
||||
final IdentityKeyPair pniIdentityKeyPair) {
|
||||
@Nullable final IdentityKeyPair pniIdentityKeyPair) {
|
||||
final TestDevice device = new TestDevice(deviceId);
|
||||
device.addSignedPreKey(aciIdentityKeyPair);
|
||||
device.addSignedPreKey(pniIdentityKeyPair);
|
||||
if (pniIdentityKeyPair != null) {
|
||||
device.addSignedPreKey(pniIdentityKeyPair);
|
||||
}
|
||||
return device;
|
||||
}
|
||||
|
||||
|
||||
@@ -33,7 +33,8 @@ public class TestUser {
|
||||
|
||||
private final int registrationId;
|
||||
|
||||
private final int pniRegistrationId;
|
||||
@Nullable
|
||||
private final Integer pniRegistrationId;
|
||||
|
||||
private final IdentityKeyPair aciIdentityKey;
|
||||
|
||||
@@ -56,6 +57,22 @@ public class TestUser {
|
||||
@Nullable
|
||||
private UUID pniUuid;
|
||||
|
||||
public static TestUser createNumberless(final String accountPassword, final byte[] accountRecoveryPassword) {
|
||||
final IdentityKeyPair aciIdentityKey = IdentityKeyPair.generate();
|
||||
final int registrationId = KeyHelper.generateRegistrationId(false);
|
||||
final byte[] unidentifiedAccessKey = new byte[UnidentifiedAccessUtil.UNIDENTIFIED_ACCESS_KEY_LENGTH];
|
||||
new SecureRandom().nextBytes(unidentifiedAccessKey);
|
||||
|
||||
return new TestUser(
|
||||
registrationId,
|
||||
null,
|
||||
aciIdentityKey,
|
||||
null,
|
||||
null,
|
||||
unidentifiedAccessKey,
|
||||
accountPassword,
|
||||
accountRecoveryPassword);
|
||||
}
|
||||
|
||||
public static TestUser create(final String phoneNumber, final String accountPassword, final byte[] registrationPassword) {
|
||||
// ACI identity key pair
|
||||
@@ -82,10 +99,10 @@ public class TestUser {
|
||||
|
||||
public TestUser(
|
||||
final int registrationId,
|
||||
final int pniRegistrationId,
|
||||
@Nullable final Integer pniRegistrationId,
|
||||
final IdentityKeyPair aciIdentityKey,
|
||||
final String phoneNumber,
|
||||
final IdentityKeyPair pniIdentityKey,
|
||||
@Nullable final String phoneNumber,
|
||||
@Nullable final IdentityKeyPair pniIdentityKey,
|
||||
final byte[] unidentifiedAccessKey,
|
||||
final String accountPassword,
|
||||
final byte[] registrationPassword) {
|
||||
@@ -134,7 +151,7 @@ public class TestUser {
|
||||
|
||||
public AccountAttributes accountAttributes() {
|
||||
return new AccountAttributes(true, registrationId, pniRegistrationId, "".getBytes(StandardCharsets.UTF_8), "", true,
|
||||
DeviceCapability.CAPABILITIES_REQUIRED_FOR_NEW_DEVICES)
|
||||
DeviceCapability.CAPABILITIES_REQUIRED_FOR_NEW_DEVICES, null)
|
||||
.setUnidentifiedAccessKey(unidentifiedAccessKey)
|
||||
.setRecoveryPassword(registrationPassword);
|
||||
}
|
||||
|
||||
@@ -15,5 +15,8 @@ public record Config(@NotBlank String domain,
|
||||
@NotNull @Valid DynamoDbClientFactory dynamoDbClient,
|
||||
@NotNull @Valid DynamoDbTables dynamoDbTables,
|
||||
@NotBlank String prescribedRegistrationNumber,
|
||||
@NotBlank String prescribedRegistrationCode) {
|
||||
@NotBlank String prescribedRegistrationCode,
|
||||
@NotBlank String prescribedReceiptSerial,
|
||||
@NotBlank String prescribedReceiptCredential,
|
||||
@NotBlank String serverZkPublicParams) {
|
||||
}
|
||||
@@ -10,5 +10,6 @@ import jakarta.validation.constraints.NotBlank;
|
||||
public record DynamoDbTables(@NotBlank String registrationRecovery,
|
||||
@NotBlank String verificationSessions,
|
||||
@NotBlank String phoneNumberIdentifiers,
|
||||
@NotBlank String changeNumberWaitingPeriods) {
|
||||
@NotBlank String changeNumberWaitingPeriods,
|
||||
@NotBlank String redeemedReceipts) {
|
||||
}
|
||||
@@ -21,6 +21,8 @@ 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;
|
||||
@@ -33,6 +35,22 @@ 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 testCreateAccount() {
|
||||
final TestUser user = Operations.newRegisteredUser("+19995550101");
|
||||
|
||||
@@ -61,7 +61,7 @@ public class MessagingTest {
|
||||
assertDoesNotThrow(() -> WebsocketClientSession.decode(SendMessageResponse.class, responseMessage));
|
||||
|
||||
final WebsocketClientSession websocketB = Operations.authenticatedWebsocket(userB, Device.PRIMARY_ID);
|
||||
assertTimeoutPreemptively(Duration.ofSeconds(5), websocketB::waitForQueueEmpty);
|
||||
assertTimeoutPreemptively(Duration.ofSeconds(15), websocketB::waitForQueueEmpty);
|
||||
|
||||
assertEquals(1, websocketB.getReceivedEnvelopes().size());
|
||||
final MessageProtos.Envelope envelope = websocketB.getReceivedEnvelopes().getFirst();
|
||||
|
||||
@@ -45,57 +45,59 @@
|
||||
</modules>
|
||||
|
||||
<properties>
|
||||
<aws.sdk2.version>2.42.27</aws.sdk2.version>
|
||||
<braintree.version>3.48.0</braintree.version>
|
||||
<aws.sdk2.version>2.54.5</aws.sdk2.version>
|
||||
<braintree.version>3.53.0</braintree.version>
|
||||
<commons-csv.version>1.14.1</commons-csv.version>
|
||||
<commons-io.version>2.21.0</commons-io.version>
|
||||
<dropwizard.version>5.0.1</dropwizard.version>
|
||||
<commons-io.version>2.22.0</commons-io.version>
|
||||
<dropwizard.version>5.0.2</dropwizard.version>
|
||||
<!-- Note: We use x86_64 builds without AVX instructions enabled (i.e. FoundationDB versions with even-numbered
|
||||
patch versions). Also when updating FoundationDB, make sure to update the version of FoundationDBused by GitHub
|
||||
Actions. -->
|
||||
<foundationdb.version>7.3.68</foundationdb.version>
|
||||
patch versions). -->
|
||||
<foundationdb.version>7.3.76</foundationdb.version>
|
||||
<foundationdb.api-version>730</foundationdb.api-version>
|
||||
<foundationdb.client-library-sha256>8c96a1f7ab561cd38e16e4c269c5e50ae0fd8063854e0d72c89339a7ac1b6873</foundationdb.client-library-sha256>
|
||||
<google-cloud-libraries.version>26.79.0</google-cloud-libraries.version>
|
||||
<foundationdb.client-library-sha256>af099848721d08904ff9e5d38fade0de24d92e86451ea491d9ab5ce84adcf62a</foundationdb.client-library-sha256>
|
||||
<google-cloud-libraries.version>26.86.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.13.2</gson.version>
|
||||
<guava.version>33.5.0-jre</guava.version>
|
||||
<gson.version>2.14.0</gson.version>
|
||||
<guava.version>33.7.1-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.21.2</jackson.version>
|
||||
<jackson.version>2.22.2</jackson.version>
|
||||
<java-otp.version>1.0.0</java-otp.version>
|
||||
<jetty.version>12.1.9</jetty.version>
|
||||
<junit-pioneer.version>2.3.0</junit-pioneer.version>
|
||||
<jsr305.version>3.0.2</jsr305.version>
|
||||
<kotlin.version>2.3.20</kotlin.version>
|
||||
<kotlin.version>2.4.10</kotlin.version>
|
||||
<!-- dropwizard references a constant removed in 1.6. See also: dependabot.yml -->
|
||||
<logback.version>1.5.38</logback.version>
|
||||
<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 -->
|
||||
<logback-access-common.version>2.0.15</logback-access-common.version>
|
||||
<lettuce.version>7.6.0.RELEASE</lettuce.version>
|
||||
<libphonenumber.version>9.0.37</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 -->
|
||||
<resilience4j.version>2.4.0</resilience4j.version>
|
||||
<semver4j.version>3.1.0</semver4j.version>
|
||||
<simple-grpc.version>0.2.0</simple-grpc.version>
|
||||
<slf4j.version>2.0.17</slf4j.version>
|
||||
<stripe.version>33.1.0</stripe.version>
|
||||
<swagger.version>2.2.46</swagger.version>
|
||||
<testcontainers.version>2.0.4</testcontainers.version>
|
||||
<simple-grpc.version>0.2.1</simple-grpc.version>
|
||||
<slf4j.version>2.0.18</slf4j.version>
|
||||
<stripe.version>33.3.0</stripe.version>
|
||||
<swagger.version>2.2.54</swagger.version>
|
||||
<testcontainers.version>2.0.5</testcontainers.version>
|
||||
|
||||
<!-- images to use in tests via testcontainers -->
|
||||
<dynamodb.image>amazon/dynamodb-local:3.3.0@sha256:d89f8fcc6b1a39cb35976c248ed42a28c66ae00dc043099210f5571e42648ab4</dynamodb.image>
|
||||
<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>
|
||||
<redis-cluster.image>docker.io/bitnamilegacy/redis-cluster:7.4.3@sha256:a53d023fdfaf8a8d7ddc58da040d3494e4cb45772644618ffa44c42dcd32b9af</redis-cluster.image>
|
||||
|
||||
<docker.image>eclipse-temurin:25-jre-resolute@sha256:17ddcc32b1f296155738c4b2f689208e46bf0cf4eb0b215c717717deb8b74b90</docker.image>
|
||||
<docker.image>eclipse-temurin:25-jre-resolute@sha256:71bfb73662d4146bdc9ee2f97418a764d5ab4e83f4e90baec3b3dcda14071007</docker.image>
|
||||
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
</properties>
|
||||
@@ -105,7 +107,9 @@
|
||||
<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>
|
||||
@@ -113,6 +117,50 @@
|
||||
<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>
|
||||
@@ -127,27 +175,6 @@
|
||||
<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>
|
||||
@@ -165,14 +192,14 @@
|
||||
<dependency>
|
||||
<groupId>io.opentelemetry</groupId>
|
||||
<artifactId>opentelemetry-bom</artifactId>
|
||||
<version>1.60.1</version>
|
||||
<version>1.65.0</version>
|
||||
<type>pom</type>
|
||||
<scope>import</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>io.opentelemetry.instrumentation</groupId>
|
||||
<artifactId>opentelemetry-instrumentation-bom</artifactId>
|
||||
<version>2.26.1</version>
|
||||
<version>2.31.1</version>
|
||||
<type>pom</type>
|
||||
<scope>import</scope>
|
||||
</dependency>
|
||||
@@ -190,6 +217,11 @@
|
||||
<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>
|
||||
@@ -249,7 +281,7 @@
|
||||
<dependency>
|
||||
<groupId>commons-logging</groupId>
|
||||
<artifactId>commons-logging</artifactId>
|
||||
<version>1.3.6</version>
|
||||
<version>1.4.0</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.stripe</groupId>
|
||||
@@ -285,7 +317,7 @@
|
||||
<dependency>
|
||||
<groupId>org.signal</groupId>
|
||||
<artifactId>libsignal-server</artifactId>
|
||||
<version>0.100.0</version>
|
||||
<version>0.101.0</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.signal</groupId>
|
||||
@@ -354,7 +386,7 @@
|
||||
<dependency>
|
||||
<groupId>org.wiremock</groupId>
|
||||
<artifactId>wiremock-jetty12</artifactId>
|
||||
<version>3.13.1</version>
|
||||
<version>3.13.2</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
@@ -422,32 +454,32 @@
|
||||
<plugin>
|
||||
<groupId>com.google.cloud.tools</groupId>
|
||||
<artifactId>jib-maven-plugin</artifactId>
|
||||
<version>3.4.6</version>
|
||||
<version>3.5.2</version>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-surefire-plugin</artifactId>
|
||||
<version>3.5.5</version>
|
||||
<version>3.5.6</version>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-failsafe-plugin</artifactId>
|
||||
<version>3.5.4</version>
|
||||
<version>3.5.6</version>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-jar-plugin</artifactId>
|
||||
<version>3.5.0</version>
|
||||
<version>3.5.1</version>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-shade-plugin</artifactId>
|
||||
<version>3.6.1</version>
|
||||
<version>3.6.2</version>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-assembly-plugin</artifactId>
|
||||
<version>3.7.1</version>
|
||||
<version>3.8.0</version>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.codehaus.mojo</groupId>
|
||||
@@ -457,7 +489,7 @@
|
||||
<plugin>
|
||||
<groupId>org.codehaus.mojo</groupId>
|
||||
<artifactId>properties-maven-plugin</artifactId>
|
||||
<version>1.2.1</version>
|
||||
<version>1.3.0</version>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</pluginManagement>
|
||||
@@ -469,7 +501,7 @@
|
||||
<version>0.6.1</version>
|
||||
<configuration>
|
||||
<checkStaleness>false</checkStaleness>
|
||||
<protocArtifact>com.google.protobuf:protoc:${protoc.version}:exe:${os.detected.classifier}</protocArtifact>
|
||||
<protocArtifact>com.google.protobuf:protoc:${protobuf.version}:exe:${os.detected.classifier}</protocArtifact>
|
||||
<pluginId>grpc-java</pluginId>
|
||||
<pluginArtifact>io.grpc:protoc-gen-grpc-java:${grpc.version}:exe:${os.detected.classifier}</pluginArtifact>
|
||||
|
||||
@@ -507,7 +539,7 @@
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-jar-plugin</artifactId>
|
||||
<version>3.5.0</version>
|
||||
<version>3.5.1</version>
|
||||
<configuration>
|
||||
<archive>
|
||||
<manifest>
|
||||
@@ -520,7 +552,7 @@
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-dependency-plugin</artifactId>
|
||||
<version>3.10.0</version>
|
||||
<version>3.11.0</version>
|
||||
<executions>
|
||||
<execution>
|
||||
<!--
|
||||
@@ -540,7 +572,7 @@
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-enforcer-plugin</artifactId>
|
||||
<version>3.6.2</version>
|
||||
<version>3.6.3</version>
|
||||
<executions>
|
||||
<execution>
|
||||
<goals>
|
||||
|
||||
@@ -79,7 +79,8 @@ 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
|
||||
|
||||
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==
|
||||
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==
|
||||
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
|
||||
|
||||
@@ -138,7 +138,6 @@ 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
|
||||
@@ -316,8 +315,11 @@ storageService:
|
||||
AAAAAAAAAAAAAAAAAAAA
|
||||
-----END CERTIFICATE-----
|
||||
|
||||
callingZkConfigPreV101:
|
||||
serverSecret: secret://callingZkConfigPreV101.serverSecret
|
||||
|
||||
callingZkConfig:
|
||||
serverSecret: secret://callingZkConfig.serverSecret
|
||||
serverSecret: secret://callingZkConfigV101.serverSecret
|
||||
|
||||
chatZkConfig:
|
||||
serverSecret: secret://chatZkConfig.serverSecret
|
||||
|
||||
+45
-20
@@ -11,19 +11,18 @@
|
||||
<artifactId>service</artifactId>
|
||||
|
||||
<properties>
|
||||
<apollo-api-jvm.version>3.8.5</apollo-api-jvm.version>
|
||||
<apollo-api-jvm.version>3.8.6</apollo-api-jvm.version>
|
||||
<commons-compress.version>1.28.0</commons-compress.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>
|
||||
<dynamodb-lock-client.version>1.5.0</dynamodb-lock-client.version>
|
||||
<firebase-admin.version>9.10.0</firebase-admin.version>
|
||||
<libphonenumber-geocoder.version>3.37</libphonenumber-geocoder.version>
|
||||
<google-androidpublisher.version>v3-rev20250904-2.0.0</google-androidpublisher.version>
|
||||
<java-jwt.version>4.5.0</java-jwt.version>
|
||||
<java-jwt.version>4.6.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.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>
|
||||
<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>
|
||||
</properties>
|
||||
|
||||
<dependencies>
|
||||
@@ -47,6 +46,11 @@
|
||||
<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>
|
||||
@@ -142,7 +146,6 @@
|
||||
<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>
|
||||
@@ -173,6 +176,20 @@
|
||||
<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>
|
||||
@@ -284,16 +301,11 @@
|
||||
<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>
|
||||
<groupId>io.opentelemetry.instrumentation</groupId>
|
||||
<artifactId>opentelemetry-instrumentation-api-incubator</artifactId>
|
||||
<!-- conflicts with jackson-dataformat 2.22.1 -->
|
||||
<groupId>org.codehaus.woodstox</groupId>
|
||||
<artifactId>stax2-api</artifactId>
|
||||
</exclusion>
|
||||
</exclusions>
|
||||
</dependency>
|
||||
@@ -303,6 +315,13 @@
|
||||
<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>
|
||||
@@ -404,6 +423,11 @@
|
||||
<artifactId>lettuce-core</artifactId>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>com.eatthepath</groupId>
|
||||
<artifactId>java-otp</artifactId>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>com.eatthepath</groupId>
|
||||
<artifactId>pushy</artifactId>
|
||||
@@ -616,7 +640,8 @@
|
||||
<dependency>
|
||||
<groupId>com.squareup.okio</groupId>
|
||||
<artifactId>okio-jvm</artifactId>
|
||||
<version>3.16.4</version>
|
||||
<!-- update dependabot.yml when this dependency is removed -->
|
||||
<version>3.17.0</version>
|
||||
</dependency>
|
||||
|
||||
</dependencies>
|
||||
@@ -831,7 +856,7 @@
|
||||
<plugin>
|
||||
<groupId>org.codehaus.mojo</groupId>
|
||||
<artifactId>templating-maven-plugin</artifactId>
|
||||
<version>3.0.0</version>
|
||||
<version>3.1.0</version>
|
||||
<executions>
|
||||
<execution>
|
||||
<id>filter-src</id>
|
||||
|
||||
+20
@@ -63,6 +63,7 @@ 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;
|
||||
@@ -227,6 +228,11 @@ public class WhisperServerConfiguration extends Configuration {
|
||||
@JsonProperty
|
||||
private PaymentsServiceConfiguration paymentsService;
|
||||
|
||||
@Valid
|
||||
@NotNull
|
||||
@JsonProperty
|
||||
private GenericZkConfig callingZkConfigPreV101;
|
||||
|
||||
@Valid
|
||||
@NotNull
|
||||
@JsonProperty
|
||||
@@ -379,6 +385,11 @@ public class WhisperServerConfiguration extends Configuration {
|
||||
@JsonProperty
|
||||
private FoundationDbMessagesConfiguration foundationDbMessages;
|
||||
|
||||
@Valid
|
||||
@NotNull
|
||||
@JsonProperty
|
||||
private TotpConfiguration registrationTotp = TotpConfiguration.DEFAULT;
|
||||
|
||||
public TlsKeyStoreConfiguration getTlsKeyStoreConfiguration() {
|
||||
return tlsKeyStore;
|
||||
}
|
||||
@@ -508,6 +519,11 @@ 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;
|
||||
@@ -633,4 +649,8 @@ public class WhisperServerConfiguration extends Configuration {
|
||||
public FoundationDbMessagesConfiguration getFoundationDbMessagesConfiguration() {
|
||||
return foundationDbMessages;
|
||||
}
|
||||
|
||||
public TotpConfiguration getRegistrationTotpConfiguration() {
|
||||
return registrationTotp;
|
||||
}
|
||||
}
|
||||
@@ -175,6 +175,7 @@ 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;
|
||||
@@ -206,7 +207,6 @@ 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;
|
||||
@@ -272,14 +272,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.PhoneNumberRecoveryPasswords;
|
||||
import org.whispersystems.textsecuregcm.storage.PhoneNumberRecoveryPasswordsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.RemoteConfigs;
|
||||
import org.whispersystems.textsecuregcm.storage.RemoteConfigsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.RepeatedUseECSignedPreKeyStore;
|
||||
@@ -327,6 +327,7 @@ 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;
|
||||
@@ -405,6 +406,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
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",
|
||||
@@ -542,10 +544,15 @@ 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(),
|
||||
@@ -798,7 +805,8 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
pubsubClient, accountLockManager, keysManager, messagesManager, profilesManager,
|
||||
changeNumberWaitingPeriodManager, secureStorageClient, secureValueRecovery2Client, disconnectionRequestManager,
|
||||
phoneNumberRecoveryPasswordsManager, accountLockExecutor, messagePollExecutor,
|
||||
retryExecutor, clock, config.getLinkDeviceSecretConfiguration().secret().value());
|
||||
retryExecutor, clock, config.getLinkDeviceSecretConfiguration().secret().value(),
|
||||
config.getRegistrationTotpConfiguration().maxValidationDelay());
|
||||
RemoteConfigsManager remoteConfigsManager = new RemoteConfigsManager(remoteConfigs, config.getRemoteConfigConfiguration().globalConfig());
|
||||
APNSender apnSender = new APNSender(apnSenderExecutor, Clock.systemUTC(), config.getApnConfiguration());
|
||||
FcmSender fcmSender = new FcmSender(fcmSenderExecutor, config.getFcmConfiguration().credentials().value());
|
||||
@@ -817,10 +825,6 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
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 =
|
||||
@@ -936,6 +940,7 @@ 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);
|
||||
@@ -1141,6 +1146,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
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()),
|
||||
@@ -1176,11 +1182,14 @@ 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(List.of(
|
||||
new OmnibusRouter.OmnibusRoute("/v1/websocket", websocketAddress),
|
||||
new OmnibusRouter.OmnibusRoute("/v1/provisioning", websocketAddress)),
|
||||
final OmnibusRouter omnibusRouter = new OmnibusRouter(Map.of(
|
||||
websocketServletPath, websocketAddress,
|
||||
provisioningWebsocketServletPath, websocketAddress),
|
||||
grpcLocalAddress);
|
||||
@Nullable final Mapping<String, SslContext> sniMapping = config.getGrpc().h2c()
|
||||
? null
|
||||
@@ -1211,9 +1220,6 @@ 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,
|
||||
@@ -1263,9 +1269,9 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
experimentEnrollmentManager, config.getAttachments().maxAttachmentUploadSizeInBytes()),
|
||||
new ArchiveController(accountsManager, backupAuthManager, backupManager, backupMetrics, config.getAttachments().maxAttachmentUploadSizeInBytes(), config.getAttachments().maxMessageBackupUploadSizeInBytes()),
|
||||
new CallRoutingControllerV2(rateLimiters, cloudflareTurnCredentialsManager),
|
||||
new CallLinkController(rateLimiters, callingGenericZkSecretParams),
|
||||
new CallLinkController(rateLimiters, callingGenericZkSecretParams, callingPreV101GenericZkSecretParams),
|
||||
new CallQualitySurveyController(callQualitySurveyManager),
|
||||
new CertificateController(accountsManager, certificateGenerator, zkAuthOperations, callingGenericZkSecretParams, clock),
|
||||
new CertificateController(accountsManager, certificateGenerator, zkAuthOperations, callingGenericZkSecretParams, callingPreV101GenericZkSecretParams, clock),
|
||||
new ChallengeController(accountsManager, rateLimitChallengeManager, challengeConstraintChecker),
|
||||
new DeviceController(accountsManager, rateLimiters, persistentTimer),
|
||||
new DeviceCheckController(clock, accountsManager, backupAuthManager, appleDeviceCheckManager, rateLimiters,
|
||||
@@ -1283,7 +1289,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
groupZkSecretParams, zkProfileOperations, batchIdentityCheckExecutor),
|
||||
new ProvisioningController(rateLimiters, provisioningManager),
|
||||
new RegistrationController(accountsManager, phoneVerificationTokenManager, registrationLockVerificationManager,
|
||||
rateLimiters, registrationFraudChecker),
|
||||
rateLimiters, registrationFraudChecker, ReceiptCredentialPresentation::new, zkReceiptOperations, clock, dynamicConfigurationManager),
|
||||
new RemoteConfigController(remoteConfigsManager),
|
||||
new SecureStorageController(storageCredentialsGenerator),
|
||||
new SecureValueRecovery2Controller(svr2CredentialsGenerator, accountsManager),
|
||||
@@ -1360,7 +1366,6 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
List.of(
|
||||
new LoggingUnhandledExceptionMapper(),
|
||||
new CompletionExceptionMapper(),
|
||||
new GrpcStatusRuntimeExceptionMapper(),
|
||||
new IOExceptionMapper(),
|
||||
new RateLimitExceededExceptionMapper(),
|
||||
new InvalidWebsocketAddressExceptionMapper(),
|
||||
|
||||
+2
-3
@@ -19,7 +19,6 @@ 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;
|
||||
@@ -101,7 +100,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.getIdentifier(IdentityType.ACI),
|
||||
return Optional.of(new AuthenticatedDevice(authenticatedAccount.getAccountIdentifier(),
|
||||
device.get().getId(),
|
||||
Instant.ofEpochMilli(authenticatedAccount.getPrimaryDevice().getLastSeen())));
|
||||
} else {
|
||||
@@ -142,7 +141,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.getIdentifier(IdentityType.ACI), device, Util.todayInMillis(clock));
|
||||
return accountsManager.updateDeviceLastSeen(account.getAccountIdentifier(), device, Util.todayInMillis(clock));
|
||||
}
|
||||
|
||||
return account;
|
||||
|
||||
+2
-2
@@ -34,7 +34,7 @@ public class CertificateGenerator {
|
||||
}
|
||||
|
||||
public byte[] createFor(final Account account, final byte deviceId, boolean includeE164) {
|
||||
if (includeE164 && account.getNumberOptional().isEmpty()) {
|
||||
if (includeE164 && account.getNumber().isEmpty()) {
|
||||
throw new IllegalArgumentException();
|
||||
}
|
||||
|
||||
@@ -45,7 +45,7 @@ public class CertificateGenerator {
|
||||
.setSenderUuid(UUIDUtil.toByteString(account.getAccountIdentifier()));
|
||||
|
||||
if (includeE164) {
|
||||
builder.setSenderE164(account.getNumberOptional().get());
|
||||
builder.setSenderE164(account.getNumber().get());
|
||||
}
|
||||
|
||||
if (embedSigner) {
|
||||
|
||||
+1
-1
@@ -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.getIdentifier(IdentityType.ACI),
|
||||
return requestDisconnection(account.getAccountIdentifier(),
|
||||
account.getDevices().stream().map(Device::getId).toList());
|
||||
}
|
||||
|
||||
|
||||
+17
-9
@@ -14,6 +14,7 @@ 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;
|
||||
@@ -28,6 +29,7 @@ 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;
|
||||
|
||||
public class RegistrationLockVerificationManager {
|
||||
public enum Flow {
|
||||
@@ -85,7 +87,7 @@ public class RegistrationLockVerificationManager {
|
||||
final PhoneVerificationRequest.VerificationType phoneVerificationType
|
||||
) throws RateLimitExceededException, RegistrationLockFailureException {
|
||||
|
||||
final String phoneNumber = account.getNumberOptional()
|
||||
final String phoneNumber = account.getNumber()
|
||||
.orElseThrow(() -> new IllegalArgumentException("account does not have a phone number"));
|
||||
|
||||
final Tags expiredTags = Tags.of(UserAgentTagUtil.getPlatformTag(userAgent),
|
||||
@@ -137,12 +139,8 @@ 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 Account updatedAccount;
|
||||
if (!alreadyLocked) {
|
||||
updatedAccount = accounts.update(account, Account::lockAuthTokenHash);
|
||||
} else {
|
||||
updatedAccount = account;
|
||||
}
|
||||
|
||||
final List<TransactWriteItem> additionalWriteItems;
|
||||
|
||||
// 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.
|
||||
@@ -151,10 +149,20 @@ 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) {
|
||||
phoneNumberRecoveryPasswordsManager.remove(updatedAccount.getPhoneNumberIdentifierOptional()
|
||||
.orElseThrow(() -> new AssertionError("Account with a phone number did not have a phone number identifier")));
|
||||
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();
|
||||
}
|
||||
|
||||
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);
|
||||
|
||||
|
||||
+1
-1
@@ -266,7 +266,7 @@ public class BackupAuthManager {
|
||||
}
|
||||
|
||||
boolean receiptAllowed = redeemedReceiptsManager
|
||||
.put(receiptSerial, receiptExpiration.getEpochSecond(), receiptLevel, account.getAccountIdentifier());
|
||||
.put(receiptSerial, receiptExpiration, receiptLevel, account.getAccountIdentifier());
|
||||
if (!receiptAllowed) {
|
||||
throw new BackupBadReceiptException("receipt serial is already redeemed");
|
||||
}
|
||||
|
||||
+3
-3
@@ -69,7 +69,7 @@ public class DynamoDbTables {
|
||||
private final Table profilesV2;
|
||||
private final Table pushChallenge;
|
||||
private final Table pushNotificationExperimentSamples;
|
||||
private final TableWithExpiration redeemedReceipts;
|
||||
private final Table 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 TableWithExpiration redeemedReceipts,
|
||||
@JsonProperty("redeemedReceipts") final Table 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 TableWithExpiration getRedeemedReceipts() {
|
||||
public Table getRedeemedReceipts() {
|
||||
return redeemedReceipts;
|
||||
}
|
||||
|
||||
|
||||
+1
@@ -18,6 +18,7 @@ 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 {
|
||||
|
||||
|
||||
+20
@@ -0,0 +1,20 @@
|
||||
/*
|
||||
* 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();
|
||||
}
|
||||
}
|
||||
}
|
||||
+9
-5
@@ -55,7 +55,6 @@ 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;
|
||||
@@ -208,7 +207,7 @@ public class AccountController {
|
||||
throw new ForbiddenException();
|
||||
}
|
||||
|
||||
accounts.updateDevice(account.getIdentifier(IdentityType.ACI), targetDeviceId, d -> d.setName(deviceName.deviceName()));
|
||||
accounts.updateDevice(account.getAccountIdentifier(), targetDeviceId, d -> d.setName(deviceName.deviceName()));
|
||||
}
|
||||
|
||||
@PUT
|
||||
@@ -224,12 +223,12 @@ public class AccountController {
|
||||
.orElseThrow(() -> new WebApplicationException(Status.UNAUTHORIZED));
|
||||
|
||||
final Collection<TransactWriteItem> additionalWriteItems =
|
||||
account.getPhoneNumberIdentifierOptional()
|
||||
account.getPhoneNumberIdentifier()
|
||||
.flatMap(phoneNumberIdentifier -> attributes.recoveryPassword().map(recoveryPassword ->
|
||||
List.of(phoneNumberRecoveryPasswordsManager.buildTransactWriteItemForStorePassword(phoneNumberIdentifier, recoveryPassword))))
|
||||
.orElseGet(Collections::emptyList);
|
||||
|
||||
final Account updatedAccount = accounts.update(auth.accountIdentifier(), a -> {
|
||||
accounts.update(auth.accountIdentifier(), a -> {
|
||||
a.getDevice(auth.deviceId()).ifPresent(d -> {
|
||||
d.setFetchesMessages(attributes.getFetchesMessages());
|
||||
d.setName(attributes.getName());
|
||||
@@ -243,6 +242,11 @@ public class AccountController {
|
||||
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);
|
||||
@@ -430,7 +434,7 @@ public class AccountController {
|
||||
} else {
|
||||
usernameLinkHandle = UUID.randomUUID();
|
||||
}
|
||||
updateUsernameLink(account.getIdentifier(IdentityType.ACI), usernameLinkHandle, encryptedUsername.usernameLinkEncryptedValue());
|
||||
updateUsernameLink(account.getAccountIdentifier(), usernameLinkHandle, encryptedUsername.usernameLinkEncryptedValue());
|
||||
return new UsernameLinkHandle(usernameLinkHandle);
|
||||
}
|
||||
|
||||
|
||||
+8
-3
@@ -155,8 +155,13 @@ public class AccountControllerV2 {
|
||||
@Auth AuthenticatedDevice auth,
|
||||
@NotNull @Valid PhoneNumberDiscoverabilityRequest phoneNumberDiscoverability) {
|
||||
|
||||
accountsManager.update(auth.accountIdentifier(), a -> a.setDiscoverableByPhoneNumber(
|
||||
phoneNumberDiscoverability.discoverableByPhoneNumber()));
|
||||
accountsManager.update(auth.accountIdentifier(), account -> {
|
||||
if (account.getNumber().isEmpty()) {
|
||||
throw new BadRequestException();
|
||||
}
|
||||
|
||||
account.setDiscoverableByPhoneNumber(phoneNumberDiscoverability.discoverableByPhoneNumber());
|
||||
});
|
||||
}
|
||||
|
||||
@GET
|
||||
@@ -174,7 +179,7 @@ public class AccountControllerV2 {
|
||||
return new AccountDataReportResponse(UUID.randomUUID(), Instant.now(),
|
||||
new AccountDataReportResponse.AccountAndDevicesDataReport(
|
||||
new AccountDataReportResponse.AccountDataReport(
|
||||
account.getNumberOptional(),
|
||||
account.getNumber(),
|
||||
account.getBadges().stream().map(AccountDataReportResponse.BadgeDataReport::new).toList(),
|
||||
account.isUnrestrictedUnidentifiedAccess(),
|
||||
account.isDiscoverableByPhoneNumber()),
|
||||
|
||||
+4
-3
@@ -48,12 +48,13 @@ public class AccountIdentityResponseBuilder {
|
||||
.orElse(null);
|
||||
|
||||
return new AccountIdentityResponse(account.getAccountIdentifier(),
|
||||
account.getNumberOptional(),
|
||||
account.getPhoneNumberIdentifierOptional(),
|
||||
account.getNumber(),
|
||||
account.getPhoneNumberIdentifier(),
|
||||
account.getUsernameHash().filter(h -> h.length > 0).orElse(null),
|
||||
account.getUsernameLinkHandle(),
|
||||
storageCapable,
|
||||
new Entitlements(badges, backupEntitlement));
|
||||
new Entitlements(badges, backupEntitlement),
|
||||
account.getAuthCredentialSalt().orElse(null));
|
||||
}
|
||||
|
||||
public static AccountIdentityResponse fromAccount(final Account account) {
|
||||
|
||||
+10
-3
@@ -2,6 +2,7 @@ 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;
|
||||
@@ -9,6 +10,7 @@ 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;
|
||||
@@ -26,13 +28,16 @@ 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 genericServerSecretParams,
|
||||
final GenericServerSecretParams genericServerSecretParamsPreV101
|
||||
) {
|
||||
this.rateLimiters = rateLimiters;
|
||||
this.genericServerSecretParams = genericServerSecretParams;
|
||||
this.genericServerSecretParamsPreV101 = genericServerSecretParamsPreV101;
|
||||
}
|
||||
|
||||
@POST
|
||||
@@ -52,7 +57,9 @@ public class CallLinkController {
|
||||
@ApiResponse(responseCode = "429", description = "Ratelimited.")
|
||||
public CreateCallLinkCredential getCreateAuth(
|
||||
final @Auth AuthenticatedDevice auth,
|
||||
final @NotNull @Valid GetCreateCallLinkCredentialsRequest request
|
||||
final @NotNull @Valid GetCreateCallLinkCredentialsRequest request,
|
||||
@Parameter(description = "Whether to use libsignal v0.101.0+ secret params")
|
||||
final @QueryParam("v101") boolean v101
|
||||
) throws RateLimitExceededException {
|
||||
|
||||
rateLimiters.getCreateCallLinkLimiter().validate(auth.accountIdentifier());
|
||||
@@ -67,7 +74,7 @@ public class CallLinkController {
|
||||
}
|
||||
|
||||
return new CreateCallLinkCredential(
|
||||
createCallLinkCredentialRequest.issueCredential(new ServiceId.Aci(auth.accountIdentifier()), truncatedDayTimestamp, genericServerSecretParams).serialize(),
|
||||
createCallLinkCredentialRequest.issueCredential(new ServiceId.Aci(auth.accountIdentifier()), truncatedDayTimestamp, v101 ? genericServerSecretParams : genericServerSecretParamsPreV101).serialize(),
|
||||
truncatedDayTimestamp.getEpochSecond()
|
||||
);
|
||||
}
|
||||
|
||||
+9
-3
@@ -10,6 +10,7 @@ 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;
|
||||
@@ -49,6 +50,7 @@ public class CertificateController {
|
||||
private final CertificateGenerator certificateGenerator;
|
||||
private final ServerZkAuthOperations serverZkAuthOperations;
|
||||
private final GenericServerSecretParams genericServerSecretParams;
|
||||
private final GenericServerSecretParams genericServerSecretParamsPreV101;
|
||||
private final Clock clock;
|
||||
|
||||
@VisibleForTesting
|
||||
@@ -61,12 +63,14 @@ 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);
|
||||
}
|
||||
|
||||
@@ -95,7 +99,9 @@ public class CertificateController {
|
||||
public GroupCredentials getGroupAuthenticationCredentials(
|
||||
@Auth AuthenticatedDevice auth,
|
||||
@QueryParam("redemptionStartSeconds") long startSeconds,
|
||||
@QueryParam("redemptionEndSeconds") long endSeconds) {
|
||||
@QueryParam("redemptionEndSeconds") long endSeconds,
|
||||
@Parameter(description = "Whether to use libsignal v0.101.0+ secret params")
|
||||
@QueryParam("v101") boolean v101) {
|
||||
|
||||
final RedemptionRange redemptionRange;
|
||||
try {
|
||||
@@ -113,7 +119,7 @@ public class CertificateController {
|
||||
final List<GroupCredentials.CallLinkAuthCredential> callLinkAuthCredentials = new ArrayList<>();
|
||||
|
||||
final ServiceId.Aci aci = new ServiceId.Aci(account.getAccountIdentifier());
|
||||
final Optional<ServiceId.Pni> maybePni = account.getPhoneNumberIdentifierOptional().map(ServiceId.Pni::new);
|
||||
final Optional<ServiceId.Pni> maybePni = account.getPhoneNumberIdentifier().map(ServiceId.Pni::new);
|
||||
|
||||
for (Instant redemption : redemptionRange) {
|
||||
final AuthCredentialWithPniResponse authCredentialWithPni =
|
||||
@@ -127,7 +133,7 @@ public class CertificateController {
|
||||
(int) redemption.getEpochSecond()));
|
||||
|
||||
callLinkAuthCredentials.add(new GroupCredentials.CallLinkAuthCredential(
|
||||
CallLinkAuthCredentialResponse.issueCredential(aci, redemption, genericServerSecretParams).serialize(),
|
||||
CallLinkAuthCredentialResponse.issueCredential(aci, redemption, v101 ? genericServerSecretParams : genericServerSecretParamsPreV101).serialize(),
|
||||
redemption.getEpochSecond()));
|
||||
}
|
||||
|
||||
|
||||
+6
@@ -14,6 +14,7 @@ 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;
|
||||
@@ -35,6 +36,7 @@ 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;
|
||||
@@ -139,6 +141,10 @@ 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));
|
||||
|
||||
|
||||
+39
-21
@@ -62,7 +62,6 @@ 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;
|
||||
@@ -72,6 +71,7 @@ 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;
|
||||
@@ -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 supported by all other devices on the account")
|
||||
@ApiResponse(responseCode = "409", description = "The new device is missing a capability required for 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,7 +232,6 @@ 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);
|
||||
@@ -242,15 +241,31 @@ public class DeviceController {
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
final boolean allKeysValid =
|
||||
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");
|
||||
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());
|
||||
|
||||
if (!allKeysValid) {
|
||||
throw new WebApplicationException(Response.status(422).build());
|
||||
@@ -279,25 +294,28 @@ public class DeviceController {
|
||||
}
|
||||
|
||||
try {
|
||||
final Pair<Account, Device> accountAndDevice = accounts.addDevice(account.getIdentifier(IdentityType.ACI),
|
||||
final Pair<Account, Device> accountAndDevice = accounts.addDevice(account.getAccountIdentifier(),
|
||||
new DeviceSpec(deviceAttributes.name(),
|
||||
authorizationHeader.getPassword(),
|
||||
signalAgent,
|
||||
capabilities,
|
||||
deviceAttributes.registrationId(),
|
||||
deviceAttributes.phoneNumberIdentityRegistrationId(),
|
||||
new DeviceIdentityInfo(
|
||||
deviceAttributes.registrationId(),
|
||||
deviceActivationRequest.aciSignedPreKey(),
|
||||
deviceActivationRequest.aciPqLastResortPreKey()),
|
||||
account.getPhoneNumberIdentityKey().map(_ ->
|
||||
new DeviceIdentityInfo(
|
||||
deviceAttributes.phoneNumberIdentityRegistrationId(),
|
||||
deviceActivationRequest.pniSignedPreKey().get(),
|
||||
deviceActivationRequest.pniPqLastResortPreKey().get())),
|
||||
deviceAttributes.fetchesMessages(),
|
||||
deviceActivationRequest.apnToken(),
|
||||
deviceActivationRequest.gcmToken(),
|
||||
deviceActivationRequest.aciSignedPreKey(),
|
||||
deviceActivationRequest.pniSignedPreKey(),
|
||||
deviceActivationRequest.aciPqLastResortPreKey(),
|
||||
deviceActivationRequest.pniPqLastResortPreKey()),
|
||||
deviceActivationRequest.gcmToken()),
|
||||
linkDeviceRequest.verificationCode());
|
||||
|
||||
return new LinkDeviceResponse(
|
||||
accountAndDevice.first().getIdentifier(IdentityType.ACI),
|
||||
accountAndDevice.first().getIdentifier(IdentityType.PNI),
|
||||
accountAndDevice.first().getAccountIdentifier(),
|
||||
accountAndDevice.first().getPhoneNumberIdentifier(),
|
||||
accountAndDevice.second().getId());
|
||||
} catch (final LinkDeviceTokenAlreadyUsedException e) {
|
||||
throw new ForbiddenException();
|
||||
|
||||
+1
-1
@@ -130,7 +130,7 @@ public class DonationController {
|
||||
}
|
||||
|
||||
final boolean receiptMatched = redeemedReceiptsManager.put(
|
||||
receiptSerial, receiptExpiration.getEpochSecond(), receiptLevel, auth.accountIdentifier());
|
||||
receiptSerial, receiptExpiration, receiptLevel, auth.accountIdentifier());
|
||||
if (!receiptMatched) {
|
||||
return Response.status(Status.BAD_REQUEST)
|
||||
.entity("receipt serial is already redeemed")
|
||||
|
||||
+27
-8
@@ -159,7 +159,7 @@ public class KeysController {
|
||||
|
||||
final UUID identifier = getIdentifier(account, identityType);
|
||||
|
||||
checkSignedPreKeySignatures(setKeysRequest, account.getIdentityKey(identityType), userAgent);
|
||||
checkSignedPreKeySignatures(setKeysRequest, getIdentityKey(account, identityType), userAgent);
|
||||
|
||||
final Tag platformTag = UserAgentTagUtil.getPlatformTag(userAgent);
|
||||
final Tag primaryDeviceTag = Tag.of(PRIMARY_DEVICE_TAG_NAME, String.valueOf(auth.deviceId() == Device.PRIMARY_ID));
|
||||
@@ -279,7 +279,7 @@ public class KeysController {
|
||||
final boolean digestsMatch;
|
||||
|
||||
if (maybeSignedPreKey.isPresent() && maybeLastResortKey.isPresent()) {
|
||||
final IdentityKey identityKey = account.getIdentityKey(checkKeysRequest.identityType());
|
||||
final IdentityKey identityKey = getIdentityKey(account, checkKeysRequest.identityType());
|
||||
final ECSignedPreKey ecSignedPreKey = maybeSignedPreKey.get();
|
||||
final KEMSignedPreKey lastResortKey = maybeLastResortKey.get();
|
||||
|
||||
@@ -384,7 +384,12 @@ public class KeysController {
|
||||
.fromCompletionStage(keysManager.takeDevicePreKeys(device.getId(), targetIdentifier, userAgent))
|
||||
.flatMap(Mono::justOrEmpty)
|
||||
.map(devicePreKeys -> new PreKeyResponseItem(
|
||||
device.getId(), device.getRegistrationId(targetIdentifier.identityType()),
|
||||
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"));
|
||||
},
|
||||
devicePreKeys.ecSignedPreKey(),
|
||||
devicePreKeys.ecPreKey().orElse(null),
|
||||
devicePreKeys.kemSignedPreKey())))
|
||||
@@ -392,7 +397,11 @@ public class KeysController {
|
||||
.blockOptional()
|
||||
.orElseGet(Collections::emptyList);
|
||||
|
||||
final IdentityKey identityKey = target.getIdentityKey(targetIdentifier.identityType());
|
||||
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"));
|
||||
};
|
||||
|
||||
if (responseItems.isEmpty()) {
|
||||
throw new WebApplicationException(Response.Status.NOT_FOUND);
|
||||
@@ -428,7 +437,10 @@ public class KeysController {
|
||||
final Optional<Byte> parsedTargetDeviceId = parseDeviceId(targetDeviceId);
|
||||
final Optional<Integer> targetRegistrationId = parsedTargetDeviceId
|
||||
.flatMap(targetAccount::getDevice)
|
||||
.map(device -> device.getRegistrationId(targetIdentifier.identityType()));
|
||||
.flatMap(device -> switch (targetIdentifier.identityType()) {
|
||||
case ACI -> Optional.of(device.getAccountRegistrationId());
|
||||
case PNI -> device.getPhoneNumberIdentityRegistrationId();
|
||||
});
|
||||
return RateLimitKeys.preKeyLimiterKey(
|
||||
account.getAccountIdentifier(),
|
||||
authenticatedDevice.deviceId(),
|
||||
@@ -438,12 +450,19 @@ public class KeysController {
|
||||
|
||||
/// Get the identity of the requested `idenityType`, or throw a [BadRequestException] if `account` does not contain
|
||||
/// that type.
|
||||
private UUID getIdentifier(final Account account, final IdentityType identityType) {
|
||||
private static UUID getIdentifier(final Account account, final IdentityType identityType) {
|
||||
return switch (identityType) {
|
||||
case ACI -> account.getAccountIdentifier();
|
||||
case PNI -> account.getPhoneNumberIdentifierOptional().orElseThrow(() ->
|
||||
new BadRequestException("Cannot set PNI identity keys on an account without a number"));
|
||||
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"));
|
||||
};
|
||||
}
|
||||
}
|
||||
+7
@@ -73,6 +73,13 @@ public class LoginPurchaseController {
|
||||
|
||||
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)))
|
||||
|
||||
+4
-4
@@ -605,7 +605,7 @@ public class MessageController {
|
||||
|
||||
CompletableFuture.allOf(resolvedRecipients.values()
|
||||
.stream()
|
||||
.map(account -> account.getIdentifier(IdentityType.ACI))
|
||||
.map(account -> account.getAccountIdentifier())
|
||||
.map(accountIdentifier ->
|
||||
rateLimiters.getStoriesLimiter().validateAsync(accountIdentifier).toCompletableFuture())
|
||||
.toList()
|
||||
@@ -746,7 +746,7 @@ public class MessageController {
|
||||
final Optional<Account> maybeAccount = accountsManager.getByE164(source);
|
||||
if (maybeAccount.isPresent()) {
|
||||
sourceAci = maybeAccount.map(Account::getAccountIdentifier);
|
||||
sourcePni = maybeAccount.flatMap(Account::getPhoneNumberIdentifierOptional);
|
||||
sourcePni = maybeAccount.flatMap(Account::getPhoneNumberIdentifier);
|
||||
} else {
|
||||
sourcePni = Optional.ofNullable(phoneNumberIdentifiers.getPhoneNumberIdentifier(source).join());
|
||||
sourceAci = sourcePni.flatMap(accountsManager::findRecentlyDeletedAccountIdentifier);
|
||||
@@ -764,8 +764,8 @@ public class MessageController {
|
||||
Util.getCanonicalNumber(phoneNumberIdentifiers.getPhoneNumber(pni).join()));
|
||||
sourceAccountDeleted = true;
|
||||
} else {
|
||||
sourceNumber = sourceAccount.flatMap(Account::getNumberOptional);
|
||||
sourcePni = sourceAccount.flatMap(Account::getPhoneNumberIdentifierOptional);
|
||||
sourceNumber = sourceAccount.flatMap(Account::getNumber);
|
||||
sourcePni = sourceAccount.flatMap(Account::getPhoneNumberIdentifier);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+13
-5
@@ -414,11 +414,17 @@ public class ProfileController {
|
||||
final Optional<Account> maybeAccount = accountsManager.getByServiceIdentifier(identifier);
|
||||
|
||||
maybeAccount.ifPresent(account -> {
|
||||
final IdentityKey identityKey = account.getIdentityKey(identifier.identityType());
|
||||
if (identityKey == null) {
|
||||
final Optional<IdentityKey> maybeIdentityKey = switch (identifier.identityType()) {
|
||||
case ACI -> Optional.of(account.getAccountIdentityKey());
|
||||
case PNI -> account.getPhoneNumberIdentityKey();
|
||||
};
|
||||
|
||||
if (maybeIdentityKey.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
|
||||
final IdentityKey identityKey = maybeIdentityKey.get();
|
||||
|
||||
md.reset();
|
||||
byte[] digest = md.digest(identityKey.serialize());
|
||||
byte[] fingerprint = Util.truncate(digest, 4);
|
||||
@@ -503,7 +509,7 @@ public class ProfileController {
|
||||
final boolean isSelf,
|
||||
final ContainerRequestContext containerRequestContext) {
|
||||
|
||||
return new BaseProfileResponse(account.getIdentityKey(IdentityType.ACI),
|
||||
return new BaseProfileResponse(account.getAccountIdentityKey(),
|
||||
account.getUnidentifiedAccessKey().map(UnidentifiedAccessChecksum::generateFor).orElse(null),
|
||||
account.isUnrestrictedUnidentifiedAccess(),
|
||||
getAccountCapabilities(account),
|
||||
@@ -515,12 +521,14 @@ public class ProfileController {
|
||||
}
|
||||
|
||||
private BaseProfileResponse buildBaseProfileResponseForPhoneNumberIdentity(final Account account) {
|
||||
return new BaseProfileResponse(account.getIdentityKey(IdentityType.PNI),
|
||||
return new BaseProfileResponse(account.getPhoneNumberIdentityKey()
|
||||
.orElseThrow(() -> new IllegalStateException("Account retrieved by PNI does not have PNI identity key")),
|
||||
null,
|
||||
false,
|
||||
getAccountCapabilities(account),
|
||||
Collections.emptyList(),
|
||||
new PniServiceIdentifier(account.getPhoneNumberIdentifier()));
|
||||
new PniServiceIdentifier(account.getPhoneNumberIdentifier()
|
||||
.orElseThrow(() -> new IllegalStateException("Account retrieved by PNI does not have PNI"))));
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
+293
-15
@@ -13,6 +13,8 @@ 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;
|
||||
@@ -34,12 +36,19 @@ 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;
|
||||
@@ -49,6 +58,7 @@ 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;
|
||||
@@ -61,7 +71,13 @@ 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;
|
||||
|
||||
@@ -84,6 +100,10 @@ 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);
|
||||
|
||||
@@ -91,13 +111,21 @@ public class RegistrationController {
|
||||
final PhoneVerificationTokenManager phoneVerificationTokenManager,
|
||||
final RegistrationLockVerificationManager registrationLockVerificationManager,
|
||||
final RateLimiters rateLimiters,
|
||||
final RegistrationFraudChecker registrationFraudChecker) {
|
||||
final RegistrationFraudChecker registrationFraudChecker,
|
||||
final ReceiptCredentialPresentationFactory receiptCredentialPresentationFactory,
|
||||
final ServerZkReceiptOperations serverZkReceiptOperations,
|
||||
final Clock clock,
|
||||
final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager) {
|
||||
|
||||
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
|
||||
@@ -112,6 +140,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")
|
||||
@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")
|
||||
@@ -120,8 +149,23 @@ 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,
|
||||
@@ -129,9 +173,6 @@ 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);
|
||||
}
|
||||
@@ -143,7 +184,47 @@ public class RegistrationController {
|
||||
throw new WebApplicationException("Missing required device capability", 499);
|
||||
}
|
||||
|
||||
rateLimiters.getRegistrationLimiter().validate(number);
|
||||
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);
|
||||
}
|
||||
|
||||
final PhoneVerificationRequest.VerificationType verificationType;
|
||||
try {
|
||||
@@ -164,6 +245,8 @@ 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)
|
||||
@@ -186,15 +269,16 @@ public class RegistrationController {
|
||||
}
|
||||
|
||||
if (existingAccount.isPresent()) {
|
||||
assert existingAccount.get().getNumberOptional().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(
|
||||
@@ -202,15 +286,18 @@ public class RegistrationController {
|
||||
password,
|
||||
signalAgent,
|
||||
registrationRequest.accountAttributes().getCapabilities(),
|
||||
registrationRequest.accountAttributes().getRegistrationId(),
|
||||
registrationRequest.accountAttributes().getPhoneNumberIdentityRegistrationId(),
|
||||
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().getFetchesMessages(),
|
||||
registrationRequest.deviceActivationRequest().apnToken(),
|
||||
registrationRequest.deviceActivationRequest().gcmToken(),
|
||||
registrationRequest.deviceActivationRequest().aciSignedPreKey(),
|
||||
registrationRequest.deviceActivationRequest().pniSignedPreKey(),
|
||||
registrationRequest.deviceActivationRequest().aciPqLastResortPreKey(),
|
||||
registrationRequest.deviceActivationRequest().pniPqLastResortPreKey()),
|
||||
registrationRequest.deviceActivationRequest().gcmToken()),
|
||||
userAgent);
|
||||
|
||||
if (verificationType == PhoneVerificationRequest.VerificationType.SESSION) {
|
||||
@@ -237,4 +324,195 @@ 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 BadRequestException("Receipt credential presentation verification failed");
|
||||
}
|
||||
|
||||
final Instant receiptExpiration = Instant.ofEpochSecond(receiptCredentialPresentation.getReceiptExpirationTime());
|
||||
if (clock.instant().isAfter(receiptExpiration)) {
|
||||
throw new BadRequestException("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 BadRequestException("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);
|
||||
}
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -666,7 +666,7 @@ public class VerificationController {
|
||||
|
||||
accountsManager.getByE164(registrationServiceSession.number())
|
||||
.filter(existingAccount ->
|
||||
experimentEnrollmentManager.isEnrolled(existingAccount.getIdentifier(IdentityType.ACI), VERIFICATION_CODE_PUSH_NOTIFICATION_EXPERIMENT_NAME))
|
||||
experimentEnrollmentManager.isEnrolled(existingAccount.getAccountIdentifier(), VERIFICATION_CODE_PUSH_NOTIFICATION_EXPERIMENT_NAME))
|
||||
.ifPresent(existingAccount -> {
|
||||
try {
|
||||
pushNotificationManager.sendVerificationCodeRequestedNotifications(existingAccount, clock.instant());
|
||||
|
||||
+13
-5
@@ -14,6 +14,7 @@ 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;
|
||||
@@ -52,15 +53,17 @@ public class AccountAttributes {
|
||||
public AccountAttributes(
|
||||
final boolean fetchesMessages,
|
||||
final int registrationId,
|
||||
final int phoneNumberIdentifierRegistrationId,
|
||||
final Integer phoneNumberIdentifierRegistrationId,
|
||||
final byte[] name,
|
||||
final String registrationLock,
|
||||
final boolean discoverableByPhoneNumber,
|
||||
final Set<DeviceCapability> capabilities) {
|
||||
final Set<DeviceCapability> capabilities,
|
||||
@Nullable final byte[] recoveryPassword) {
|
||||
|
||||
this.deviceAttributes = new DeviceAttributes(fetchesMessages, registrationId, phoneNumberIdentifierRegistrationId, name, capabilities);
|
||||
this.registrationLock = registrationLock;
|
||||
this.discoverableByPhoneNumber = discoverableByPhoneNumber;
|
||||
this.recoveryPassword = recoveryPassword;
|
||||
}
|
||||
|
||||
public boolean getFetchesMessages() {
|
||||
@@ -71,8 +74,8 @@ public class AccountAttributes {
|
||||
return deviceAttributes.registrationId();
|
||||
}
|
||||
|
||||
public int getPhoneNumberIdentityRegistrationId() {
|
||||
return deviceAttributes.phoneNumberIdentityRegistrationId();
|
||||
public Optional<Integer> getPhoneNumberIdentityRegistrationId() {
|
||||
return Optional.ofNullable(deviceAttributes.phoneNumberIdentityRegistrationId());
|
||||
}
|
||||
|
||||
public byte[] getName() {
|
||||
@@ -101,7 +104,7 @@ public class AccountAttributes {
|
||||
}
|
||||
|
||||
public Optional<byte[]> recoveryPassword() {
|
||||
return Optional.ofNullable(recoveryPassword);
|
||||
return Optional.ofNullable(recoveryPassword).filter(ArrayUtils::isNotEmpty);
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
@@ -128,6 +131,11 @@ public class AccountAttributes {
|
||||
return this;
|
||||
}
|
||||
|
||||
public AccountAttributes setDiscoverableByPhoneNumber(final boolean discoverableByPhoneNumber) {
|
||||
this.discoverableByPhoneNumber = discoverableByPhoneNumber;
|
||||
return this;
|
||||
}
|
||||
|
||||
@AssertTrue
|
||||
@Schema(hidden = true)
|
||||
public boolean isUnrestrictedUakValid() {
|
||||
|
||||
+4
-1
@@ -35,5 +35,8 @@ public record AccountIdentityResponse(
|
||||
boolean storageCapable,
|
||||
|
||||
@Schema(description = "entitlements for this account and their current expirations")
|
||||
Entitlements entitlements) {
|
||||
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) {
|
||||
}
|
||||
+6
-12
@@ -1,10 +1,8 @@
|
||||
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(
|
||||
@@ -15,12 +13,10 @@ public record DeviceActivationRequest(
|
||||
""")
|
||||
ECSignedPreKey aciSignedPreKey,
|
||||
|
||||
@NotNull
|
||||
@Valid
|
||||
@Schema(requiredMode = Schema.RequiredMode.REQUIRED, description = """
|
||||
A signed EC pre-key to be associated with this account's PNI.
|
||||
@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.
|
||||
""")
|
||||
ECSignedPreKey pniSignedPreKey,
|
||||
Optional<@Valid ECSignedPreKey> pniSignedPreKey,
|
||||
|
||||
@NotNull
|
||||
@Valid
|
||||
@@ -29,12 +25,10 @@ public record DeviceActivationRequest(
|
||||
""")
|
||||
KEMSignedPreKey aciPqLastResortPreKey,
|
||||
|
||||
@NotNull
|
||||
@Valid
|
||||
@Schema(requiredMode = Schema.RequiredMode.REQUIRED, description = """
|
||||
A signed Kyber-1024 "last resort" pre-key to be associated with this account's PNI.
|
||||
@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.
|
||||
""")
|
||||
KEMSignedPreKey pniPqLastResortPreKey,
|
||||
Optional<@Valid 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
|
||||
|
||||
+6
-4
@@ -13,6 +13,7 @@ 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;
|
||||
@@ -24,16 +25,16 @@ public record DeviceAttributes(
|
||||
|
||||
int registrationId,
|
||||
|
||||
@JsonProperty("pniRegistrationId") int phoneNumberIdentityRegistrationId,
|
||||
@JsonProperty("pniRegistrationId")
|
||||
@Nullable
|
||||
Integer 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) {
|
||||
@@ -41,6 +42,7 @@ public record DeviceAttributes(
|
||||
@AssertTrue
|
||||
@Schema(hidden = true)
|
||||
public boolean isEachRegistrationIdValid() {
|
||||
return validRegistrationId(registrationId) && validRegistrationId(phoneNumberIdentityRegistrationId);
|
||||
return validRegistrationId(registrationId) &&
|
||||
(phoneNumberIdentityRegistrationId == null || validRegistrationId(phoneNumberIdentityRegistrationId));
|
||||
}
|
||||
}
|
||||
@@ -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 org.whispersystems.textsecuregcm.identity.IdentityType;
|
||||
import org.whispersystems.textsecuregcm.storage.Device;
|
||||
import org.whispersystems.textsecuregcm.util.ByteArrayAdapter;
|
||||
import org.whispersystems.textsecuregcm.util.ByteArrayBase64WithPaddingAdapter;
|
||||
@@ -33,7 +32,10 @@ public record DeviceInfo(long id,
|
||||
byte[] createdAtCiphertext) {
|
||||
|
||||
public static DeviceInfo forDevice(final Device device) {
|
||||
return new DeviceInfo(device.getId(), device.getName(), device.getLastSeen(), device.getRegistrationId(
|
||||
IdentityType.ACI), device.getCreatedAtCiphertext());
|
||||
return new DeviceInfo(device.getId(),
|
||||
device.getName(),
|
||||
device.getLastSeen(),
|
||||
device.getAccountRegistrationId(),
|
||||
device.getCreatedAtCiphertext());
|
||||
}
|
||||
}
|
||||
+2
-2
@@ -6,7 +6,6 @@ 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;
|
||||
@@ -19,12 +18,13 @@ 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 = ByteArrayBase64Deserializer.class)
|
||||
@JsonDeserialize(using = ByteArrayAdapter.Deserializing.class)
|
||||
@NotNull
|
||||
// Note that max size is validated elsewhere in the interest of controlling responses and
|
||||
// reporting additional metrics.
|
||||
|
||||
+2
-2
@@ -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") @NotNull @Valid ECSignedPreKey pniSignedPreKey,
|
||||
@JsonProperty("pniSignedPreKey") Optional<@Valid ECSignedPreKey> pniSignedPreKey,
|
||||
@JsonProperty("aciPqLastResortPreKey") @NotNull @Valid KEMSignedPreKey aciPqLastResortPreKey,
|
||||
@JsonProperty("pniPqLastResortPreKey") @NotNull @Valid KEMSignedPreKey pniPqLastResortPreKey,
|
||||
@JsonProperty("pniPqLastResortPreKey") Optional<@Valid KEMSignedPreKey> pniPqLastResortPreKey,
|
||||
@JsonProperty("apnToken") Optional<@Valid ApnRegistrationId> apnToken,
|
||||
@JsonProperty("gcmToken") Optional<@Valid GcmRegistrationId> gcmToken) {
|
||||
|
||||
|
||||
+2
-1
@@ -5,7 +5,8 @@
|
||||
|
||||
package org.whispersystems.textsecuregcm.entities;
|
||||
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
|
||||
public record LinkDeviceResponse(UUID uuid, UUID pni, byte deviceId) {
|
||||
public record LinkDeviceResponse(UUID uuid, Optional<UUID> pni, byte deviceId) {
|
||||
}
|
||||
+26
-5
@@ -10,31 +10,52 @@ 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
|
||||
RECOVERY_PASSWORD,
|
||||
RECEIPT_CREDENTIAL
|
||||
}
|
||||
|
||||
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() {
|
||||
// checking that exactly one of sessionId/recoveryPassword is non-empty
|
||||
return isNotBlank(sessionId()) ^ (recoveryPassword() != null && recoveryPassword().length > 0);
|
||||
// exactly one of sessionId/recoveryPassword/receiptCredentialPresentation should be present
|
||||
return presentVerificationTypes().size() == 1;
|
||||
}
|
||||
|
||||
default PhoneVerificationRequest.VerificationType verificationType() {
|
||||
return isNotBlank(sessionId()) ? PhoneVerificationRequest.VerificationType.SESSION
|
||||
: PhoneVerificationRequest.VerificationType.RECOVERY_PASSWORD;
|
||||
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;
|
||||
}
|
||||
|
||||
default byte[] decodeSessionId() {
|
||||
|
||||
-1
@@ -22,7 +22,6 @@ 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) {
|
||||
|
||||
+54
-10
@@ -15,25 +15,48 @@ 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.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` is not provided; must not be
|
||||
provided if `recoveryPassword` is provided.
|
||||
metadata object. Must be provided if `recoveryPassword` and `receiptCredentialPresentation`
|
||||
are not provided; must not be provided if `recoveryPassword` or `receiptCredentialPresentation`
|
||||
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` is
|
||||
not provided; must not be provided if `sessionId` is provided
|
||||
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.
|
||||
""")
|
||||
@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.
|
||||
""")
|
||||
@Nullable
|
||||
byte[] receiptCredentialPresentation,
|
||||
|
||||
@Schema(requiredMode = Schema.RequiredMode.NOT_REQUIRED, description = """
|
||||
A TOTP one-time password; required if recovering an account that has TOTP keys.
|
||||
""")
|
||||
@PositiveOrZero
|
||||
@Nullable
|
||||
Integer totp,
|
||||
|
||||
@NotNull
|
||||
@Valid
|
||||
@Schema(requiredMode = Schema.RequiredMode.REQUIRED)
|
||||
@@ -58,13 +81,17 @@ public record RegistrationRequest(@Schema(requiredMode = Schema.RequiredMode.NOT
|
||||
@JsonDeserialize(using = IdentityKeyAdapter.Deserializer.class)
|
||||
IdentityKey aciIdentityKey,
|
||||
|
||||
@NotNull
|
||||
@Valid
|
||||
@Schema(requiredMode = Schema.RequiredMode.REQUIRED, description = """
|
||||
@Schema(requiredMode = Schema.RequiredMode.NOT_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
|
||||
@@ -75,14 +102,18 @@ public record RegistrationRequest(@Schema(requiredMode = Schema.RequiredMode.NOT
|
||||
|
||||
public boolean isEverySignedKeyValid(@Nullable final String userAgent) {
|
||||
if (deviceActivationRequest().aciSignedPreKey() == null ||
|
||||
deviceActivationRequest().pniSignedPreKey() == null ||
|
||||
deviceActivationRequest().aciPqLastResortPreKey() == null ||
|
||||
deviceActivationRequest().pniPqLastResortPreKey() == null) {
|
||||
deviceActivationRequest().aciPqLastResortPreKey() == null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
final boolean allPniPresentOrAllAbsent = ((pniIdentityKey == null) == deviceActivationRequest().pniSignedPreKey().isEmpty())
|
||||
&& ((pniIdentityKey == null) == deviceActivationRequest().pniPqLastResortPreKey().isEmpty());
|
||||
if (!allPniPresentOrAllAbsent) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return PreKeySignatureValidator.validatePreKeySignatures(aciIdentityKey(), List.of(deviceActivationRequest().aciSignedPreKey(), deviceActivationRequest().aciPqLastResortPreKey()), userAgent, "register")
|
||||
&& PreKeySignatureValidator.validatePreKeySignatures(pniIdentityKey(), List.of(deviceActivationRequest().pniSignedPreKey(), deviceActivationRequest().pniPqLastResortPreKey()), userAgent, "register");
|
||||
&& (pniIdentityKey == null || PreKeySignatureValidator.validatePreKeySignatures(pniIdentityKey(), List.of(deviceActivationRequest().pniSignedPreKey().get(), deviceActivationRequest().pniPqLastResortPreKey().get()), userAgent, "register"));
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
@@ -98,4 +129,17 @@ 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);
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -65,7 +65,7 @@ abstract class IdleDevicePushNotificationExperiment implements PushNotificationE
|
||||
} else {
|
||||
pushTokenType = null;
|
||||
}
|
||||
return new DeviceLastSeenState(true, device.getRegistrationId(IdentityType.ACI), hasPushToken(device), device.getLastSeen(), pushTokenType);
|
||||
return new DeviceLastSeenState(true, device.getAccountRegistrationId(), hasPushToken(device), device.getLastSeen(), pushTokenType);
|
||||
} else {
|
||||
return DeviceLastSeenState.MISSING_DEVICE_STATE;
|
||||
}
|
||||
|
||||
+144
-6
@@ -14,10 +14,12 @@ 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;
|
||||
import java.util.Objects;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import java.util.function.Function;
|
||||
import java.util.stream.Collectors;
|
||||
@@ -28,6 +30,8 @@ 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;
|
||||
@@ -37,6 +41,8 @@ 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;
|
||||
@@ -45,7 +51,11 @@ 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.ListTotpKeysRequest;
|
||||
import org.signal.chat.account.ListTotpKeysResponse;
|
||||
import org.signal.chat.account.RegistrationLockFailure;
|
||||
import org.signal.chat.account.RemoveTotpKeyRequest;
|
||||
import org.signal.chat.account.RemoveTotpKeyResponse;
|
||||
import org.signal.chat.account.ReserveUsernameHashRequest;
|
||||
import org.signal.chat.account.ReserveUsernameHashResponse;
|
||||
import org.signal.chat.account.SetDiscoverableByPhoneNumberRequest;
|
||||
@@ -54,15 +64,19 @@ 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.SetTotpKeyMetadataRequest;
|
||||
import org.signal.chat.account.SetTotpKeyMetadataResponse;
|
||||
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;
|
||||
import org.signal.chat.errors.NotFound;
|
||||
import org.signal.chat.messages.SendMessageType;
|
||||
import org.signal.libsignal.protocol.IdentityKey;
|
||||
import org.signal.libsignal.protocol.InvalidKeyException;
|
||||
@@ -90,16 +104,21 @@ 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.AnnotatedTotpKey;
|
||||
import org.whispersystems.textsecuregcm.storage.ChangeNumberManager;
|
||||
import org.whispersystems.textsecuregcm.storage.DeviceCapability;
|
||||
import org.whispersystems.textsecuregcm.storage.PhoneNumberRecoveryPasswordsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.TooManyTotpKeysException;
|
||||
import org.whispersystems.textsecuregcm.storage.TotpKey;
|
||||
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 {
|
||||
|
||||
@@ -112,6 +131,9 @@ public class AccountsGrpcService extends SimpleAccountsGrpc.AccountsImplBase {
|
||||
private final Clock clock;
|
||||
private final ChangeNumberManager changeNumberManager;
|
||||
|
||||
private static class TotpKeyNotFoundException extends NoStackTraceRuntimeException {
|
||||
}
|
||||
|
||||
public AccountsGrpcService(final AccountsManager accountsManager,
|
||||
final RateLimiters rateLimiters,
|
||||
final UsernameHashZkProofVerifier usernameHashZkProofVerifier,
|
||||
@@ -316,7 +338,13 @@ public class AccountsGrpcService extends SimpleAccountsGrpc.AccountsImplBase {
|
||||
@Override
|
||||
public SetDiscoverableByPhoneNumberResponse setDiscoverableByPhoneNumber(final SetDiscoverableByPhoneNumberRequest request) {
|
||||
accountsManager.update(AuthenticationUtil.requireAuthenticatedDevice().accountIdentifier(),
|
||||
account -> account.setDiscoverableByPhoneNumber(request.getDiscoverableByPhoneNumber()));
|
||||
account -> {
|
||||
if (account.getNumber().isEmpty()) {
|
||||
throw GrpcExceptions.invalidArguments("account does not have a phone number");
|
||||
}
|
||||
|
||||
account.setDiscoverableByPhoneNumber(request.getDiscoverableByPhoneNumber());
|
||||
});
|
||||
|
||||
return SetDiscoverableByPhoneNumberResponse.getDefaultInstance();
|
||||
}
|
||||
@@ -326,7 +354,7 @@ public class AccountsGrpcService extends SimpleAccountsGrpc.AccountsImplBase {
|
||||
final Account account = getAuthenticatedAccount();
|
||||
final byte[] recoveryPassword = request.getRegistrationRecoveryPassword().toByteArray();
|
||||
|
||||
final Collection<TransactWriteItem> additionalWriteItems = account.getPhoneNumberIdentifierOptional()
|
||||
final Collection<TransactWriteItem> additionalWriteItems = account.getPhoneNumberIdentifier()
|
||||
.map(phoneNumberIdentifier ->
|
||||
List.of(phoneNumberRecoveryPasswordsManager.buildTransactWriteItemForStorePassword(phoneNumberIdentifier, recoveryPassword)))
|
||||
.orElseGet(Collections::emptyList);
|
||||
@@ -499,7 +527,7 @@ public class AccountsGrpcService extends SimpleAccountsGrpc.AccountsImplBase {
|
||||
final AccountDataReportResponse report = new AccountDataReportResponse(UUID.randomUUID(), clock.instant(),
|
||||
new AccountDataReportResponse.AccountAndDevicesDataReport(
|
||||
new AccountDataReportResponse.AccountDataReport(
|
||||
account.getNumberOptional(),
|
||||
account.getNumber(),
|
||||
account.getBadges().stream().map(AccountDataReportResponse.BadgeDataReport::new).toList(),
|
||||
account.isUnrestrictedUnidentifiedAccess(),
|
||||
account.isDiscoverableByPhoneNumber()),
|
||||
@@ -528,15 +556,125 @@ public class AccountsGrpcService extends SimpleAccountsGrpc.AccountsImplBase {
|
||||
return GetCapabilitiesResponse.newBuilder().setCapabilities(builder.build()).build();
|
||||
}
|
||||
|
||||
@Override
|
||||
public GenerateTotpKeyResponse generateTotpKey(final GenerateTotpKeyRequest request) {
|
||||
try {
|
||||
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 e) {
|
||||
return GenerateTotpKeyResponse.newBuilder()
|
||||
.setTooManyTotpKeys(FailedPrecondition.getDefaultInstance())
|
||||
.build();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public ConfirmTotpKeyResponse confirmTotpKey(final ConfirmTotpKeyRequest request) {
|
||||
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());
|
||||
}
|
||||
|
||||
@Override
|
||||
public ListTotpKeysResponse listTotpKeys(final ListTotpKeysRequest request) {
|
||||
final ListTotpKeysResponse.Builder responseBuilder = ListTotpKeysResponse.newBuilder();
|
||||
|
||||
getAuthenticatedAccount().getTotpKeys().forEach((keyId, totpKey) -> {
|
||||
assert totpKey.metadataCiphertext() != null;
|
||||
|
||||
responseBuilder.putKeys(keyId, ListTotpKeysResponse.TotpKeyMetadata.newBuilder()
|
||||
.setMetadataCiphertext(ByteString.copyFrom(totpKey.metadataCiphertext()))
|
||||
.setTotpParameters(toGrpcTotpParameters(totpKey.totpKey().totpParameters()))
|
||||
.build());
|
||||
});
|
||||
|
||||
return responseBuilder.build();
|
||||
}
|
||||
|
||||
@Override
|
||||
public SetTotpKeyMetadataResponse setTotpKeyMetadata(final SetTotpKeyMetadataRequest request) {
|
||||
final byte keyId = validateTotpKeyId(request.getKeyId());
|
||||
|
||||
try {
|
||||
accountsManager.update(AuthenticationUtil.requireAuthenticatedDevice().accountIdentifier(), account -> {
|
||||
final Map<Byte, AnnotatedTotpKey> totpKeys = new HashMap<>(account.getTotpKeys());
|
||||
@Nullable final AnnotatedTotpKey existingKey = totpKeys.get(keyId);
|
||||
|
||||
if (existingKey == null) {
|
||||
throw new TotpKeyNotFoundException();
|
||||
}
|
||||
|
||||
totpKeys.put(keyId, new AnnotatedTotpKey(existingKey.totpKey(), request.getMetadataCiphertext().toByteArray()));
|
||||
|
||||
account.setTotpKeys(totpKeys);
|
||||
});
|
||||
|
||||
return SetTotpKeyMetadataResponse.newBuilder()
|
||||
.setMetadataUpdated(SetTotpKeyMetadataResponse.MetadataUpdated.getDefaultInstance())
|
||||
.build();
|
||||
} catch (final TotpKeyNotFoundException _) {
|
||||
return SetTotpKeyMetadataResponse.newBuilder()
|
||||
.setKeyNotFound(NotFound.getDefaultInstance())
|
||||
.build();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public RemoveTotpKeyResponse removeTotpKey(final RemoveTotpKeyRequest request) {
|
||||
final byte keyId = validateTotpKeyId(request.getKeyId());
|
||||
|
||||
accountsManager.update(AuthenticationUtil.requireAuthenticatedDevice().accountIdentifier(), account -> {
|
||||
final Map<Byte, AnnotatedTotpKey> totpKeys = new HashMap<>(account.getTotpKeys());
|
||||
totpKeys.remove(keyId);
|
||||
|
||||
account.setTotpKeys(totpKeys);
|
||||
});
|
||||
|
||||
return RemoveTotpKeyResponse.getDefaultInstance();
|
||||
}
|
||||
|
||||
private byte validateTotpKeyId(final int keyId) {
|
||||
if (keyId < 0 || keyId > Account.MAX_TOTP_KEY_ID) {
|
||||
throw GrpcExceptions.invalidArguments("TOTP 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.getPhoneNumberIdentifierOptional()
|
||||
account.getPhoneNumberIdentifier()
|
||||
.map(phoneNumberIdentifier -> GrpcServiceIdentifierUtil.toGrpcServiceIdentifier(new PniServiceIdentifier(phoneNumberIdentifier)))
|
||||
.ifPresent(accountIdentifiersBuilder::addServiceIdentifiers);
|
||||
|
||||
account.getNumberOptional().ifPresent(accountIdentifiersBuilder::setE164);
|
||||
account.getNumber().ifPresent(accountIdentifiersBuilder::setE164);
|
||||
|
||||
account.getUsernameHash().ifPresent(usernameHash ->
|
||||
accountIdentifiersBuilder.setUsernameHash(ByteString.copyFrom(usernameHash)));
|
||||
@@ -578,7 +716,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) {
|
||||
|
||||
+2
-2
@@ -98,7 +98,7 @@ public class CredentialsGrpcService extends SimpleCredentialsGrpc.CredentialsImp
|
||||
.setCertificateWithoutE164(ByteString.copyFrom(
|
||||
certificateGenerator.createFor(account, authenticatedDevice.deviceId(), false)));
|
||||
|
||||
if (account.getNumberOptional().isPresent()) {
|
||||
if (account.getNumber().isPresent()) {
|
||||
responseBuilder.setCertificateWithE164(ByteString.copyFrom(
|
||||
certificateGenerator.createFor(account, authenticatedDevice.deviceId(), true)));
|
||||
}
|
||||
@@ -123,7 +123,7 @@ public class CredentialsGrpcService extends SimpleCredentialsGrpc.CredentialsImp
|
||||
.orElseThrow(() -> GrpcExceptions.invalidCredentials("invalid credentials"));
|
||||
|
||||
final ServiceId.Aci aci = new ServiceId.Aci(account.getAccountIdentifier());
|
||||
final Optional<ServiceId.Pni> maybePni = account.getPhoneNumberIdentifierOptional().map(ServiceId.Pni::new);
|
||||
final Optional<ServiceId.Pni> maybePni = account.getPhoneNumberIdentifier().map(ServiceId.Pni::new);
|
||||
|
||||
final GetGroupCredentialsResponse.Builder responseBuilder = GetGroupCredentialsResponse.newBuilder();
|
||||
|
||||
|
||||
@@ -20,6 +20,7 @@ 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");
|
||||
};
|
||||
@@ -33,6 +34,7 @@ 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.getRegistrationId(IdentityType.ACI))
|
||||
.setRegistrationId(device.getAccountRegistrationId())
|
||||
.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.getIdentifier(IdentityType.ACI), deviceId, device -> device.setName(request.getName().toByteArray()));
|
||||
accountsManager.updateDevice(account.getAccountIdentifier(), 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.getIdentifier(IdentityType.ACI), authenticatedDevice.deviceId(), d -> {
|
||||
accountsManager.updateDevice(account.getAccountIdentifier(), authenticatedDevice.deviceId(), d -> {
|
||||
d.setApnId(apnsToken);
|
||||
d.setGcmId(fcmToken);
|
||||
d.setFetchesMessages(false);
|
||||
|
||||
+1
-1
@@ -84,7 +84,7 @@ public class DonationsGrpcService extends SimpleDonationsGrpc.DonationsImplBase
|
||||
throw GrpcExceptions.unavailable("server does not recognize the requested receipt level");
|
||||
}
|
||||
final boolean receiptMatched = redeemedReceiptsManager.put(
|
||||
receiptSerial, receiptExpiration.getEpochSecond(), receiptLevel, authenticatedDevice.accountIdentifier());
|
||||
receiptSerial, receiptExpiration, receiptLevel, authenticatedDevice.accountIdentifier());
|
||||
if (!receiptMatched) {
|
||||
return RedeemReceiptResponse.newBuilder()
|
||||
.setAlreadyRedeemed(FailedPrecondition.newBuilder()
|
||||
|
||||
+2
-2
@@ -62,7 +62,7 @@ public class ErrorMappingInterceptor implements ServerInterceptor {
|
||||
}
|
||||
case IllegalStateException e -> {
|
||||
ImpossibleEvents.logImpossible(log, e.getMessage(), e);
|
||||
yield GrpcExceptions.unavailable(e.getMessage());
|
||||
yield GrpcExceptions.unavailable();
|
||||
}
|
||||
case null -> {
|
||||
log.error("RPC {} finished with status UNKNOWN: {}",
|
||||
@@ -72,7 +72,7 @@ public class ErrorMappingInterceptor implements ServerInterceptor {
|
||||
default -> {
|
||||
log.error("RPC {} finished with status UNKNOWN",
|
||||
call.getMethodDescriptor().getFullMethodName(), status.getCause());
|
||||
yield GrpcExceptions.unavailable(status.getCause().getMessage());
|
||||
yield GrpcExceptions.unavailable();
|
||||
}
|
||||
};
|
||||
super.close(statusException.getStatus(), statusException.getTrailers());
|
||||
|
||||
+2
-1
@@ -18,6 +18,7 @@ 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 {
|
||||
@@ -48,7 +49,7 @@ public enum ExternalServiceDefinitions {
|
||||
.build();
|
||||
}),
|
||||
STORAGE(ExternalServiceType.EXTERNAL_SERVICE_TYPE_STORAGE, (chatConfig, _) -> {
|
||||
final PaymentsServiceConfiguration cfg = chatConfig.getPaymentsServiceConfiguration();
|
||||
final SecureStorageServiceConfiguration cfg = chatConfig.getSecureStorageServiceConfiguration();
|
||||
return ExternalServiceCredentialsGenerator
|
||||
.builder(cfg.userAuthenticationTokenSharedSecret())
|
||||
.prependUsername(true)
|
||||
|
||||
+9
-5
@@ -10,6 +10,7 @@ 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;
|
||||
@@ -94,14 +95,17 @@ 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(account -> !fingerprintMatches(account.getIdentityKey(serviceIdentifierAndFingerprint.getT1()
|
||||
.identityType()), serviceIdentifierAndFingerprint.getT2()))
|
||||
.map(account -> CheckIdentityKeyResponse.newBuilder()
|
||||
.filter(identityKey -> !fingerprintMatches(identityKey, serviceIdentifierAndFingerprint.getT2()))
|
||||
.map(identityKey -> CheckIdentityKeyResponse.newBuilder()
|
||||
.setTargetIdentifier(
|
||||
GrpcServiceIdentifierUtil.toGrpcServiceIdentifier(serviceIdentifierAndFingerprint.getT1()))
|
||||
.setIdentityKey(ByteString.copyFrom(account.getIdentityKey(serviceIdentifierAndFingerprint.getT1()
|
||||
.identityType()).serialize()))
|
||||
.setIdentityKey(ByteString.copyFrom(identityKey.serialize()))
|
||||
.build())));
|
||||
}
|
||||
|
||||
|
||||
@@ -6,13 +6,12 @@
|
||||
package org.whispersystems.textsecuregcm.grpc;
|
||||
|
||||
import com.google.protobuf.ByteString;
|
||||
import java.util.Arrays;
|
||||
import io.grpc.StatusRuntimeException;
|
||||
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;
|
||||
@@ -22,15 +21,14 @@ 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;
|
||||
|
||||
@@ -74,8 +72,14 @@ 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(targetAccount.getIdentityKey(targetServiceIdentifier.identityType()).serialize()))
|
||||
.setIdentityKey(ByteString.copyFrom(identityKey.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.
|
||||
@@ -89,6 +93,11 @@ 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()
|
||||
@@ -99,7 +108,7 @@ class KeysGrpcHelper {
|
||||
.setKeyId(KeyIdUtil.toUnsignedInt(devicePreKeys.kemSignedPreKey().keyId()))
|
||||
.setPublicKey(ByteString.copyFrom(devicePreKeys.kemSignedPreKey().serializedPublicKey()))
|
||||
.setSignature(ByteString.copyFrom(devicePreKeys.kemSignedPreKey().signature())))
|
||||
.setRegistrationId(device.getRegistrationId(targetServiceIdentifier.identityType()));
|
||||
.setRegistrationId(registrationId);
|
||||
|
||||
devicePreKeys.ecPreKey().ifPresent(ecPreKey -> builder.setEcOneTimePreKey(EcPreKey.newBuilder()
|
||||
.setKeyId(KeyIdUtil.toUnsignedInt(ecPreKey.keyId()))
|
||||
|
||||
@@ -65,14 +65,14 @@ public class KeysGrpcService extends SimpleKeysGrpc.KeysImplBase {
|
||||
final CompletableFuture<Integer> aciEcKeyCountFuture =
|
||||
keysManager.getEcCount(aci, authenticatedDevice.deviceId());
|
||||
|
||||
final CompletableFuture<Integer> pniEcKeyCountFuture = account.getPhoneNumberIdentifierOptional()
|
||||
final CompletableFuture<Integer> pniEcKeyCountFuture = account.getPhoneNumberIdentifier()
|
||||
.map(pni -> keysManager.getEcCount(pni, authenticatedDevice.deviceId()))
|
||||
.orElseGet(() -> CompletableFuture.completedFuture(0));
|
||||
|
||||
final CompletableFuture<Integer> aciKemKeyCountFuture =
|
||||
keysManager.getPqCount(aci, authenticatedDevice.deviceId());
|
||||
|
||||
final CompletableFuture<Integer> pniKemKeyCountFuture = account.getPhoneNumberIdentifierOptional()
|
||||
final CompletableFuture<Integer> pniKemKeyCountFuture = account.getPhoneNumberIdentifier()
|
||||
.map(pni -> keysManager.getPqCount(pni, authenticatedDevice.deviceId()))
|
||||
.orElseGet(() -> CompletableFuture.completedFuture(0));
|
||||
|
||||
@@ -103,7 +103,10 @@ public class KeysGrpcService extends SimpleKeysGrpc.KeysImplBase {
|
||||
final Optional<Integer> targetRegistrationId = maybeTargetAccount
|
||||
.filter(_ -> request.hasDeviceId())
|
||||
.flatMap(targetAccount -> targetAccount.getDevice(deviceId))
|
||||
.map(device -> device.getRegistrationId(targetIdentifier.identityType()));
|
||||
.flatMap(device -> switch (targetIdentifier.identityType()) {
|
||||
case ACI -> Optional.of(device.getAccountRegistrationId());
|
||||
case PNI -> device.getPhoneNumberIdentityRegistrationId();
|
||||
});
|
||||
|
||||
final String rateLimitKey = RateLimitKeys.preKeyLimiterKey(
|
||||
authenticatedDevice.accountIdentifier(),
|
||||
@@ -158,10 +161,16 @@ 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, account.getIdentityKey(identityType)))
|
||||
.map(requestPreKey -> extractPreKeyFunction.apply(requestPreKey, identityKey))
|
||||
.toList();
|
||||
|
||||
storeKeysFunction.apply(identifier, preKeys).join();
|
||||
@@ -200,9 +209,13 @@ public class KeysGrpcService extends SimpleKeysGrpc.KeysImplBase {
|
||||
final BiFunction<UUID, 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(identityType);
|
||||
final K key = extractKeyFunction.apply(storeKeyRequest, identityKey);
|
||||
|
||||
storeKeyFunction.apply(identifier, key).join();
|
||||
@@ -218,7 +231,7 @@ public class KeysGrpcService extends SimpleKeysGrpc.KeysImplBase {
|
||||
private static UUID getIdentifier(Account account, IdentityType identityType) {
|
||||
return switch (identityType) {
|
||||
case ACI -> account.getAccountIdentifier();
|
||||
case PNI -> account.getPhoneNumberIdentifierOptional()
|
||||
case PNI -> account.getPhoneNumberIdentifier()
|
||||
.orElseThrow(() -> GrpcExceptions.invalidArguments("PNI identity type not allowed for an account without a phone number"));
|
||||
};
|
||||
}
|
||||
|
||||
+97
@@ -0,0 +1,97 @@
|
||||
/*
|
||||
* 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.getIdentifier(IdentityType.ACI), device);
|
||||
final MessageStream messageStream = messagesManager.getMessages(account.getAccountIdentifier(), 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.getIdentifier(IdentityType.ACI), device)
|
||||
messagesManager.mayHaveMessages(account.getAccountIdentifier(), device)
|
||||
.thenAccept(mayHaveMessages -> {
|
||||
if (mayHaveMessages) {
|
||||
pushNotificationScheduler.scheduleDelayedNotification(account, device,
|
||||
@@ -240,7 +240,7 @@ public class MessageDispatcher {
|
||||
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.getIdentifier(IdentityType.ACI),
|
||||
messageDeliveryLoopMonitor.recordDeliveryAttempt(account.getAccountIdentifier(),
|
||||
device.getId(),
|
||||
UUIDUtil.fromByteString(message.getServerGuid()),
|
||||
userAgent,
|
||||
|
||||
+1
-1
@@ -143,7 +143,7 @@ public class MessagesAnonymousGrpcService extends SimpleMessagesAnonymousGrpc.Me
|
||||
|
||||
final Account destination = maybeDestination.get();
|
||||
|
||||
rateLimiters.getStoriesLimiter().validate(destination.getIdentifier(IdentityType.ACI));
|
||||
rateLimiters.getStoriesLimiter().validate(destination.getAccountIdentifier());
|
||||
|
||||
return sendIndividualMessage(destination,
|
||||
destinationServiceIdentifier,
|
||||
|
||||
+7
-12
@@ -256,19 +256,14 @@ public class OneTimeDonationsGrpcService extends SimpleOneTimeDonationsGrpc.OneT
|
||||
public CreateBoostReceiptCredentialsResponse createBoostReceiptCredentials(
|
||||
final CreateBoostReceiptCredentialsRequest request) throws IOException {
|
||||
|
||||
final PaymentProvider processor;
|
||||
final Optional<PaymentDetails> maybePaymentDetails;
|
||||
switch (request.getProcessor()) {
|
||||
case PAYMENT_PROVIDER_STRIPE -> {
|
||||
processor = PaymentProvider.STRIPE;
|
||||
maybePaymentDetails = stripeManager.claimOneTimePurchase(request.getPaymentIntentId());
|
||||
}
|
||||
case PAYMENT_PROVIDER_BRAINTREE -> {
|
||||
processor = PaymentProvider.BRAINTREE;
|
||||
maybePaymentDetails = braintreeManager.claimOneTimePurchase(request.getPaymentIntentId());
|
||||
}
|
||||
final PaymentProvider processor = PaymentProvider.fromProto(request.getProcessor())
|
||||
.orElseThrow(() -> GrpcExceptions.fieldViolation("processor", "Unsupported payment processor"));
|
||||
|
||||
final Optional<PaymentDetails> maybePaymentDetails = switch (processor) {
|
||||
case STRIPE -> stripeManager.claimOneTimePurchase(request.getPaymentIntentId());
|
||||
case BRAINTREE -> braintreeManager.claimOneTimePurchase(request.getPaymentIntentId());
|
||||
default -> throw GrpcExceptions.fieldViolation("processor", "Unsupported payment processor");
|
||||
}
|
||||
};
|
||||
|
||||
if (maybePaymentDetails.isEmpty()) {
|
||||
return CreateBoostReceiptCredentialsResponse.newBuilder()
|
||||
|
||||
@@ -16,11 +16,11 @@ import java.util.HexFormat;
|
||||
import java.util.Optional;
|
||||
import org.bouncycastle.crypto.digests.TupleHash;
|
||||
import org.signal.chat.common.S3UploadForm;
|
||||
import org.signal.chat.profile.AccountInfo;
|
||||
import org.signal.chat.profile.GetExpiringProfileKeyCredentialResult;
|
||||
import org.signal.chat.profile.LegacyProfileResult;
|
||||
import org.signal.chat.profile.ProfileResult;
|
||||
import org.signal.chat.profile.ProfileResultOrBuilder;
|
||||
import org.signal.chat.profile.LegacyProfileResult;
|
||||
import org.signal.chat.profile.AccountInfo;
|
||||
import org.signal.libsignal.protocol.ServiceId;
|
||||
import org.signal.libsignal.zkgroup.InvalidInputException;
|
||||
import org.signal.libsignal.zkgroup.VerificationFailedException;
|
||||
@@ -30,7 +30,6 @@ import org.signal.libsignal.zkgroup.profiles.ProfileKeyCredentialRequest;
|
||||
import org.signal.libsignal.zkgroup.profiles.ServerZkProfileOperations;
|
||||
import org.whispersystems.textsecuregcm.auth.UnidentifiedAccessChecksum;
|
||||
import org.whispersystems.textsecuregcm.badges.ProfileBadgeConverter;
|
||||
import org.whispersystems.textsecuregcm.identity.IdentityType;
|
||||
import org.whispersystems.textsecuregcm.s3.PostPolicyGenerator;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.DeviceCapability;
|
||||
@@ -60,12 +59,20 @@ public class ProfileGrpcHelper {
|
||||
final VersionedProfileV1 v1Profile = maybeV1Profile.get();
|
||||
|
||||
final LegacyProfileResult.Builder builder = LegacyProfileResult.newBuilder()
|
||||
.setAccountInfo(buildAccountInfo(profileBadgeConverter, account))
|
||||
.setName(ByteString.copyFrom(v1Profile.name()))
|
||||
.setAbout(ByteString.copyFrom(v1Profile.about()))
|
||||
.setAboutEmoji(ByteString.copyFrom(v1Profile.aboutEmoji()))
|
||||
.setPhoneNumberSharing(ByteString.copyFrom(v1Profile.phoneNumberSharing()));
|
||||
.setAccountInfo(buildAccountInfo(profileBadgeConverter, account));
|
||||
|
||||
if (v1Profile.name() != null) {
|
||||
builder.setName(ByteString.copyFrom(v1Profile.name()));
|
||||
}
|
||||
if (v1Profile.about() != null) {
|
||||
builder.setAbout(ByteString.copyFrom(v1Profile.about()));
|
||||
}
|
||||
if (v1Profile.aboutEmoji() != null) {
|
||||
builder.setAboutEmoji(ByteString.copyFrom(v1Profile.aboutEmoji()));
|
||||
}
|
||||
if (v1Profile.phoneNumberSharing() != null) {
|
||||
builder.setPhoneNumberSharing(ByteString.copyFrom(v1Profile.phoneNumberSharing()));
|
||||
}
|
||||
if (v1Profile.avatar() != null) {
|
||||
builder.setAvatar(v1Profile.avatar());
|
||||
}
|
||||
@@ -110,7 +117,7 @@ public class ProfileGrpcHelper {
|
||||
final Account account) {
|
||||
final AccountInfo.Builder accountInfoBuilder = AccountInfo.newBuilder()
|
||||
.addAllBadgeIds(profileBadgeConverter.visibleBadgeIds(account.getBadges()))
|
||||
.setIdentityKey(ByteString.copyFrom(account.getIdentityKey(IdentityType.ACI).serialize()))
|
||||
.setIdentityKey(ByteString.copyFrom(account.getAccountIdentityKey().serialize()))
|
||||
.setUnrestrictedUnidentifiedAccess(account.isUnrestrictedUnidentifiedAccess());
|
||||
|
||||
account.getUnidentifiedAccessKey()
|
||||
|
||||
+33
-2
@@ -31,6 +31,8 @@ import org.signal.chat.profile.SetProfileRequest;
|
||||
import org.signal.chat.profile.SetProfileResponse;
|
||||
import org.signal.chat.profile.SetProfileResult;
|
||||
import org.signal.chat.profile.SetProfileV1Request.AvatarChange;
|
||||
import org.signal.chat.profile.SetV1AvatarRequest;
|
||||
import org.signal.chat.profile.SetV1AvatarResponse;
|
||||
import org.signal.chat.profile.SimpleProfileGrpc;
|
||||
import org.signal.libsignal.protocol.ServiceId;
|
||||
import org.signal.libsignal.zkgroup.GenericServerSecretParams;
|
||||
@@ -107,7 +109,7 @@ public class ProfileGrpcService extends SimpleProfileGrpc.ProfileImplBase {
|
||||
final AuthenticatedDevice authenticatedDevice = AuthenticationUtil.requireAuthenticatedDevice();
|
||||
|
||||
final Account account = accountsManager.getByAccountIdentifier(authenticatedDevice.accountIdentifier())
|
||||
.orElseThrow(() -> GrpcExceptions.invalidArguments("Account not found"));
|
||||
.orElseThrow(() -> GrpcExceptions.invalidCredentials("invalid credentials"));
|
||||
|
||||
if (!account.hasCapability(DeviceCapability.PROFILES_V2)) {
|
||||
return SetProfileResponse.newBuilder()
|
||||
@@ -224,7 +226,7 @@ public class ProfileGrpcService extends SimpleProfileGrpc.ProfileImplBase {
|
||||
final AuthenticatedDevice authenticatedDevice = AuthenticationUtil.requireAuthenticatedDevice();
|
||||
|
||||
final Account account = accountsManager.getByAccountIdentifier(authenticatedDevice.accountIdentifier())
|
||||
.orElseThrow(() -> GrpcExceptions.invalidCredentials("account not found"));
|
||||
.orElseThrow(() -> GrpcExceptions.invalidCredentials("invalid credentials"));
|
||||
|
||||
if (account.getZkCredentialKey().isEmpty()) {
|
||||
return GetAvatarCredentialsResponse.newBuilder()
|
||||
@@ -275,6 +277,35 @@ public class ProfileGrpcService extends SimpleProfileGrpc.ProfileImplBase {
|
||||
.orElseGet(() -> GetProfileResponse.newBuilder().setNotFound(NotFound.getDefaultInstance()).build());
|
||||
}
|
||||
|
||||
@Override
|
||||
public SetV1AvatarResponse setV1Avatar(final SetV1AvatarRequest request) {
|
||||
|
||||
final AuthenticatedDevice authenticatedDevice = AuthenticationUtil.requireAuthenticatedDevice();
|
||||
|
||||
final String version = request.getVersion();
|
||||
final Optional<VersionedProfileV1> maybeV1Profile = profilesManager.getV1(authenticatedDevice.accountIdentifier(),
|
||||
version);
|
||||
|
||||
if (maybeV1Profile.isEmpty() && request.getCommitment().isEmpty()) {
|
||||
throw GrpcExceptions.fieldViolation("commitment", "Commitment is required for new profile versions");
|
||||
}
|
||||
|
||||
maybeV1Profile.map(VersionedProfileV1::avatar).filter(a -> a.startsWith("profiles/"))
|
||||
.ifPresent(profilesManager::deleteAvatar);
|
||||
|
||||
final byte[] commitment = maybeV1Profile.map(VersionedProfileV1::commitment).orElseGet(request.getCommitment()::toByteArray);
|
||||
|
||||
final String updateAvatarObjectName = ProfileHelper.generateAvatarObjectName();
|
||||
|
||||
profilesManager.setV1Avatar(authenticatedDevice.accountIdentifier(), version, updateAvatarObjectName, commitment);
|
||||
|
||||
return SetV1AvatarResponse.newBuilder()
|
||||
.setForm(ProfileGrpcHelper.generateAvatarUploadForm(updateAvatarObjectName,
|
||||
ProfileHelper.MAX_PROFILE_AVATAR_SIZE_BYTES,
|
||||
policyGenerator, clock))
|
||||
.build();
|
||||
}
|
||||
|
||||
private Optional<Account> validateRateLimitAndGetAccount(final UUID requesterUuid,
|
||||
final ServiceIdentifier targetIdentifier) throws RateLimitExceededException {
|
||||
rateLimiters.getProfileLimiter().validate(requesterUuid);
|
||||
|
||||
@@ -5,26 +5,21 @@
|
||||
package org.whispersystems.textsecuregcm.grpc.net;
|
||||
|
||||
import java.net.SocketAddress;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
public class OmnibusRouter {
|
||||
|
||||
public record OmnibusRoute(String prefix, SocketAddress backend) {}
|
||||
|
||||
private final List<OmnibusRoute> prefixRoutes;
|
||||
private final Map<String, SocketAddress> routes;
|
||||
private final SocketAddress defaultBackend;
|
||||
|
||||
public OmnibusRouter(final List<OmnibusRoute> prefixRoutes, final SocketAddress defaultBackend) {
|
||||
this.prefixRoutes = prefixRoutes;
|
||||
public OmnibusRouter(final Map<String, SocketAddress> routes, final SocketAddress defaultBackend) {
|
||||
this.routes = routes;
|
||||
this.defaultBackend = defaultBackend;
|
||||
}
|
||||
|
||||
SocketAddress match(final String path) {
|
||||
for (final OmnibusRoute route : prefixRoutes) {
|
||||
if (path.startsWith(route.prefix)) {
|
||||
return route.backend;
|
||||
}
|
||||
}
|
||||
return defaultBackend;
|
||||
SocketAddress match(final String fullPath) {
|
||||
final int queryIndex = fullPath.indexOf('?');
|
||||
final String path = queryIndex >= 0 ? fullPath.substring(0, queryIndex) : fullPath;
|
||||
return routes.getOrDefault(path, defaultBackend);
|
||||
}
|
||||
}
|
||||
+3
-1
@@ -4,6 +4,7 @@
|
||||
*/
|
||||
package org.whispersystems.textsecuregcm.grpc.net;
|
||||
|
||||
import com.google.common.net.InetAddresses;
|
||||
import io.netty.channel.ChannelHandlerContext;
|
||||
import io.netty.channel.ChannelInboundHandlerAdapter;
|
||||
import io.netty.handler.codec.haproxy.HAProxyMessage;
|
||||
@@ -30,7 +31,8 @@ class ProxyMessageAttributeSetterHandler extends ChannelInboundHandlerAdapter {
|
||||
try {
|
||||
final String sourceAddress = proxyMessage.sourceAddress();
|
||||
if (sourceAddress != null) {
|
||||
ctx.channel().attr(PROXY_REMOTE_ADDRESS).set(InetAddress.getByName(sourceAddress));
|
||||
// Assume that the server has been configured to only allow access from a trusted PPv2 provider
|
||||
ctx.channel().attr(PROXY_REMOTE_ADDRESS).set(InetAddresses.forString(sourceAddress));
|
||||
} else {
|
||||
logger.warn("PROXY protocol message has no source address");
|
||||
}
|
||||
|
||||
+16
-2
@@ -5,17 +5,17 @@
|
||||
|
||||
package org.whispersystems.textsecuregcm.jetty;
|
||||
|
||||
import org.eclipse.jetty.http.HttpHeader;
|
||||
import org.eclipse.jetty.http2.server.HTTP2ServerConnectionFactory;
|
||||
import org.eclipse.jetty.server.ConnectionFactory;
|
||||
import org.eclipse.jetty.server.Connector;
|
||||
import org.eclipse.jetty.server.ForwardedRequestCustomizer;
|
||||
import org.eclipse.jetty.server.HttpConfiguration;
|
||||
import org.eclipse.jetty.server.HttpConnectionFactory;
|
||||
import org.eclipse.jetty.util.component.Container;
|
||||
import org.eclipse.jetty.util.component.LifeCycle;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import io.micrometer.core.instrument.binder.jetty.JettyConnectionMetrics;
|
||||
|
||||
/**
|
||||
* Uses {@link Container.Listener} to update {@link org.eclipse.jetty.server.HttpConfiguration}
|
||||
@@ -38,6 +38,20 @@ public class JettyHttpConfigurationCustomizer implements Container.Listener, Lif
|
||||
// see https://github.com/jetty/jetty.project/issues/1891
|
||||
logger.info("setNotifyRemoteAsyncErrors(false) for {}", cf);
|
||||
httpConfiguration.setNotifyRemoteAsyncErrors(false);
|
||||
|
||||
httpConfiguration.getCustomizers().stream()
|
||||
.filter(ForwardedRequestCustomizer.class::isInstance)
|
||||
.map(ForwardedRequestCustomizer.class::cast)
|
||||
.forEach(forwardedRequestCustomizer -> {
|
||||
// If this http configuration supports using proxy-supplied headers, only use X-Forwarded-For
|
||||
|
||||
// Disable all headers except for 'Forwarded'
|
||||
forwardedRequestCustomizer.setForwardedOnly(true);
|
||||
// Disable 'Forwarded'
|
||||
forwardedRequestCustomizer.setForwardedHeader(null);
|
||||
// Enable 'X-Forwarded-For'
|
||||
forwardedRequestCustomizer.setForwardedForHeader(HttpHeader.X_FORWARDED_FOR.toString());
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -65,6 +65,7 @@ public class RateLimiters extends BaseRateLimiters<RateLimiters.For> {
|
||||
CREATE_DONATION_PERMIT("createDonationCredential", new RateLimiterConfig(30, Duration.ofHours(4), true)),
|
||||
ONE_TIME_DONATION("oneTimeDonation", new RateLimiterConfig(5, Duration.ofMinutes(1), true)),
|
||||
ADD_SUBSCRIPTION_PAYMENT_METHOD("addSubscriptionPaymentMethod", new RateLimiterConfig(10, Duration.ofMinutes(1), true)),
|
||||
CHECK_TOTP("checkTotp", new RateLimiterConfig(5, Duration.ofSeconds(6), false))
|
||||
;
|
||||
|
||||
private final String id;
|
||||
@@ -250,4 +251,8 @@ public class RateLimiters extends BaseRateLimiters<RateLimiters.For> {
|
||||
public RateLimiter getCreateDonationPermitLimiter() {
|
||||
return forDescriptor(For.CREATE_DONATION_PERMIT);
|
||||
}
|
||||
|
||||
public RateLimiter getCheckTotpLimiter() {
|
||||
return forDescriptor(For.CHECK_TOTP);
|
||||
}
|
||||
}
|
||||
-36
@@ -1,36 +0,0 @@
|
||||
/*
|
||||
* Copyright 2023 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.mappers;
|
||||
|
||||
import io.dropwizard.jersey.errors.ErrorMessage;
|
||||
import io.grpc.StatusRuntimeException;
|
||||
import jakarta.ws.rs.core.MediaType;
|
||||
import jakarta.ws.rs.core.Response;
|
||||
import jakarta.ws.rs.ext.ExceptionMapper;
|
||||
import jakarta.ws.rs.ext.Provider;
|
||||
|
||||
@Provider
|
||||
public class GrpcStatusRuntimeExceptionMapper implements ExceptionMapper<StatusRuntimeException> {
|
||||
|
||||
@Override
|
||||
public Response toResponse(final StatusRuntimeException exception) {
|
||||
int httpCode = switch (exception.getStatus().getCode()) {
|
||||
case OK -> 200;
|
||||
case INVALID_ARGUMENT, FAILED_PRECONDITION, OUT_OF_RANGE -> 400;
|
||||
case UNAUTHENTICATED -> 401;
|
||||
case PERMISSION_DENIED -> 403;
|
||||
case NOT_FOUND -> 404;
|
||||
case ALREADY_EXISTS, ABORTED -> 409;
|
||||
case CANCELLED -> 499;
|
||||
case UNKNOWN, UNIMPLEMENTED, DEADLINE_EXCEEDED, RESOURCE_EXHAUSTED, INTERNAL, UNAVAILABLE, DATA_LOSS -> 500;
|
||||
};
|
||||
|
||||
return Response.status(httpCode)
|
||||
.entity(new ErrorMessage(httpCode, exception.getMessage()))
|
||||
.type(MediaType.APPLICATION_JSON_TYPE)
|
||||
.build();
|
||||
}
|
||||
}
|
||||
-115
@@ -1,115 +0,0 @@
|
||||
/*
|
||||
* Copyright 2021 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.metrics;
|
||||
|
||||
import ch.qos.logback.classic.LoggerContext;
|
||||
import ch.qos.logback.classic.PatternLayout;
|
||||
import ch.qos.logback.classic.spi.ILoggingEvent;
|
||||
import ch.qos.logback.core.Appender;
|
||||
import ch.qos.logback.core.encoder.LayoutWrappingEncoder;
|
||||
import ch.qos.logback.core.helpers.NOPAppender;
|
||||
import ch.qos.logback.core.net.ssl.SSLConfiguration;
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import com.fasterxml.jackson.annotation.JsonTypeName;
|
||||
import com.fasterxml.jackson.databind.node.JsonNodeFactory;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import com.fasterxml.jackson.databind.node.TextNode;
|
||||
import io.dropwizard.logging.common.AbstractAppenderFactory;
|
||||
import io.dropwizard.logging.common.async.AsyncAppenderFactory;
|
||||
import io.dropwizard.logging.common.filter.LevelFilterFactory;
|
||||
import io.dropwizard.logging.common.layout.LayoutFactory;
|
||||
import jakarta.validation.constraints.NotEmpty;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
import java.time.Duration;
|
||||
import java.util.Optional;
|
||||
import net.logstash.logback.appender.LogstashTcpSocketAppender;
|
||||
import net.logstash.logback.encoder.LogstashEncoder;
|
||||
import org.whispersystems.textsecuregcm.configuration.secrets.SecretString;
|
||||
import org.whispersystems.textsecuregcm.util.HostnameUtil;
|
||||
|
||||
@JsonTypeName("logstashtcpsocket")
|
||||
public class LogstashTcpSocketAppenderFactory extends AbstractAppenderFactory<ILoggingEvent> {
|
||||
|
||||
@JsonProperty
|
||||
private String destination;
|
||||
|
||||
@JsonProperty
|
||||
private Duration keepAlive = Duration.ofSeconds(20);
|
||||
|
||||
@JsonProperty
|
||||
@NotNull
|
||||
private SecretString apiKey;
|
||||
|
||||
@JsonProperty
|
||||
private String environment;
|
||||
|
||||
@JsonProperty
|
||||
@NotEmpty
|
||||
public String getDestination() {
|
||||
return destination;
|
||||
}
|
||||
|
||||
@JsonProperty
|
||||
public Duration getKeepAlive() {
|
||||
return keepAlive;
|
||||
}
|
||||
|
||||
@JsonProperty
|
||||
public SecretString getApiKey() {
|
||||
return apiKey;
|
||||
}
|
||||
|
||||
@JsonProperty
|
||||
@NotEmpty
|
||||
public String getEnvironment() {
|
||||
return environment;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Appender<ILoggingEvent> build(
|
||||
final LoggerContext context,
|
||||
final String applicationName,
|
||||
final LayoutFactory<ILoggingEvent> layoutFactory,
|
||||
final LevelFilterFactory<ILoggingEvent> levelFilterFactory,
|
||||
final AsyncAppenderFactory<ILoggingEvent> asyncAppenderFactory) {
|
||||
|
||||
final boolean disableLogstashTcpSocketAppender = Optional.ofNullable(
|
||||
System.getenv("SIGNAL_DISABLE_LOGSTASH_TCP_SOCKET_APPENDER"))
|
||||
.isPresent();
|
||||
|
||||
if (disableLogstashTcpSocketAppender) {
|
||||
return new NOPAppender<>();
|
||||
}
|
||||
|
||||
final SSLConfiguration sslConfiguration = new SSLConfiguration();
|
||||
final LogstashTcpSocketAppender appender = new LogstashTcpSocketAppender();
|
||||
appender.setName("logstashtcpsocket-appender");
|
||||
appender.setContext(context);
|
||||
appender.setSsl(sslConfiguration);
|
||||
appender.addDestination(destination);
|
||||
appender.setKeepAliveDuration(new ch.qos.logback.core.util.Duration(keepAlive.toMillis()));
|
||||
|
||||
final LogstashEncoder encoder = new LogstashEncoder();
|
||||
final ObjectNode customFieldsNode = new ObjectNode(JsonNodeFactory.instance);
|
||||
customFieldsNode.set("host", TextNode.valueOf(HostnameUtil.getLocalHostname()));
|
||||
customFieldsNode.set("service", TextNode.valueOf("chat"));
|
||||
|
||||
encoder.setCustomFields(customFieldsNode.toString());
|
||||
final LayoutWrappingEncoder<ILoggingEvent> prefix = new LayoutWrappingEncoder<>();
|
||||
final PatternLayout layout = new PatternLayout();
|
||||
layout.setPattern(String.format("%s ", apiKey.value()));
|
||||
layout.setContext(context);
|
||||
prefix.setLayout(layout);
|
||||
encoder.setPrefix(prefix);
|
||||
appender.setEncoder(encoder);
|
||||
|
||||
appender.addFilter(levelFilterFactory.build(threshold));
|
||||
getFilterFactories().forEach(f -> appender.addFilter(f.build()));
|
||||
appender.start();
|
||||
|
||||
return wrapAsync(appender, asyncAppenderFactory);
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -81,7 +81,7 @@ public class IdleDeviceNotificationScheduler extends JobScheduler {
|
||||
|
||||
try {
|
||||
return scheduleJob(runAt, SystemMapper.jsonMapper().writeValueAsBytes(
|
||||
new JobDescriptor(account.getIdentifier(IdentityType.ACI), device.getId(), device.getLastSeen())));
|
||||
new JobDescriptor(account.getAccountIdentifier(), device.getId(), device.getLastSeen())));
|
||||
} catch (final JsonProcessingException e) {
|
||||
// This should never happen when serializing an `AccountAndDeviceIdentifier`
|
||||
throw new AssertionError(e);
|
||||
|
||||
@@ -30,7 +30,6 @@ import org.whispersystems.textsecuregcm.controllers.MessageDeliveryNotAllowedExc
|
||||
import org.whispersystems.textsecuregcm.controllers.MismatchedDevices;
|
||||
import org.whispersystems.textsecuregcm.controllers.MismatchedDevicesException;
|
||||
import org.whispersystems.textsecuregcm.controllers.MultiRecipientMismatchedDevicesException;
|
||||
import org.whispersystems.textsecuregcm.identity.IdentityType;
|
||||
import org.whispersystems.textsecuregcm.identity.ServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
|
||||
import org.whispersystems.textsecuregcm.metrics.UserAgentTagUtil;
|
||||
@@ -131,7 +130,7 @@ public class MessageSender {
|
||||
syncMessageSenderDeviceId,
|
||||
platformTag);
|
||||
|
||||
messagesManager.insert(destination.getIdentifier(IdentityType.ACI), messagesByDeviceId)
|
||||
messagesManager.insert(destination.getAccountIdentifier(), messagesByDeviceId)
|
||||
.forEach((deviceId, destinationPresent) -> {
|
||||
final Envelope message = messagesByDeviceId.get(deviceId);
|
||||
|
||||
@@ -409,9 +408,14 @@ public class MessageSender {
|
||||
// We know the device must be present because we've already filtered out device IDs that aren't associated
|
||||
// with the given account
|
||||
final Device device = account.getDevice(deviceId).orElseThrow();
|
||||
final int expectedRegistrationId = device.getRegistrationId(serviceIdentifier.identityType());
|
||||
final Optional<Integer> maybeExpectedRegistrationId = switch (serviceIdentifier.identityType()) {
|
||||
case ACI -> Optional.of(device.getAccountRegistrationId());
|
||||
case PNI -> device.getPhoneNumberIdentityRegistrationId();
|
||||
};
|
||||
|
||||
return registrationId != expectedRegistrationId;
|
||||
return maybeExpectedRegistrationId
|
||||
.map(expectedRegistrationId -> registrationId != expectedRegistrationId)
|
||||
.orElse(true);
|
||||
})
|
||||
.map(Map.Entry::getKey)
|
||||
.collect(Collectors.toSet());
|
||||
|
||||
+1
-1
@@ -217,7 +217,7 @@ public class PushNotificationManager {
|
||||
// updating an uninstalled feedback timestamp though.
|
||||
accountsManager.getByAccountIdentifier(account.getAccountIdentifier()).ifPresent(rereadAccount ->
|
||||
rereadAccount.getDevice(device.getId()).ifPresent(rereadDevice ->
|
||||
accountsManager.updateDevice(rereadAccount.getIdentifier(IdentityType.ACI), device.getId(), d -> {
|
||||
accountsManager.updateDevice(rereadAccount.getAccountIdentifier(), device.getId(), d -> {
|
||||
// Don't clear the token if it's already changed
|
||||
if (originalToken.equals(getPushToken(d, tokenType))) {
|
||||
switch (tokenType) {
|
||||
|
||||
@@ -57,7 +57,11 @@ public class ReceiptSender {
|
||||
|
||||
final Map<Byte, Integer> registrationIdsByDeviceId = destinationAccount.getDevices().stream()
|
||||
.collect(Collectors.toMap(Device::getId,
|
||||
device -> device.getRegistrationId(destinationIdentifier.identityType())));
|
||||
device -> switch (destinationIdentifier.identityType()) {
|
||||
case ACI -> device.getAccountRegistrationId();
|
||||
case PNI -> device.getPhoneNumberIdentityRegistrationId()
|
||||
.orElseThrow(() -> new IllegalStateException("Destination account identified by PNI has device without PNI registration ID"));
|
||||
}));
|
||||
|
||||
try {
|
||||
messageSender.sendMessages(destinationAccount,
|
||||
|
||||
+2
-2
@@ -42,14 +42,14 @@ public class SchedulingUtil {
|
||||
final LocalTime preferredTime,
|
||||
final Clock clock) {
|
||||
|
||||
final ZonedDateTime candidateNotificationTime = account.getNumberOptional()
|
||||
final ZonedDateTime candidateNotificationTime = account.getNumber()
|
||||
.flatMap(number -> getZoneId(number, clock))
|
||||
.map(zoneId -> {
|
||||
Metrics.counter(PARSED_TIMEZONE_COUNTER_NAME, HAS_TIMEZONE_TAG_NAME, String.valueOf(true)).increment();
|
||||
return ZonedDateTime.now(clock.withZone(zoneId)).with(preferredTime);
|
||||
})
|
||||
.orElseGet(() -> {
|
||||
if (account.getNumberOptional().isPresent()) {
|
||||
if (account.getNumber().isPresent()) {
|
||||
Metrics.counter(PARSED_TIMEZONE_COUNTER_NAME, HAS_TIMEZONE_TAG_NAME, String.valueOf(false)).increment();
|
||||
}
|
||||
return ZonedDateTime.now(ZoneId.systemDefault()).with(preferredTime);
|
||||
|
||||
@@ -22,12 +22,15 @@ import java.time.Instant;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Base64;
|
||||
import java.util.Collections;
|
||||
import java.util.HashSet;
|
||||
import java.util.HexFormat;
|
||||
import java.util.List;
|
||||
import java.util.NoSuchElementException;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
import java.util.stream.IntStream;
|
||||
import javax.annotation.Nullable;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.signal.libsignal.protocol.IdentityKey;
|
||||
@@ -38,7 +41,6 @@ import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.auth.SaltedTokenHash;
|
||||
import org.whispersystems.textsecuregcm.auth.StoredRegistrationLock;
|
||||
import org.whispersystems.textsecuregcm.entities.AccountAttributes;
|
||||
import org.whispersystems.textsecuregcm.identity.IdentityType;
|
||||
import org.whispersystems.textsecuregcm.identity.ServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.util.ByteArrayBase64UrlAdapter;
|
||||
import org.whispersystems.textsecuregcm.util.IdentityKeyAdapter;
|
||||
@@ -47,6 +49,8 @@ import org.whispersystems.textsecuregcm.util.ZkCredentialPublicKeyAdapter;
|
||||
@JsonFilter("Account")
|
||||
public class Account {
|
||||
|
||||
public static final int MAX_TOTP_KEY_ID = Byte.MAX_VALUE;
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(Account.class);
|
||||
|
||||
@JsonProperty
|
||||
@@ -157,6 +161,13 @@ public class Account {
|
||||
@Nullable
|
||||
private byte[] authCredentialSalt;
|
||||
|
||||
@JsonProperty("pendingTotp")
|
||||
@Nullable
|
||||
private TotpKey pendingTotpKey;
|
||||
|
||||
@JsonProperty("totp")
|
||||
private Map<Byte, AnnotatedTotpKey> totpKeys = Collections.emptyMap();
|
||||
|
||||
@JsonIgnore
|
||||
private boolean stale;
|
||||
|
||||
@@ -164,26 +175,6 @@ public class Account {
|
||||
|
||||
public record BackupVoucher(@JsonProperty("rl") long receiptLevel, @JsonProperty("e") Instant expiration) {}
|
||||
|
||||
/// Returns an identifier for the given identity type for this account with the assumption that all accounts have
|
||||
/// identifiers for all identity types.
|
||||
///
|
||||
/// @param identityType the identity type for which to retrieve an account identifier
|
||||
///
|
||||
/// @return the identifier for the given identity type
|
||||
///
|
||||
/// @throws NoSuchElementException if the account does not have an identifier for the given identity type
|
||||
///
|
||||
/// @deprecated Different identity types have significantly differing presence and staleness requirements/guarantees
|
||||
/// for their respective account identifiers. Please use [#getAccountIdentifier()] or
|
||||
/// [#getPhoneNumberIdentifierOptional()] instead.
|
||||
@Deprecated
|
||||
public UUID getIdentifier(final IdentityType identityType) {
|
||||
return switch (identityType) {
|
||||
case ACI -> getAccountIdentifier();
|
||||
case PNI -> getPhoneNumberIdentifier();
|
||||
};
|
||||
}
|
||||
|
||||
/// Returns the core account identifier (ACI) for this account. An account's core identifier never changes.
|
||||
///
|
||||
/// @return the core account identifier for this account
|
||||
@@ -198,28 +189,10 @@ public class Account {
|
||||
this.uuid = accountIdentifier;
|
||||
}
|
||||
|
||||
/// Returns the phone number identifier for this account.
|
||||
///
|
||||
/// @throws NoSuchElementException if this account does not have a phone number identifier
|
||||
///
|
||||
/// @return the phone number identifier for this account
|
||||
///
|
||||
/// @deprecated Please use [#getPhoneNumberIdentifierOptional()] (which has clearer presence semantics) instead.
|
||||
@Deprecated
|
||||
public UUID getPhoneNumberIdentifier() {
|
||||
requireNotStale();
|
||||
|
||||
if (phoneNumberIdentifier == null) {
|
||||
throw new NoSuchElementException();
|
||||
}
|
||||
|
||||
return phoneNumberIdentifier;
|
||||
}
|
||||
|
||||
/// Returns the phone number identifier for this account or empty if this account does not have a phone number.
|
||||
///
|
||||
/// @return the phone number identifier for this account or empty if this account does not have a phone number
|
||||
public Optional<UUID> getPhoneNumberIdentifierOptional() {
|
||||
public Optional<UUID> getPhoneNumberIdentifier() {
|
||||
requireNotStale();
|
||||
|
||||
return Optional.ofNullable(phoneNumberIdentifier);
|
||||
@@ -237,26 +210,10 @@ public class Account {
|
||||
};
|
||||
}
|
||||
|
||||
/// Returns the E.164-formatted phone number for this account.
|
||||
///
|
||||
/// @return the E.164-formatted phone number for this account
|
||||
///
|
||||
/// @throws NoSuchElementException if this account does not have a phone number
|
||||
@Deprecated
|
||||
public String getNumber() {
|
||||
requireNotStale();
|
||||
|
||||
if (number == null) {
|
||||
throw new NoSuchElementException();
|
||||
}
|
||||
|
||||
return number;
|
||||
}
|
||||
|
||||
/// Returns the phone number for this account or empty if this account does not have a phone number.
|
||||
///
|
||||
/// @return the phone number for this account or empty if this account does not have a phone number
|
||||
public Optional<String> getNumberOptional() {
|
||||
public Optional<String> getNumber() {
|
||||
requireNotStale();
|
||||
|
||||
return Optional.ofNullable(number);
|
||||
@@ -390,28 +347,6 @@ public class Account {
|
||||
this.identityKey = identityKey;
|
||||
}
|
||||
|
||||
/// Returns an identity key for the given identity type for this account with the assumption that all accounts have
|
||||
/// identity keys for all identity types.
|
||||
///
|
||||
/// @param identityType the identity type for which to retrieve an identity key
|
||||
///
|
||||
/// @return the identity key for the given identity type
|
||||
///
|
||||
/// @throws NoSuchElementException if the account does not have an identifier (and therefore identity key) for the given identity type
|
||||
///
|
||||
/// @deprecated Different identity types have significantly differing existence requirements/guarantees
|
||||
/// for their respective identity keys. Please use [#getAccountIdentityKey()] or
|
||||
/// [#getPhoneNumberIdentityKey()] instead.
|
||||
@Deprecated
|
||||
public IdentityKey getIdentityKey(final IdentityType identityType) {
|
||||
requireNotStale();
|
||||
|
||||
return switch (identityType) {
|
||||
case ACI -> identityKey;
|
||||
case PNI -> Optional.ofNullable(phoneNumberIdentityKey).orElseThrow(NoSuchElementException::new);
|
||||
};
|
||||
}
|
||||
|
||||
/// Returns an identity key for the ACI identity for this account.
|
||||
public IdentityKey getAccountIdentityKey() {
|
||||
requireNotStale();
|
||||
@@ -588,12 +523,12 @@ public class Account {
|
||||
/// @return `true` if this account has a phone number and has opted into discovery by phone number or `false`
|
||||
/// otherwise
|
||||
///
|
||||
/// @see #getPhoneNumberIdentifierOptional()
|
||||
/// @see #getPhoneNumberIdentifier()
|
||||
/// @see #setDiscoverableByPhoneNumber(boolean)
|
||||
public boolean isDiscoverableByPhoneNumber() {
|
||||
requireNotStale();
|
||||
|
||||
return getPhoneNumberIdentifierOptional().isPresent() && this.discoverableByPhoneNumber;
|
||||
return getPhoneNumberIdentifier().isPresent() && this.discoverableByPhoneNumber;
|
||||
}
|
||||
|
||||
public void setDiscoverableByPhoneNumber(final boolean discoverableByPhoneNumber) {
|
||||
@@ -711,6 +646,13 @@ public class Account {
|
||||
this.accountRecoveryPasswordHash = saltedAccountRecoveryPasswordHash.hash();
|
||||
}
|
||||
|
||||
public void clearAccountRecoveryPassword() {
|
||||
requireNotStale();
|
||||
|
||||
this.accountRecoveryPasswordSalt = null;
|
||||
this.accountRecoveryPasswordHash = null;
|
||||
}
|
||||
|
||||
public Optional<byte[]> getAuthCredentialSalt() {
|
||||
requireNotStale();
|
||||
return Optional.ofNullable(authCredentialSalt);
|
||||
@@ -721,6 +663,37 @@ public class Account {
|
||||
this.authCredentialSalt = authCredentialSalt;
|
||||
}
|
||||
|
||||
public void setPendingTotpKey(@Nullable final TotpKey pendingTotpKey) {
|
||||
requireNotStale();
|
||||
this.pendingTotpKey = pendingTotpKey;
|
||||
}
|
||||
|
||||
public Optional<TotpKey> getPendingTotpKey() {
|
||||
requireNotStale();
|
||||
return Optional.ofNullable(pendingTotpKey);
|
||||
}
|
||||
|
||||
public byte getNextTotpKeyId() {
|
||||
requireNotStale();
|
||||
|
||||
final Set<Byte> usedKeys = new HashSet<>(totpKeys.keySet());
|
||||
|
||||
return (byte) IntStream.range(0, MAX_TOTP_KEY_ID + 1)
|
||||
.filter(b -> !usedKeys.contains((byte) b))
|
||||
.findFirst()
|
||||
.orElseThrow(IllegalStateException::new);
|
||||
}
|
||||
|
||||
public Map<Byte, AnnotatedTotpKey> getTotpKeys() {
|
||||
requireNotStale();
|
||||
return totpKeys;
|
||||
}
|
||||
|
||||
public void setTotpKeys(final Map<Byte, AnnotatedTotpKey> totpKeys) {
|
||||
requireNotStale();
|
||||
this.totpKeys = totpKeys;
|
||||
}
|
||||
|
||||
public void markStale() {
|
||||
stale = true;
|
||||
}
|
||||
|
||||
+1
-1
@@ -113,6 +113,6 @@ public class AccountLockManager {
|
||||
public <V, E extends Exception> V withSingleAccountLock(Account account,
|
||||
final ThrowingSupplier<V, E> task,
|
||||
final Executor lockAcquisitionExecutor) throws E {
|
||||
return withLock(Set.of(account.getPhoneNumberIdentifierOptional().orElse(account.getAccountIdentifier())), task, lockAcquisitionExecutor);
|
||||
return withLock(Set.of(account.getPhoneNumberIdentifier().orElse(account.getAccountIdentifier())), task, lockAcquisitionExecutor);
|
||||
}
|
||||
}
|
||||
@@ -26,7 +26,6 @@ import java.util.Collection;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
@@ -37,6 +36,7 @@ import javax.annotation.Nonnull;
|
||||
import javax.annotation.Nullable;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.signal.libsignal.zkgroup.backups.BackupCredentialType;
|
||||
import org.signal.libsignal.zkgroup.receipts.ReceiptCredentialPresentation;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.util.AsyncTimerUtil;
|
||||
@@ -168,6 +168,7 @@ public class Accounts {
|
||||
|
||||
private final DynamoDbClient dynamoDbClient;
|
||||
private final DynamoDbAsyncClient dynamoDbAsyncClient;
|
||||
private final RedeemedReceiptsManager redeemedReceiptsManager;
|
||||
|
||||
private final String phoneNumberConstraintTableName;
|
||||
private final String phoneNumberIdentifierConstraintTableName;
|
||||
@@ -180,6 +181,7 @@ public class Accounts {
|
||||
final Clock clock,
|
||||
final DynamoDbClient dynamoDbClient,
|
||||
final DynamoDbAsyncClient dynamoDbAsyncClient,
|
||||
final RedeemedReceiptsManager redeemedReceiptsManager,
|
||||
final String accountsTableName,
|
||||
final String phoneNumberConstraintTableName,
|
||||
final String phoneNumberIdentifierConstraintTableName,
|
||||
@@ -190,6 +192,7 @@ public class Accounts {
|
||||
this.clock = clock;
|
||||
this.dynamoDbClient = dynamoDbClient;
|
||||
this.dynamoDbAsyncClient = dynamoDbAsyncClient;
|
||||
this.redeemedReceiptsManager = redeemedReceiptsManager;
|
||||
this.phoneNumberConstraintTableName = phoneNumberConstraintTableName;
|
||||
this.phoneNumberIdentifierConstraintTableName = phoneNumberIdentifierConstraintTableName;
|
||||
this.accountsTableName = accountsTableName;
|
||||
@@ -214,24 +217,27 @@ public class Accounts {
|
||||
boolean create(final Account account, final List<TransactWriteItem> additionalWriteItems)
|
||||
throws AccountAlreadyExistsException {
|
||||
|
||||
if (account.getNumber().isEmpty() || account.getPhoneNumberIdentifier().isEmpty()) {
|
||||
throw new IllegalArgumentException("Phone number and phone number identifier must be set");
|
||||
}
|
||||
|
||||
final Timer.Sample sample = Timer.start();
|
||||
|
||||
try {
|
||||
final AttributeValue uuidAttr = AttributeValues.fromUUID(account.getAccountIdentifier());
|
||||
final AttributeValue numberAttr = AttributeValues.fromString(account.getNumber());
|
||||
final AttributeValue pniUuidAttr = AttributeValues.fromUUID(account.getPhoneNumberIdentifier());
|
||||
final AttributeValue numberAttr = AttributeValues.fromString(account.getNumber().get());
|
||||
final AttributeValue pniUuidAttr = AttributeValues.fromUUID(account.getPhoneNumberIdentifier().get());
|
||||
|
||||
final TransactWriteItem phoneNumberConstraintPut = buildConstraintTablePutIfAbsent(
|
||||
phoneNumberConstraintTableName, uuidAttr, ATTR_ACCOUNT_E164, numberAttr);
|
||||
|
||||
final TransactWriteItem phoneNumberIdentifierConstraintPut = buildConstraintTablePutIfAbsent(
|
||||
phoneNumberIdentifierConstraintTableName, uuidAttr, ATTR_PNI_UUID, pniUuidAttr);
|
||||
|
||||
final TransactWriteItem accountPut = buildAccountPut(account, uuidAttr, numberAttr, pniUuidAttr);
|
||||
final TransactWriteItem accountPut = buildAccountPut(account, uuidAttr, Optional.of(numberAttr), Optional.of(pniUuidAttr));
|
||||
|
||||
// Clear any "recently deleted account" record for this number since, if it existed, we've used its old ACI for
|
||||
// the newly-created account.
|
||||
final TransactWriteItem deletedAccountDelete = buildRemoveDeletedAccount(account.getPhoneNumberIdentifier());
|
||||
final TransactWriteItem deletedAccountDelete = buildRemoveDeletedAccount(account.getPhoneNumberIdentifier().get());
|
||||
|
||||
final Collection<TransactWriteItem> writeItems = new ArrayList<>(
|
||||
List.of(phoneNumberConstraintPut, phoneNumberIdentifierConstraintPut, accountPut, deletedAccountDelete));
|
||||
@@ -292,6 +298,76 @@ public class Accounts {
|
||||
return true;
|
||||
}
|
||||
|
||||
boolean create(final Account account,
|
||||
final ReceiptCredentialPresentation receiptCredentialPresentation,
|
||||
final byte[] accountRecoveryPasswordInRequest,
|
||||
final List<TransactWriteItem> additionalWriteItems)
|
||||
throws AccountAlreadyExistsException, ReceiptAlreadyRedeemedException {
|
||||
|
||||
final Timer.Sample sample = Timer.start();
|
||||
|
||||
try {
|
||||
final AttributeValue uuidAttr = AttributeValues.fromUUID(account.getAccountIdentifier());
|
||||
|
||||
final TransactWriteItem signalLoginReceiptConstraintPut =
|
||||
redeemedReceiptsManager.buildTransactWriteItemForReceipt(
|
||||
receiptCredentialPresentation.getReceiptSerial(),
|
||||
Instant.ofEpochSecond(receiptCredentialPresentation.getReceiptExpirationTime()),
|
||||
receiptCredentialPresentation.getReceiptLevel(),
|
||||
account.getAccountIdentifier());
|
||||
final TransactWriteItem accountPut = buildAccountPut(account, uuidAttr, Optional.empty(), Optional.empty());
|
||||
|
||||
final Collection<TransactWriteItem> writeItems = new ArrayList<>(
|
||||
List.of(signalLoginReceiptConstraintPut, accountPut));
|
||||
|
||||
writeItems.addAll(additionalWriteItems);
|
||||
|
||||
final TransactWriteItemsRequest request = TransactWriteItemsRequest.builder()
|
||||
.transactItems(writeItems)
|
||||
.build();
|
||||
|
||||
try {
|
||||
dynamoDbClient.transactWriteItems(request);
|
||||
} catch (final TransactionCanceledException e) {
|
||||
|
||||
final CancellationReason receiptSerialConstraintCancellationReason = e.cancellationReasons().get(0);
|
||||
|
||||
if (conditionalCheckFailed(receiptSerialConstraintCancellationReason)) {
|
||||
final UUID existingAccountUuid = UUIDUtil.fromByteBuffer(receiptSerialConstraintCancellationReason.item()
|
||||
.get(RedeemedReceiptsManager.ATTR_ACCOUNT_UUID).b().asByteBuffer());
|
||||
final Account existingAccount = getByAccountIdentifier(existingAccountUuid)
|
||||
// The account was already deleted, and we don't allow re-registering with the same receipt
|
||||
.orElseThrow(ReceiptAlreadyRedeemedException::new);
|
||||
|
||||
// If the account recovery password in the request matches the existing account, this is likely a client retry,
|
||||
// and we continue to allow for idempotency, otherwise this is an attempt to double-redeem a receipt
|
||||
final boolean isRetry = existingAccount.getAccountRecoveryPassword()
|
||||
.map(arp -> PhoneNumberRecoveryPasswordsManager.verify(arp, accountRecoveryPasswordInRequest))
|
||||
.orElse(false);
|
||||
|
||||
if (!isRetry) {
|
||||
throw new ReceiptAlreadyRedeemedException();
|
||||
}
|
||||
|
||||
throw new AccountAlreadyExistsException(existingAccount);
|
||||
}
|
||||
|
||||
final CancellationReason accountCancellationReason = e.cancellationReasons().get(1);
|
||||
if (TRANSACTION_CONFLICT.equals(accountCancellationReason.code())) {
|
||||
// this should only happen if two clients manage to make concurrent create() calls
|
||||
throw new ContestedOptimisticLockException();
|
||||
}
|
||||
|
||||
// this shouldn't happen
|
||||
throw new RuntimeException("could not create account: " + extractCancellationReasonCodes(e));
|
||||
}
|
||||
} finally {
|
||||
sample.stop(CREATE_TIMER);
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Copies over any account attributes that should be preserved when a new account reclaims an account identifier.
|
||||
*
|
||||
@@ -303,11 +379,13 @@ public class Accounts {
|
||||
final Collection<TransactWriteItem> additionalWriteItems) {
|
||||
|
||||
if (!existingAccount.getAccountIdentifier().equals(accountToCreate.getAccountIdentifier()) ||
|
||||
existingAccount.getNumber().isPresent() != accountToCreate.getNumber().isPresent() ||
|
||||
!existingAccount.getPhoneNumberIdentifier().equals(accountToCreate.getPhoneNumberIdentifier())) {
|
||||
|
||||
log.error("Reclaimed accounts must match. Old account {}:{}:{}, New account {}:{}:{}",
|
||||
existingAccount.getAccountIdentifier(), redactPhoneNumber(existingAccount.getNumber()), existingAccount.getPhoneNumberIdentifier(),
|
||||
accountToCreate.getAccountIdentifier(), redactPhoneNumber(accountToCreate.getNumber()), accountToCreate.getPhoneNumberIdentifier());
|
||||
existingAccount.getAccountIdentifier(), existingAccount.getNumber().map(Accounts::redactPhoneNumber), existingAccount.getPhoneNumberIdentifier(),
|
||||
accountToCreate.getAccountIdentifier(), accountToCreate.getNumber().map(Accounts::redactPhoneNumber), accountToCreate.getPhoneNumberIdentifier());
|
||||
|
||||
throw new IllegalArgumentException("reclaimed accounts must match");
|
||||
}
|
||||
|
||||
@@ -325,10 +403,17 @@ public class Accounts {
|
||||
// Carry over the existing backup voucher to the new account
|
||||
accountToCreate.setBackupVoucher(existingAccount.getBackupVoucher());
|
||||
|
||||
// Carry over any existing badges to the new account
|
||||
accountToCreate.setBadges(clock, existingAccount.getBadges());
|
||||
|
||||
// Carry over the existing ZK credential key to the new account
|
||||
accountToCreate.setZkCredentialKey(existingAccount.getZkCredentialKey().orElse(null));
|
||||
accountToCreate.setZkCredentialKeyRotationId(existingAccount.getZkCredentialKeyRotationId());
|
||||
|
||||
// Carry over any existing TOTP keys to the new account; we don't need to copy the pending TOTP key since that's
|
||||
// just a temporary holding place for essentially ephemeral data
|
||||
accountToCreate.setTotpKeys(new HashMap<>(existingAccount.getTotpKeys()));
|
||||
|
||||
final List<TransactWriteItem> writeItems = new ArrayList<>();
|
||||
|
||||
// If we're reclaiming an account that already has a username, we'd like to give the re-registering client
|
||||
@@ -378,19 +463,23 @@ public class Accounts {
|
||||
|
||||
// Phone number canonicalization means that a user can use a different phone number in the same equivalence class
|
||||
// to reclaim the account.
|
||||
if (!existingAccount.getNumber().equals(accountToCreate.getNumber())) {
|
||||
if (getAlternateForms(existingAccount.getNumber()).contains(accountToCreate.getNumber())) {
|
||||
if (!existingAccount.getNumber().equals(accountToCreate.getNumber())
|
||||
&& existingAccount.getNumber().isPresent()
|
||||
&& accountToCreate.getNumber().isPresent()) {
|
||||
final String existingAccountNumber = existingAccount.getNumber().get();
|
||||
final String accountToCreateNumber = accountToCreate.getNumber().get();
|
||||
if (getAlternateForms(existingAccountNumber).contains(accountToCreateNumber)) {
|
||||
final AttributeValue uuidAttr = AttributeValues.fromUUID(existingAccount.getAccountIdentifier());
|
||||
final AttributeValue numberAttr = AttributeValues.fromString(accountToCreate.getNumber());
|
||||
final AttributeValue numberAttr = AttributeValues.fromString(accountToCreateNumber);
|
||||
final TransactWriteItem phoneNumberConstraintPut = buildConstraintTablePutIfAbsent(
|
||||
phoneNumberConstraintTableName, uuidAttr, ATTR_ACCOUNT_E164, numberAttr);
|
||||
|
||||
writeItems.add(buildDelete(phoneNumberConstraintTableName, ATTR_ACCOUNT_E164, existingAccount.getNumber()));
|
||||
writeItems.add(buildDelete(phoneNumberConstraintTableName, ATTR_ACCOUNT_E164, existingAccountNumber));
|
||||
writeItems.add(phoneNumberConstraintPut);
|
||||
} else {
|
||||
throw new IllegalStateException(String.format("Reclaiming account with a non-equivalent phone number. Old account %s:%s:%s, new account %s:%s:%s",
|
||||
existingAccount.getAccountIdentifier(), redactPhoneNumber(existingAccount.getNumber()), existingAccount.getPhoneNumberIdentifier(),
|
||||
accountToCreate.getAccountIdentifier(), redactPhoneNumber(accountToCreate.getNumber()), accountToCreate.getPhoneNumberIdentifier()));
|
||||
existingAccount.getAccountIdentifier(), redactPhoneNumber(existingAccountNumber), existingAccount.getPhoneNumberIdentifier(),
|
||||
accountToCreate.getAccountIdentifier(), redactPhoneNumber(accountToCreateNumber), accountToCreate.getPhoneNumberIdentifier()));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -408,7 +497,7 @@ public class Accounts {
|
||||
if (unwrapped instanceof TransactionCanceledException te) {
|
||||
if (Accounts.conditionalCheckFailed(te.cancellationReasons().get(updateAccountItemIndex))) {
|
||||
final Map<String, AttributeValue> item = te.cancellationReasons().get(updateAccountItemIndex).item();
|
||||
final String existingNumber = AttributeValues.getString(item, Accounts.ATTR_ACCOUNT_E164, null);
|
||||
final Optional<String> existingNumber = Optional.ofNullable(AttributeValues.getString(item, Accounts.ATTR_ACCOUNT_E164, null));
|
||||
if (!existingAccount.getNumber().equals(existingNumber)) {
|
||||
log.error("Failed to update account due to unexpected existing phone number. Account {}. Expected {}, got {}",
|
||||
existingAccount.getAccountIdentifier(), existingAccount.getNumber(), existingNumber);
|
||||
@@ -446,8 +535,8 @@ public class Accounts {
|
||||
final Collection<TransactWriteItem> additionalWriteItems) {
|
||||
|
||||
CHANGE_NUMBER_TIMER.record(() -> {
|
||||
final String originalNumber = account.getNumber();
|
||||
final UUID originalPni = account.getPhoneNumberIdentifier();
|
||||
final String originalNumber = account.getNumber().orElseThrow(() -> new IllegalArgumentException("Account does not have a phone number"));
|
||||
final UUID originalPni = account.getPhoneNumberIdentifier().orElseThrow(() -> new IllegalArgumentException("Account does not have a phone number"));
|
||||
|
||||
boolean succeeded = false;
|
||||
|
||||
@@ -990,26 +1079,34 @@ public class Accounts {
|
||||
static UpdateAccountSpec forReclaimedAccount(
|
||||
final String accountTableName,
|
||||
final Account account,
|
||||
final String expectedExistingE164) {
|
||||
final Optional<String> maybeExpectedExistingE164) {
|
||||
final UpdateAccountSpec base = forAccount(accountTableName, account);
|
||||
|
||||
final Map<String, String> attrNames = new HashMap<>(base.attrNames());
|
||||
final Map<String, AttributeValue> attrValues = new HashMap<>(base.attrValues());
|
||||
attrValues.put(":number", AttributeValues.fromString(account.getNumber()));
|
||||
|
||||
final UpdateExpression updateExpression = base.updateExpression();
|
||||
final List<String> setClauses = new ArrayList<>(updateExpression.setClauses());
|
||||
setClauses.add("#number = :number");
|
||||
|
||||
final MembershipExpression membershipExpression = MembershipExpression.build(getAlternateForms(expectedExistingE164));
|
||||
attrValues.putAll(membershipExpression.values());
|
||||
final String conditionExpression = account.getNumber()
|
||||
.map(number -> {
|
||||
attrNames.put("#number", ATTR_ACCOUNT_E164);
|
||||
attrValues.put(":number", AttributeValues.fromString(number));
|
||||
setClauses.add("#number = :number");
|
||||
|
||||
// Defensive check: we should only update the e164 to another e164 in the same equivalence class
|
||||
final String conditionExpression = base.conditionExpression() + " AND #number IN %s".formatted(membershipExpression.expression());
|
||||
final MembershipExpression membershipExpression = maybeExpectedExistingE164
|
||||
.map(e164 -> MembershipExpression.build(getAlternateForms(e164)))
|
||||
.orElseThrow(() -> new IllegalArgumentException("E164 must be present on existing account"));
|
||||
|
||||
attrValues.putAll(membershipExpression.values());
|
||||
// Defensive check: if an e164 exists on the account, we should only update it to another e164 in the same equivalence class
|
||||
return base.conditionExpression() + " AND #number IN %s".formatted(membershipExpression.expression());
|
||||
})
|
||||
.orElse(base.conditionExpression());
|
||||
|
||||
return new UpdateAccountSpec(
|
||||
base.tableName(),
|
||||
base.key(),
|
||||
base.attrNames(),
|
||||
attrNames,
|
||||
attrValues,
|
||||
new UpdateExpression(setClauses, updateExpression.addClauses(), updateExpression.removeClauses()),
|
||||
conditionExpression
|
||||
@@ -1020,7 +1117,6 @@ public class Accounts {
|
||||
final String accountTableName,
|
||||
final Account account) {
|
||||
final Map<String, String> attrNames = new HashMap<>(Map.of(
|
||||
"#number", ATTR_ACCOUNT_E164,
|
||||
"#data", ATTR_ACCOUNT_DATA,
|
||||
"#cds", ATTR_CANONICALLY_DISCOVERABLE,
|
||||
"#version", ATTR_VERSION));
|
||||
@@ -1083,7 +1179,7 @@ public class Accounts {
|
||||
attrNames,
|
||||
attrValues,
|
||||
new UpdateExpression(setClauses, addClauses, removeClauses),
|
||||
"attribute_exists(#number) AND #version = :version");
|
||||
"#version = :version");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1305,12 +1401,17 @@ public class Accounts {
|
||||
account = maybeAccount.get();
|
||||
}
|
||||
|
||||
final List<TransactWriteItem> transactWriteItems = new ArrayList<>(List.of(
|
||||
buildConditionalDeleteAccount(account),
|
||||
buildDelete(phoneNumberConstraintTableName, ATTR_ACCOUNT_E164, account.getNumber()),
|
||||
buildDelete(phoneNumberIdentifierConstraintTableName, ATTR_PNI_UUID, account.getPhoneNumberIdentifier()),
|
||||
buildPutDeletedAccount(uuid, account.getPhoneNumberIdentifier())
|
||||
));
|
||||
|
||||
final List<TransactWriteItem> transactWriteItems = new ArrayList<>();
|
||||
transactWriteItems.add(buildConditionalDeleteAccount(account));
|
||||
|
||||
account.getNumber().ifPresent(e164 -> transactWriteItems.add(
|
||||
buildDelete(phoneNumberConstraintTableName, ATTR_ACCOUNT_E164, e164)));
|
||||
|
||||
account.getPhoneNumberIdentifier().ifPresent(pni -> {
|
||||
transactWriteItems.add(buildDelete(phoneNumberIdentifierConstraintTableName, ATTR_PNI_UUID, pni));
|
||||
transactWriteItems.add(buildPutDeletedAccount(uuid, pni));
|
||||
});
|
||||
|
||||
account.getUsernameHash().ifPresent(usernameHash -> transactWriteItems.add(
|
||||
buildDelete(usernamesConstraintTableName, UsernameTable.KEY_USERNAME_HASH, usernameHash)));
|
||||
@@ -1484,13 +1585,14 @@ public class Accounts {
|
||||
private TransactWriteItem buildAccountPut(
|
||||
final Account account,
|
||||
final AttributeValue uuidAttr,
|
||||
final AttributeValue numberAttr,
|
||||
final AttributeValue pniUuidAttr) {
|
||||
final Optional<AttributeValue> maybeNumberAttr,
|
||||
final Optional<AttributeValue> maybePniUuidAttr) {
|
||||
if (maybeNumberAttr.isPresent() != maybePniUuidAttr.isPresent()) {
|
||||
throw new IllegalArgumentException("Number and PNI attribute values must both be provided together or not at all");
|
||||
}
|
||||
|
||||
final Map<String, AttributeValue> item = new HashMap<>(Map.of(
|
||||
KEY_ACCOUNT_UUID, uuidAttr,
|
||||
ATTR_ACCOUNT_E164, numberAttr,
|
||||
ATTR_PNI_UUID, pniUuidAttr,
|
||||
ATTR_ACCOUNT_DATA, accountDataAttributeValue(account),
|
||||
ATTR_VERSION, AttributeValues.fromInt(account.getVersion()),
|
||||
ATTR_CANONICALLY_DISCOVERABLE, AttributeValues.fromBool(account.isDiscoverableByPhoneNumber())));
|
||||
@@ -1500,14 +1602,24 @@ public class Accounts {
|
||||
.map(AttributeValues::fromByteArray)
|
||||
.ifPresent(uak -> item.put(ATTR_UAK, uak));
|
||||
|
||||
return TransactWriteItem.builder()
|
||||
.put(Put.builder()
|
||||
.conditionExpression("attribute_not_exists(#pni) OR #pni = :pni")
|
||||
.expressionAttributeNames(Map.of("#pni", ATTR_PNI_UUID))
|
||||
.expressionAttributeValues(Map.of(":pni", pniUuidAttr))
|
||||
final Put put = maybeNumberAttr.map(numberAttr -> {
|
||||
item.put(ATTR_ACCOUNT_E164, numberAttr);
|
||||
item.put(ATTR_PNI_UUID, maybePniUuidAttr.get());
|
||||
return Put.builder()
|
||||
.tableName(accountsTableName)
|
||||
.item(item)
|
||||
.conditionExpression("attribute_not_exists(#pni) OR #pni = :pni")
|
||||
.expressionAttributeNames(Map.of("#pni", ATTR_PNI_UUID))
|
||||
.expressionAttributeValues(Map.of(":pni", maybePniUuidAttr.get()))
|
||||
.build();
|
||||
})
|
||||
.orElseGet(() -> Put.builder()
|
||||
.tableName(accountsTableName)
|
||||
.item(item)
|
||||
.build())
|
||||
.build());
|
||||
|
||||
return TransactWriteItem.builder()
|
||||
.put(put)
|
||||
.build();
|
||||
}
|
||||
|
||||
@@ -1584,13 +1696,13 @@ public class Accounts {
|
||||
CompletableFuture<Void> regenerateConstraints(final Account account) {
|
||||
final List<CompletableFuture<?>> constraintFutures = new ArrayList<>();
|
||||
|
||||
account.getNumberOptional().ifPresent(phoneNumber ->
|
||||
account.getNumber().ifPresent(phoneNumber ->
|
||||
constraintFutures.add(writeConstraint(phoneNumberConstraintTableName,
|
||||
account.getAccountIdentifier(),
|
||||
ATTR_ACCOUNT_E164,
|
||||
AttributeValues.fromString(phoneNumber))));
|
||||
|
||||
account.getPhoneNumberIdentifierOptional().ifPresent(phoneNumberIdentifier ->
|
||||
account.getPhoneNumberIdentifier().ifPresent(phoneNumberIdentifier ->
|
||||
constraintFutures.add(writeConstraint(phoneNumberIdentifierConstraintTableName,
|
||||
account.getAccountIdentifier(),
|
||||
ATTR_PNI_UUID,
|
||||
@@ -1656,7 +1768,6 @@ public class Accounts {
|
||||
@Nonnull
|
||||
static Account fromItem(final Map<String, AttributeValue> item) {
|
||||
if (!item.containsKey(ATTR_ACCOUNT_DATA)
|
||||
|| !item.containsKey(ATTR_ACCOUNT_E164)
|
||||
|| !item.containsKey(KEY_ACCOUNT_UUID)
|
||||
|| !item.containsKey(ATTR_CANONICALLY_DISCOVERABLE)) {
|
||||
throw new RuntimeException("item missing values");
|
||||
@@ -1667,16 +1778,14 @@ public class Accounts {
|
||||
final UUID accountIdentifier = UUIDUtil.fromByteBuffer(item.get(KEY_ACCOUNT_UUID).b().asByteBuffer());
|
||||
final UUID phoneNumberIdentifierFromAttribute = AttributeValues.getUUID(item, ATTR_PNI_UUID, null);
|
||||
|
||||
if (account.getPhoneNumberIdentifier() == null || phoneNumberIdentifierFromAttribute == null ||
|
||||
!Objects.equals(account.getPhoneNumberIdentifier(), phoneNumberIdentifierFromAttribute)) {
|
||||
|
||||
log.warn("Missing or mismatched PNIs for account {}. From JSON: {}; from attribute: {}",
|
||||
if (!account.getPhoneNumberIdentifier().equals(Optional.ofNullable(phoneNumberIdentifierFromAttribute))) {
|
||||
log.warn("Mismatched PNIs for account {}. From JSON: {}; from attribute: {}",
|
||||
accountIdentifier, account.getPhoneNumberIdentifier(), phoneNumberIdentifierFromAttribute);
|
||||
}
|
||||
|
||||
final String attributeNumber = item.get(ATTR_ACCOUNT_E164).s();
|
||||
if (account.getNumber() == null || !account.getNumber().equals(attributeNumber)) {
|
||||
log.error("Missing or mismatched phone numbers for account {}. From JSON: {}; from attribute: {}",
|
||||
final String attributeNumber = AttributeValues.getString(item, ATTR_ACCOUNT_E164, null);
|
||||
if (!account.getNumber().equals(Optional.ofNullable(attributeNumber))) {
|
||||
log.error("Mismatched phone numbers for account {}. From JSON: {}; from attribute: {}",
|
||||
accountIdentifier, account.getNumber(), attributeNumber);
|
||||
}
|
||||
|
||||
|
||||
+541
-153
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,48 @@
|
||||
/*
|
||||
* Copyright 2026 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.storage;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import com.fasterxml.jackson.annotation.JsonUnwrapped;
|
||||
import java.util.Arrays;
|
||||
import java.util.Objects;
|
||||
import javax.crypto.SecretKey;
|
||||
|
||||
public record AnnotatedTotpKey(@JsonUnwrapped
|
||||
TotpKey totpKey,
|
||||
|
||||
@JsonProperty("metadata")
|
||||
byte[] metadataCiphertext) implements SecretKey {
|
||||
|
||||
@Override
|
||||
public String getAlgorithm() {
|
||||
return totpKey().getAlgorithm();
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getFormat() {
|
||||
return totpKey.getFormat();
|
||||
}
|
||||
|
||||
@Override
|
||||
public byte[] getEncoded() {
|
||||
return totpKey().getEncoded();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(final Object o) {
|
||||
if (!(o instanceof AnnotatedTotpKey(TotpKey key, byte[] ciphertext))) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return Objects.equals(totpKey, key) && Objects.deepEquals(metadataCiphertext, ciphertext);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return Objects.hash(totpKey, Arrays.hashCode(metadataCiphertext));
|
||||
}
|
||||
}
|
||||
+4
-4
@@ -101,12 +101,12 @@ public class ChangeNumberManager {
|
||||
|
||||
final Account account = accountAndMaybeExistingAccount.first();
|
||||
|
||||
if (account.getNumberOptional().isEmpty()) {
|
||||
if (account.getNumber().isEmpty()) {
|
||||
throw new IllegalArgumentException("account does not have a phone number");
|
||||
}
|
||||
|
||||
// Only verify and check reglock if there's a data change to be made...
|
||||
if (!account.getNumberOptional().get().equals(number)) {
|
||||
if (!account.getNumber().get().equals(number)) {
|
||||
|
||||
final Optional<Duration> waitingPeriodRemaining = changeNumberWaitingPeriodManager.getWaitingPeriodRemaining(account.getAccountIdentifier());
|
||||
if (waitingPeriodRemaining.isPresent()) {
|
||||
@@ -122,7 +122,7 @@ public class ChangeNumberManager {
|
||||
final Optional<Account> existingAccount = accountAndMaybeExistingAccount.second();
|
||||
|
||||
if (existingAccount.isPresent()) {
|
||||
assert existingAccount.get().getNumberOptional().isPresent();
|
||||
assert existingAccount.get().getNumber().isPresent();
|
||||
registrationLockVerificationManager.verifyRegistrationLock(existingAccount.get(), registrationLock,
|
||||
userAgent, RegistrationLockVerificationManager.Flow.CHANGE_NUMBER, verificationType);
|
||||
}
|
||||
@@ -170,7 +170,7 @@ public class ChangeNumberManager {
|
||||
try {
|
||||
// Now that we've actually updated the account, populate the "updated PNI" field on all envelopes
|
||||
messagesByDeviceId.replaceAll((_, envelope) ->
|
||||
envelope.toBuilder().setUpdatedPni(UUIDUtil.toByteString(updatedAccount.getPhoneNumberIdentifierOptional()
|
||||
envelope.toBuilder().setUpdatedPni(UUIDUtil.toByteString(updatedAccount.getPhoneNumberIdentifier()
|
||||
.orElseThrow(() -> new AssertionError("Account does not have a PNI after changing number"))))
|
||||
.build());
|
||||
|
||||
|
||||
@@ -9,17 +9,17 @@ import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import com.fasterxml.jackson.annotation.JsonSetter;
|
||||
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
|
||||
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import java.time.Duration;
|
||||
import java.util.Collections;
|
||||
import java.util.EnumSet;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.IntStream;
|
||||
import javax.annotation.Nullable;
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import org.whispersystems.textsecuregcm.auth.SaltedTokenHash;
|
||||
import org.whispersystems.textsecuregcm.identity.IdentityType;
|
||||
import org.whispersystems.textsecuregcm.util.ByteArrayAdapter;
|
||||
import org.whispersystems.textsecuregcm.util.DeviceCapabilityAdapter;
|
||||
import org.whispersystems.textsecuregcm.util.DeviceNameByteArrayAdapter;
|
||||
@@ -71,7 +71,8 @@ public class Device {
|
||||
private int registrationId;
|
||||
|
||||
@JsonProperty("pniRegistrationId")
|
||||
private int phoneNumberIdentityRegistrationId;
|
||||
@Nullable
|
||||
private Integer phoneNumberIdentityRegistrationId;
|
||||
|
||||
@JsonProperty
|
||||
private long lastSeen;
|
||||
@@ -221,11 +222,22 @@ public class Device {
|
||||
return getId() == PRIMARY_ID;
|
||||
}
|
||||
|
||||
public int getRegistrationId(final IdentityType identityType) {
|
||||
return switch (identityType) {
|
||||
case ACI -> registrationId;
|
||||
case PNI -> phoneNumberIdentityRegistrationId;
|
||||
};
|
||||
/// Returns the registration ID for this device associated with its account's account identity.
|
||||
///
|
||||
/// @return the registration ID for this device associated with its account's account identity.
|
||||
public int getAccountRegistrationId() {
|
||||
return registrationId;
|
||||
}
|
||||
|
||||
/// Returns the registration ID for this device associated with its
|
||||
/// account's phone-number identity, or an empty Optional if the account
|
||||
/// does not have a phone number.
|
||||
///
|
||||
/// @return the registration ID for this device associated with its
|
||||
/// account's phone-number identity, or an empty Optional if the account
|
||||
/// does not have a phone number.
|
||||
public Optional<Integer> getPhoneNumberIdentityRegistrationId() {
|
||||
return Optional.ofNullable(phoneNumberIdentityRegistrationId);
|
||||
}
|
||||
|
||||
public void setRegistrationId(int registrationId) {
|
||||
|
||||
+2
-1
@@ -18,7 +18,8 @@ public enum DeviceCapability {
|
||||
ATTACHMENT_BACKFILL("attachmentBackfill", AccountCapabilityMode.PRIMARY_DEVICE, AccountCapabilityVisibility.SELF, false, false),
|
||||
SPARSE_POST_QUANTUM_RATCHET("spqr", AccountCapabilityMode.ALL_DEVICES, AccountCapabilityVisibility.PUBLIC, true, true),
|
||||
PROFILES_V2("profiles_v2", AccountCapabilityMode.ALL_DEVICES, AccountCapabilityVisibility.SELF, false, false),
|
||||
USERNAME_CHANGE_SYNC_MESSAGE("usernameChangeSyncMessage", AccountCapabilityMode.ALL_DEVICES, AccountCapabilityVisibility.SELF, true, false);
|
||||
USERNAME_CHANGE_SYNC_MESSAGE("usernameChangeSyncMessage", AccountCapabilityMode.ALL_DEVICES, AccountCapabilityVisibility.SELF, true, false),
|
||||
OPTIONAL_PHONE_NUMBER("optionalPhoneNumber", AccountCapabilityMode.ALL_DEVICES, AccountCapabilityVisibility.SERVER, false, false);
|
||||
|
||||
public static final List<DeviceCapability> PUBLIC_VISIBLE_CAPABILITIES = Arrays.stream(DeviceCapability.values())
|
||||
.filter(c -> c.accountCapabilityVisibility == AccountCapabilityVisibility.PUBLIC)
|
||||
|
||||
+11
@@ -0,0 +1,11 @@
|
||||
/*
|
||||
* Copyright 2026 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.storage;
|
||||
|
||||
import org.whispersystems.textsecuregcm.entities.ECSignedPreKey;
|
||||
import org.whispersystems.textsecuregcm.entities.KEMSignedPreKey;
|
||||
|
||||
public record DeviceIdentityInfo(int registrationId, ECSignedPreKey signedPreKey, KEMSignedPreKey pqLastResortPreKey) {}
|
||||
@@ -8,9 +8,7 @@ import java.util.Set;
|
||||
import org.signal.libsignal.protocol.IdentityKey;
|
||||
import org.whispersystems.textsecuregcm.auth.SaltedTokenHash;
|
||||
import org.whispersystems.textsecuregcm.entities.ApnRegistrationId;
|
||||
import org.whispersystems.textsecuregcm.entities.ECSignedPreKey;
|
||||
import org.whispersystems.textsecuregcm.entities.GcmRegistrationId;
|
||||
import org.whispersystems.textsecuregcm.entities.KEMSignedPreKey;
|
||||
import org.whispersystems.textsecuregcm.util.EncryptDeviceCreationTimestampUtil;
|
||||
import org.whispersystems.textsecuregcm.util.Util;
|
||||
|
||||
@@ -19,16 +17,12 @@ public record DeviceSpec(
|
||||
String password,
|
||||
String signalAgent,
|
||||
Set<DeviceCapability> capabilities,
|
||||
int aciRegistrationId,
|
||||
int pniRegistrationId,
|
||||
DeviceIdentityInfo aciInfo,
|
||||
Optional<DeviceIdentityInfo> pniInfo,
|
||||
boolean fetchesMessages,
|
||||
Optional<ApnRegistrationId> apnRegistrationId,
|
||||
Optional<GcmRegistrationId> gcmRegistrationId,
|
||||
ECSignedPreKey aciSignedPreKey,
|
||||
ECSignedPreKey pniSignedPreKey,
|
||||
KEMSignedPreKey aciPqLastResortPreKey,
|
||||
KEMSignedPreKey pniPqLastResortPreKey) {
|
||||
|
||||
Optional<GcmRegistrationId> gcmRegistrationId) {
|
||||
|
||||
public Device toDevice(final byte deviceId, final Clock clock, final IdentityKey aciIdentityKey) {
|
||||
final long created = clock.millis();
|
||||
|
||||
@@ -36,13 +30,13 @@ public record DeviceSpec(
|
||||
device.setId(deviceId);
|
||||
device.setAuthTokenHash(SaltedTokenHash.generateFor(password()));
|
||||
device.setFetchesMessages(fetchesMessages());
|
||||
device.setRegistrationId(aciRegistrationId());
|
||||
device.setPhoneNumberIdentityRegistrationId(pniRegistrationId());
|
||||
device.setRegistrationId(aciInfo.registrationId());
|
||||
pniInfo().ifPresent(pniInfo -> device.setPhoneNumberIdentityRegistrationId(pniInfo.registrationId()));
|
||||
device.setName(deviceNameCiphertext());
|
||||
device.setCapabilities(capabilities());
|
||||
device.setCreated(created);
|
||||
device.setCreatedAtCiphertext(
|
||||
EncryptDeviceCreationTimestampUtil.encrypt(created, aciIdentityKey, deviceId, aciRegistrationId()));
|
||||
EncryptDeviceCreationTimestampUtil.encrypt(created, aciIdentityKey, deviceId, aciInfo.registrationId()));
|
||||
device.setLastSeen(Util.todayInMillis());
|
||||
device.setUserAgent(signalAgent());
|
||||
|
||||
@@ -64,26 +58,21 @@ public record DeviceSpec(
|
||||
|
||||
final DeviceSpec that = (DeviceSpec) o;
|
||||
|
||||
return aciRegistrationId == that.aciRegistrationId
|
||||
&& pniRegistrationId == that.pniRegistrationId
|
||||
return Objects.equals(aciInfo, that.aciInfo)
|
||||
&& Objects.equals(pniInfo, that.pniInfo)
|
||||
&& fetchesMessages == that.fetchesMessages
|
||||
&& Arrays.equals(deviceNameCiphertext, that.deviceNameCiphertext)
|
||||
&& Objects.equals(password, that.password)
|
||||
&& Objects.equals(signalAgent, that.signalAgent)
|
||||
&& Objects.equals(capabilities, that.capabilities)
|
||||
&& Objects.equals(apnRegistrationId, that.apnRegistrationId)
|
||||
&& Objects.equals(gcmRegistrationId, that.gcmRegistrationId)
|
||||
&& Objects.equals(aciSignedPreKey, that.aciSignedPreKey)
|
||||
&& Objects.equals(pniSignedPreKey, that.pniSignedPreKey)
|
||||
&& Objects.equals(aciPqLastResortPreKey, that.aciPqLastResortPreKey)
|
||||
&& Objects.equals(pniPqLastResortPreKey, that.pniPqLastResortPreKey);
|
||||
&& Objects.equals(gcmRegistrationId, that.gcmRegistrationId);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
int result = Objects.hash(password, signalAgent, capabilities, aciRegistrationId, pniRegistrationId,
|
||||
fetchesMessages, apnRegistrationId, gcmRegistrationId, aciSignedPreKey, pniSignedPreKey, aciPqLastResortPreKey,
|
||||
pniPqLastResortPreKey);
|
||||
int result = Objects.hash(password, signalAgent, capabilities, aciInfo, pniInfo,
|
||||
fetchesMessages, apnRegistrationId, gcmRegistrationId);
|
||||
result = 31 * result + Arrays.hashCode(deviceNameCiphertext);
|
||||
return result;
|
||||
}
|
||||
|
||||
@@ -9,6 +9,7 @@ import com.google.common.annotations.VisibleForTesting;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import io.micrometer.core.instrument.Tag;
|
||||
import io.micrometer.core.instrument.Tags;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
@@ -61,32 +62,49 @@ public class KeysManager {
|
||||
return pqLastResortKeys.buildTransactWriteItemForInsertion(identifier, deviceId, lastResortSignedPreKey);
|
||||
}
|
||||
|
||||
@SuppressWarnings("OptionalUsedAsFieldOrParameterType")
|
||||
public List<TransactWriteItem> buildWriteItemsForNewDevice(final UUID accountIdentifier,
|
||||
final UUID phoneNumberIdentifier,
|
||||
final Optional<UUID> maybePhoneNumberIdentifier,
|
||||
final byte deviceId,
|
||||
final ECSignedPreKey aciSignedPreKey,
|
||||
final ECSignedPreKey pniSignedPreKey,
|
||||
final Optional<ECSignedPreKey> maybePniSignedPreKey,
|
||||
final KEMSignedPreKey aciPqLastResortPreKey,
|
||||
final KEMSignedPreKey pniLastResortPreKey) {
|
||||
final Optional<KEMSignedPreKey> maybePniPqLastResortPreKey) {
|
||||
final List<TransactWriteItem> writeItems = new ArrayList<>(buildWriteItemsForNewDevice(accountIdentifier, deviceId, aciSignedPreKey, aciPqLastResortPreKey));
|
||||
|
||||
maybePhoneNumberIdentifier.ifPresent(pni ->
|
||||
writeItems.addAll(buildWriteItemsForNewDevice(pni, deviceId,
|
||||
maybePniSignedPreKey.orElseThrow(() -> new AssertionError("PNI signed pre key must be provided if PNI is present")),
|
||||
maybePniPqLastResortPreKey.orElseThrow(() -> new AssertionError("PNI PQ last resort pre key must be provided if PNI is present")))
|
||||
));
|
||||
return writeItems;
|
||||
}
|
||||
|
||||
private List<TransactWriteItem> buildWriteItemsForNewDevice(final UUID identifier,
|
||||
final byte deviceId,
|
||||
final ECSignedPreKey signedPreKey,
|
||||
final KEMSignedPreKey lastResortPreKey) {
|
||||
return List.of(
|
||||
ecSignedPreKeys.buildTransactWriteItemForInsertion(accountIdentifier, deviceId, aciSignedPreKey),
|
||||
ecSignedPreKeys.buildTransactWriteItemForInsertion(phoneNumberIdentifier, deviceId, pniSignedPreKey),
|
||||
pqLastResortKeys.buildTransactWriteItemForInsertion(accountIdentifier, deviceId, aciPqLastResortPreKey),
|
||||
pqLastResortKeys.buildTransactWriteItemForInsertion(phoneNumberIdentifier, deviceId, pniLastResortPreKey)
|
||||
ecSignedPreKeys.buildTransactWriteItemForInsertion(identifier, deviceId, signedPreKey),
|
||||
pqLastResortKeys.buildTransactWriteItemForInsertion(identifier, deviceId, lastResortPreKey)
|
||||
);
|
||||
}
|
||||
|
||||
@SuppressWarnings("OptionalUsedAsFieldOrParameterType")
|
||||
public List<TransactWriteItem> buildWriteItemsForRemovedDevice(final UUID accountIdentifier,
|
||||
final UUID phoneNumberIdentifier,
|
||||
final Optional<UUID> maybePhoneNumberIdentifier,
|
||||
final byte deviceId) {
|
||||
|
||||
return List.of(
|
||||
final List<TransactWriteItem> writeItems = new ArrayList<>(List.of(
|
||||
ecSignedPreKeys.buildTransactWriteItemForDeletion(accountIdentifier, deviceId),
|
||||
pqLastResortKeys.buildTransactWriteItemForDeletion(accountIdentifier, deviceId)
|
||||
));
|
||||
|
||||
maybePhoneNumberIdentifier.ifPresent(phoneNumberIdentifier -> writeItems.addAll(List.of(
|
||||
ecSignedPreKeys.buildTransactWriteItemForDeletion(phoneNumberIdentifier, deviceId),
|
||||
pqLastResortKeys.buildTransactWriteItemForDeletion(accountIdentifier, deviceId),
|
||||
pqLastResortKeys.buildTransactWriteItemForDeletion(phoneNumberIdentifier, deviceId)
|
||||
pqLastResortKeys.buildTransactWriteItemForDeletion(phoneNumberIdentifier, deviceId)))
|
||||
);
|
||||
|
||||
return writeItems;
|
||||
}
|
||||
|
||||
public CompletableFuture<Void> storeEcSignedPreKeys(final UUID identifier, final byte deviceId,
|
||||
|
||||
+2
-2
@@ -249,7 +249,7 @@ public class MessagePersister implements Managed {
|
||||
.filter(e -> !(e instanceof MessagePersistenceException)))
|
||||
.onErrorResume(e -> {
|
||||
logger.warn("Failed to persist queue {}::{} ({}); will schedule for retry",
|
||||
account.getIdentifier(IdentityType.ACI), device.getId(), node.getUri().getHost(), e);
|
||||
account.getAccountIdentifier(), device.getId(), node.getUri().getHost(), e);
|
||||
|
||||
return Mono.empty();
|
||||
});
|
||||
@@ -331,7 +331,7 @@ public class MessagePersister implements Managed {
|
||||
}
|
||||
|
||||
private Mono<Void> trimQueue(final Account account, final Device device) {
|
||||
final UUID aci = account.getIdentifier(IdentityType.ACI);
|
||||
final UUID aci = account.getAccountIdentifier();
|
||||
final byte deviceId = device.getId();
|
||||
|
||||
final double extraRoomRatio = this.dynamicConfigurationManager.getConfiguration()
|
||||
|
||||
@@ -241,7 +241,7 @@ public class MessagesManager {
|
||||
final SealedSenderMultiRecipientMessage.Recipient recipient = serviceIdAndRecipient.getValue();
|
||||
final byte[] devices = recipient.getDevices();
|
||||
|
||||
return insertAsync(resolvedRecipients.get(recipient).getIdentifier(IdentityType.ACI),
|
||||
return insertAsync(resolvedRecipients.get(recipient).getAccountIdentifier(),
|
||||
IntStream.range(0, devices.length).mapToObj(i -> devices[i])
|
||||
.collect(Collectors.toMap(deviceId -> deviceId, _ -> prototypeMessage.toBuilder()
|
||||
.setContent(ByteString.copyFrom(multiRecipientMessage.messageForRecipient(serviceIdAndRecipient.getValue())))
|
||||
|
||||
+2
-2
@@ -245,10 +245,10 @@ public class PhoneNumberIdentifiers {
|
||||
}
|
||||
|
||||
CompletableFuture<Void> regeneratePhoneNumberIdentifierMappings(final Account account) {
|
||||
return account.getNumberOptional()
|
||||
return account.getNumber()
|
||||
.map(phoneNumber -> setPni(phoneNumber,
|
||||
Util.getAlternateForms(phoneNumber),
|
||||
account.getPhoneNumberIdentifierOptional()
|
||||
account.getPhoneNumberIdentifier()
|
||||
.orElseThrow(() -> new AssertionError("Account has a phone number, but no PNI")))
|
||||
.thenRun(Util.NOOP))
|
||||
.orElseGet(() -> CompletableFuture.completedFuture(null));
|
||||
|
||||
+7
-1
@@ -10,6 +10,7 @@ import static java.util.Objects.requireNonNull;
|
||||
import java.util.HexFormat;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import org.whispersystems.textsecuregcm.auth.SaltedTokenHash;
|
||||
import org.whispersystems.textsecuregcm.util.Pair;
|
||||
import software.amazon.awssdk.services.dynamodb.model.TransactWriteItem;
|
||||
@@ -24,9 +25,14 @@ public class PhoneNumberRecoveryPasswordsManager {
|
||||
|
||||
public boolean verify(final UUID phoneNumberIdentifier, final byte[] password) {
|
||||
return phoneNumberRecoveryPasswords.lookup(phoneNumberIdentifier)
|
||||
.filter(hash -> hash.verify(bytesToString(password))).isPresent();
|
||||
.filter(hash -> verify(hash, password)).isPresent();
|
||||
}
|
||||
|
||||
public static boolean verify(final SaltedTokenHash saltedTokenHash, final byte[] password) {
|
||||
return saltedTokenHash.verify(bytesToString(password));
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
public boolean store(final UUID phoneNumberIdentifier, final byte[] password) {
|
||||
final String token = bytesToString(password);
|
||||
final SaltedTokenHash tokenHash = SaltedTokenHash.generateFor(token);
|
||||
|
||||
@@ -29,9 +29,11 @@ import software.amazon.awssdk.services.dynamodb.model.DeleteItemRequest;
|
||||
import software.amazon.awssdk.services.dynamodb.model.GetItemRequest;
|
||||
import software.amazon.awssdk.services.dynamodb.model.GetItemResponse;
|
||||
import software.amazon.awssdk.services.dynamodb.model.QueryRequest;
|
||||
import software.amazon.awssdk.services.dynamodb.model.ReturnValue;
|
||||
import software.amazon.awssdk.services.dynamodb.model.TransactWriteItem;
|
||||
import software.amazon.awssdk.services.dynamodb.model.Update;
|
||||
import software.amazon.awssdk.services.dynamodb.model.UpdateItemRequest;
|
||||
import software.amazon.awssdk.services.dynamodb.model.UpdateItemResponse;
|
||||
|
||||
public class Profiles {
|
||||
|
||||
@@ -282,4 +284,28 @@ public class Profiles {
|
||||
.doOnError(ignored -> sample.stop(Metrics.timer(DELETE_PROFILES_TIMER_NAME, "outcome", "error")))
|
||||
.toFuture();
|
||||
}
|
||||
|
||||
/**
|
||||
* Upserts the avatar for a v1 profile
|
||||
*/
|
||||
public VersionedProfileV1 setAvatar(UUID accountIdentifier, String version, String avatar, byte[] commitment) {
|
||||
final UpdateItemResponse response = SET_PROFILES_TIMER.record(() ->
|
||||
dynamoDbClient.updateItem(UpdateItemRequest.builder()
|
||||
.tableName(tableName)
|
||||
.key(buildPrimaryKey(accountIdentifier, version))
|
||||
.updateExpression("SET #avatar = :avatar, #commitment = if_not_exists(#commitment, :commitment)")
|
||||
.expressionAttributeNames(Map.of(
|
||||
"#avatar", ATTR_AVATAR,
|
||||
"#commitment", ATTR_COMMITMENT
|
||||
))
|
||||
.expressionAttributeValues(Map.of(
|
||||
":avatar", AttributeValues.s(avatar),
|
||||
":commitment", AttributeValues.b(commitment)
|
||||
))
|
||||
.returnValues(ReturnValue.ALL_NEW)
|
||||
.build())
|
||||
);
|
||||
|
||||
return fromItem(response.attributes());
|
||||
}
|
||||
}
|
||||
@@ -338,4 +338,14 @@ public class ProfilesManager {
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public void setV1Avatar(UUID accountIdentifier, String version, String avatar, byte[] commitment) {
|
||||
ResilienceUtil.getGeneralRedisRetry(RETRY_NAME)
|
||||
.executeRunnable(() -> cacheCluster.withBinaryCluster(
|
||||
connection -> connection.sync().del(getCacheKeyV1(accountIdentifier))));
|
||||
|
||||
final VersionedProfileV1 versionedProfileV1 = profilesV1.setAvatar(accountIdentifier, version, avatar, commitment);
|
||||
|
||||
redisSet(accountIdentifier, null, versionedProfileV1);
|
||||
}
|
||||
}
|
||||
+12
@@ -0,0 +1,12 @@
|
||||
/*
|
||||
* Copyright 2025 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.storage;
|
||||
|
||||
import org.whispersystems.textsecuregcm.util.NoStackTraceException;
|
||||
|
||||
/// Indicates that a receipt credential has already been redeemed for the entitlement
|
||||
public class ReceiptAlreadyRedeemedException extends NoStackTraceException {
|
||||
}
|
||||
+80
-22
@@ -12,38 +12,43 @@ import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.UUID;
|
||||
import javax.annotation.Nonnull;
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import org.signal.libsignal.zkgroup.receipts.ReceiptSerial;
|
||||
import org.whispersystems.textsecuregcm.util.AttributeValues;
|
||||
import org.whispersystems.textsecuregcm.util.UUIDUtil;
|
||||
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
|
||||
import software.amazon.awssdk.services.dynamodb.model.AttributeValue;
|
||||
import software.amazon.awssdk.services.dynamodb.model.DeleteItemRequest;
|
||||
import software.amazon.awssdk.services.dynamodb.model.Put;
|
||||
import software.amazon.awssdk.services.dynamodb.model.ReturnValue;
|
||||
import software.amazon.awssdk.services.dynamodb.model.ReturnValuesOnConditionCheckFailure;
|
||||
import software.amazon.awssdk.services.dynamodb.model.TransactWriteItem;
|
||||
import software.amazon.awssdk.services.dynamodb.model.UpdateItemRequest;
|
||||
import software.amazon.awssdk.services.dynamodb.model.UpdateItemResponse;
|
||||
|
||||
public class RedeemedReceiptsManager {
|
||||
|
||||
public static final String KEY_SERIAL = "S";
|
||||
public static final String KEY_TTL = "E";
|
||||
public static final String KEY_RECEIPT_EXPIRATION = "G";
|
||||
public static final String KEY_RECEIPT_LEVEL = "L";
|
||||
public static final String KEY_ACCOUNT_UUID = "U";
|
||||
public static final String KEY_REDEMPTION_TIME = "R";
|
||||
public static final String ATTR_TTL = "E";
|
||||
public static final String ATTR_RECEIPT_EXPIRATION = "G";
|
||||
public static final String ATTR_RECEIPT_LEVEL = "L";
|
||||
public static final String ATTR_ACCOUNT_UUID = "U";
|
||||
public static final String ATTR_REDEMPTION_TIME = "R";
|
||||
|
||||
private final Clock clock;
|
||||
private final String table;
|
||||
private final DynamoDbClient client;
|
||||
private final Duration expirationTime;
|
||||
|
||||
@VisibleForTesting
|
||||
static final Duration TTL_PADDING = Duration.ofDays(30);
|
||||
|
||||
public RedeemedReceiptsManager(
|
||||
@Nonnull final Clock clock,
|
||||
@Nonnull final String table,
|
||||
@Nonnull final DynamoDbClient client,
|
||||
@Nonnull final Duration expirationTime) {
|
||||
@Nonnull final DynamoDbClient client) {
|
||||
this.clock = Objects.requireNonNull(clock);
|
||||
this.table = Objects.requireNonNull(table);
|
||||
this.client = Objects.requireNonNull(client);
|
||||
this.expirationTime = Objects.requireNonNull(expirationTime);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -53,7 +58,7 @@ public class RedeemedReceiptsManager {
|
||||
*/
|
||||
public boolean put(
|
||||
@Nonnull final ReceiptSerial receiptSerial,
|
||||
final long receiptExpiration,
|
||||
final Instant receiptExpiration,
|
||||
final long receiptLevel,
|
||||
@Nonnull final UUID accountUuid) {
|
||||
|
||||
@@ -62,7 +67,6 @@ public class RedeemedReceiptsManager {
|
||||
Objects.requireNonNull(accountUuid);
|
||||
|
||||
final Instant now = clock.instant();
|
||||
final Instant rowExpiration = now.plus(expirationTime);
|
||||
final AttributeValue serialAttributeValue = AttributeValues.b(receiptSerial.serialize());
|
||||
|
||||
final UpdateItemRequest updateItemRequest = UpdateItemRequest.builder()
|
||||
@@ -75,14 +79,14 @@ public class RedeemedReceiptsManager {
|
||||
+ "#account_uuid = if_not_exists(#account_uuid, :account_uuid), "
|
||||
+ "#redemption_time = if_not_exists(#redemption_time, :redemption_time)")
|
||||
.expressionAttributeNames(Map.of(
|
||||
"#ttl", KEY_TTL,
|
||||
"#receipt_expiration", KEY_RECEIPT_EXPIRATION,
|
||||
"#receipt_level", KEY_RECEIPT_LEVEL,
|
||||
"#account_uuid", KEY_ACCOUNT_UUID,
|
||||
"#redemption_time", KEY_REDEMPTION_TIME))
|
||||
"#ttl", ATTR_TTL,
|
||||
"#receipt_expiration", ATTR_RECEIPT_EXPIRATION,
|
||||
"#receipt_level", ATTR_RECEIPT_LEVEL,
|
||||
"#account_uuid", ATTR_ACCOUNT_UUID,
|
||||
"#redemption_time", ATTR_REDEMPTION_TIME))
|
||||
.expressionAttributeValues(Map.of(
|
||||
":ttl", AttributeValues.n(rowExpiration.getEpochSecond()),
|
||||
":receipt_expiration", AttributeValues.n(receiptExpiration),
|
||||
":ttl", rowTtl(receiptExpiration),
|
||||
":receipt_expiration", AttributeValues.n(receiptExpiration.getEpochSecond()),
|
||||
":receipt_level", AttributeValues.n(receiptLevel),
|
||||
":account_uuid", AttributeValues.b(accountUuid),
|
||||
":redemption_time", AttributeValues.n(now.getEpochSecond())))
|
||||
@@ -90,10 +94,64 @@ public class RedeemedReceiptsManager {
|
||||
final UpdateItemResponse updateItemResponse = client.updateItem(updateItemRequest);
|
||||
|
||||
final Map<String, AttributeValue> attributes = updateItemResponse.attributes();
|
||||
final long ddbReceiptExpiration = Long.parseLong(attributes.get(KEY_RECEIPT_EXPIRATION).n());
|
||||
final long ddbReceiptLevel = Long.parseLong(attributes.get(KEY_RECEIPT_LEVEL).n());
|
||||
final UUID ddbAccountUuid = UUIDUtil.fromByteBuffer(attributes.get(KEY_ACCOUNT_UUID).b().asByteBuffer());
|
||||
return ddbReceiptExpiration == receiptExpiration && ddbReceiptLevel == receiptLevel &&
|
||||
final long ddbReceiptExpiration = Long.parseLong(attributes.get(ATTR_RECEIPT_EXPIRATION).n());
|
||||
final long ddbReceiptLevel = Long.parseLong(attributes.get(ATTR_RECEIPT_LEVEL).n());
|
||||
final UUID ddbAccountUuid = UUIDUtil.fromByteBuffer(attributes.get(ATTR_ACCOUNT_UUID).b().asByteBuffer());
|
||||
return ddbReceiptExpiration == receiptExpiration.getEpochSecond() && ddbReceiptLevel == receiptLevel &&
|
||||
Objects.equals(ddbAccountUuid, accountUuid);
|
||||
}
|
||||
|
||||
/// Creates a [TransactWriteItem] that inserts the receipt into the redeemed receipts table if the receipt serial
|
||||
/// mapping for the specified accountUuid doesn't already exist. If a receipt serial mapping exists for another
|
||||
/// account, the enclosing transaction fails.
|
||||
///
|
||||
/// @param receiptSerial The receipt serial
|
||||
/// @param receiptExpiration The timestamp at which the receipt expires
|
||||
/// @param receiptLevel The receipt level indicating the type of entitlement
|
||||
/// @param accountUuid The account identifier
|
||||
public TransactWriteItem buildTransactWriteItemForReceipt(
|
||||
final ReceiptSerial receiptSerial,
|
||||
final Instant receiptExpiration,
|
||||
final long receiptLevel,
|
||||
final UUID accountUuid) {
|
||||
|
||||
return TransactWriteItem.builder()
|
||||
.put(Put.builder()
|
||||
.tableName(table)
|
||||
.item(Map.of(
|
||||
KEY_SERIAL, AttributeValues.b(receiptSerial.serialize()),
|
||||
ATTR_TTL, rowTtl(receiptExpiration),
|
||||
ATTR_RECEIPT_EXPIRATION, AttributeValues.n(receiptExpiration.getEpochSecond()),
|
||||
ATTR_RECEIPT_LEVEL, AttributeValues.n(receiptLevel),
|
||||
ATTR_ACCOUNT_UUID, AttributeValues.b(accountUuid),
|
||||
ATTR_REDEMPTION_TIME, AttributeValues.n(clock.instant().getEpochSecond())))
|
||||
.conditionExpression("attribute_not_exists(#serial) OR (#account_uuid = :account_uuid AND #receipt_level = :receipt_level)")
|
||||
.expressionAttributeNames(Map.of(
|
||||
"#serial", KEY_SERIAL,
|
||||
"#account_uuid", ATTR_ACCOUNT_UUID,
|
||||
"#receipt_level", ATTR_RECEIPT_LEVEL))
|
||||
.expressionAttributeValues(Map.of(
|
||||
":account_uuid", AttributeValues.b(accountUuid),
|
||||
":receipt_level", AttributeValues.n(receiptLevel)
|
||||
))
|
||||
.returnValuesOnConditionCheckFailure(ReturnValuesOnConditionCheckFailure.ALL_OLD)
|
||||
.build())
|
||||
.build();
|
||||
}
|
||||
|
||||
/// Deletes a receipt with the given receipt serial from the redeemed receipts table.
|
||||
/// This method is only intended for use by integration tests.
|
||||
///
|
||||
/// @param receiptSerial the receipt serial
|
||||
@VisibleForTesting
|
||||
public void deleteReceipt(final ReceiptSerial receiptSerial) {
|
||||
client.deleteItem(DeleteItemRequest.builder()
|
||||
.tableName(table)
|
||||
.key(Map.of(KEY_SERIAL, AttributeValues.b(receiptSerial.serialize())))
|
||||
.build());
|
||||
}
|
||||
|
||||
private static AttributeValue rowTtl(final Instant receiptExpiration) {
|
||||
return AttributeValues.n(receiptExpiration.plus(TTL_PADDING).getEpochSecond());
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -117,7 +117,7 @@ public class ReportMessageManager {
|
||||
return rateLimitCluster.withCluster(
|
||||
connection ->
|
||||
Math.max(
|
||||
account.getPhoneNumberIdentifierOptional().map(pni -> connection.sync().pfcount(getReportedSenderPniKey(pni)).intValue()).orElse(0),
|
||||
account.getPhoneNumberIdentifier().map(pni -> connection.sync().pfcount(getReportedSenderPniKey(pni)).intValue()).orElse(0),
|
||||
connection.sync().pfcount(getReportedSenderAciKey(account.getAccountIdentifier())).intValue()));
|
||||
} catch (final RedisException e) {
|
||||
return 0;
|
||||
|
||||
Loaded 100 of 234 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user