mirror of
https://github.com/signalapp/Signal-Server.git
synced 2026-11-30 01:06:50 +00:00
Compare commits
24
Commits
v20261117.0.0
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3ec51c1200 | ||
|
|
d0ef28cbfd | ||
|
|
cb8a3fb7d6 | ||
|
|
7ec705e616 | ||
|
|
9dfbb454d1 | ||
|
|
5de899da4b | ||
|
|
cbfc2720d5 | ||
|
|
0100901667 | ||
|
|
b3db95c3ea | ||
|
|
a9f87693ba | ||
|
|
b06709b63b | ||
|
|
99278dcd1f | ||
|
|
2d6eb7951a | ||
|
|
7e26b7fe0a | ||
|
|
2f955582a4 | ||
|
|
31bb5ff621 | ||
|
|
c21ad7a3aa | ||
|
|
4a48066d87 | ||
|
|
a0cdb5d3b6 | ||
|
|
3f1b678095 | ||
|
|
ffb821e344 | ||
|
|
d9bf32dd9c | ||
|
|
2fe70c89fa | ||
|
|
9d6589110e |
No files matched your search
@@ -28,7 +28,6 @@ updates:
|
||||
versions: [">=1.6.0"]
|
||||
|
||||
# Dependency convergence sentinels, pinned to specific versions
|
||||
- dependency-name: "tools.jackson.core:jackson-databind"
|
||||
- dependency-name: "com.squareup.okio:okio-jvm"
|
||||
|
||||
groups:
|
||||
|
||||
@@ -18,7 +18,7 @@ jobs:
|
||||
# setup-java requires gpg
|
||||
sudo apt-get install -y protobuf-compiler gpg
|
||||
pip install sabledocs
|
||||
- uses: actions/setup-java@77dd5b2ce225ea11469928ac317850245a74ae78 # v6.2.0
|
||||
- uses: actions/setup-java@d1374f8ac74474200d16ef8ecee22c7ae7a51880 # v6.3.0
|
||||
with:
|
||||
distribution: 'temurin'
|
||||
java-version-file: .java-version
|
||||
|
||||
@@ -25,7 +25,7 @@ jobs:
|
||||
# setup-java requires gpg
|
||||
sudo apt update
|
||||
sudo apt install -y gpg
|
||||
- uses: actions/setup-java@77dd5b2ce225ea11469928ac317850245a74ae78 # v6.2.0
|
||||
- uses: actions/setup-java@d1374f8ac74474200d16ef8ecee22c7ae7a51880 # v6.3.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@77dd5b2ce225ea11469928ac317850245a74ae78 # v6.2.0
|
||||
uses: actions/setup-java@d1374f8ac74474200d16ef8ecee22c7ae7a51880 # v6.3.0
|
||||
with:
|
||||
distribution: 'temurin'
|
||||
java-version-file: .java-version
|
||||
|
||||
@@ -8,6 +8,7 @@ package org.signal.integration;
|
||||
import static java.util.Objects.requireNonNull;
|
||||
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.google.common.io.Resources;
|
||||
import com.google.common.net.HttpHeaders;
|
||||
import com.webauthn4j.data.AuthenticatorAssertionResponse;
|
||||
@@ -56,6 +57,7 @@ import java.util.concurrent.ExecutionException;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.TimeoutException;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
import javax.annotation.Nullable;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.apache.commons.lang3.Validate;
|
||||
@@ -121,6 +123,8 @@ public final class Operations {
|
||||
|
||||
private static final FaultTolerantHttpClient CLIENT = buildClient();
|
||||
|
||||
private static final FaultTolerantHttpClient NO_RETRY_CLIENT = buildNoRetryClient();
|
||||
|
||||
private static final WebSocketClient WEB_SOCKET_CLIENT = buildWebSocketClient();
|
||||
|
||||
private static final ManagedChannel GRPC_CHANNEL = buildGrpcChannel();
|
||||
@@ -257,50 +261,66 @@ public final class Operations {
|
||||
Optional.empty()));
|
||||
|
||||
// we expect (and need) failure with status 441, which will contain the WebAuthn challenge
|
||||
final MfaFailureExceptionMapper.MfaFailureResponse mfaFailureResponse = apiPost("/v1/registration", initialRequest)
|
||||
MfaFailureExceptionMapper.MfaFailureResponse mfaFailureResponse = apiPost("/v1/registration", initialRequest)
|
||||
// For a numberless account recovery, the username is the ACI
|
||||
.authorized(testUser.aciUuid().toString(), testUser.accountPassword())
|
||||
.executeExpectStatusCode(441, MfaFailureExceptionMapper.MfaFailureResponse.class);
|
||||
|
||||
Validate.isTrue(mfaFailureResponse.webAuthnParameters().allowedCredentialIds()
|
||||
.stream()
|
||||
.anyMatch(allowedId -> Arrays.equals(allowedId, credentialId)),
|
||||
"Expected MFA failure to contain credentialId");
|
||||
// Retry a 441 to 3 times. It's possible we burned a challenge on a 500 that actually succeeded, but we didn't see
|
||||
// the response, so we can retry on the new challenge.
|
||||
int attempt = 0;
|
||||
while (true) {
|
||||
attempt++;
|
||||
Validate.isTrue(mfaFailureResponse.webAuthnParameters().allowedCredentialIds()
|
||||
.stream()
|
||||
.anyMatch(allowedId -> Arrays.equals(allowedId, credentialId)),
|
||||
"Expected MFA failure to contain credentialId");
|
||||
|
||||
final PublicKeyCredential<AuthenticatorAssertionResponse, ?> credential =
|
||||
clientPlatform.get(new PublicKeyCredentialRequestOptions(
|
||||
new DefaultChallenge(mfaFailureResponse.webAuthnParameters().challenge()),
|
||||
null,
|
||||
relyingPartyId,
|
||||
List.of(new PublicKeyCredentialDescriptor(PublicKeyCredentialType.PUBLIC_KEY, credentialId, null)),
|
||||
UserVerificationRequirement.DISCOURAGED,
|
||||
null));
|
||||
final PublicKeyCredential<AuthenticatorAssertionResponse, ?> credential =
|
||||
clientPlatform.get(new PublicKeyCredentialRequestOptions(
|
||||
new DefaultChallenge(mfaFailureResponse.webAuthnParameters().challenge()),
|
||||
null,
|
||||
relyingPartyId,
|
||||
List.of(new PublicKeyCredentialDescriptor(PublicKeyCredentialType.PUBLIC_KEY, credentialId, null)),
|
||||
UserVerificationRequirement.DISCOURAGED,
|
||||
null));
|
||||
|
||||
final RegistrationRequest registrationRequest = new RegistrationRequest(null,
|
||||
testUser.registrationPassword(),
|
||||
null,
|
||||
null,
|
||||
webAuthnVerificationResponseJson(credential),
|
||||
recoveredUser.accountAttributes(),
|
||||
true,
|
||||
new IdentityKey(aciIdentityKeyPair.getPublicKey()),
|
||||
new IdentityKey(pniIdentityKeyPair.getPublicKey()),
|
||||
new DeviceActivationRequest(generateSignedECPreKey(1, aciIdentityKeyPair),
|
||||
Optional.of(generateSignedECPreKey(2, pniIdentityKeyPair)),
|
||||
generateSignedKEMPreKey(3, aciIdentityKeyPair),
|
||||
Optional.of(generateSignedKEMPreKey(4, pniIdentityKeyPair)),
|
||||
Optional.empty(),
|
||||
Optional.empty()));
|
||||
final RegistrationRequest registrationRequest = new RegistrationRequest(null,
|
||||
testUser.registrationPassword(),
|
||||
null,
|
||||
null,
|
||||
webAuthnVerificationResponseJson(credential),
|
||||
recoveredUser.accountAttributes(),
|
||||
true,
|
||||
new IdentityKey(aciIdentityKeyPair.getPublicKey()),
|
||||
new IdentityKey(pniIdentityKeyPair.getPublicKey()),
|
||||
new DeviceActivationRequest(generateSignedECPreKey(1, aciIdentityKeyPair),
|
||||
Optional.of(generateSignedECPreKey(2, pniIdentityKeyPair)),
|
||||
generateSignedKEMPreKey(3, aciIdentityKeyPair),
|
||||
Optional.of(generateSignedKEMPreKey(4, pniIdentityKeyPair)),
|
||||
Optional.empty(),
|
||||
Optional.empty()));
|
||||
|
||||
final AccountIdentityResponse registrationResponse = apiPost("/v1/registration", registrationRequest)
|
||||
// For a numberless account recovery, the username is the ACI
|
||||
.authorized(testUser.aciUuid().toString(), testUser.accountPassword())
|
||||
.executeExpectSuccess(AccountIdentityResponse.class);
|
||||
final Pair<Integer, JsonNode> registrationResponse = apiPost("/v1/registration", registrationRequest)
|
||||
// For a numberless account recovery, the username is the ACI
|
||||
.authorized(testUser.aciUuid().toString(), testUser.accountPassword())
|
||||
.execute(JsonNode.class);
|
||||
|
||||
recoveredUser.setAciUuid(registrationResponse.uuid());
|
||||
return recoveredUser;
|
||||
if (registrationResponse.getLeft() == 441 && attempt < 3) {
|
||||
mfaFailureResponse = SystemMapper.jsonMapper()
|
||||
.convertValue(registrationResponse.getRight(), MfaFailureExceptionMapper.MfaFailureResponse.class);
|
||||
continue;
|
||||
}
|
||||
|
||||
Validate.isTrue(HttpUtils.isSuccessfulResponse(registrationResponse.getLeft()),
|
||||
"Unexpected response code: %d, body: %s", registrationResponse.getLeft(), registrationResponse.getRight());
|
||||
recoveredUser.setAciUuid(SystemMapper.jsonMapper()
|
||||
.convertValue(registrationResponse.getRight(), AccountIdentityResponse.class).uuid());
|
||||
return recoveredUser;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public static TestUser newRegisteredUser(final String number) {
|
||||
final byte[] registrationPassword = populateRandomRecoveryPassword(number);
|
||||
final String accountPassword = Base64.getEncoder().encodeToString(randomBytes(32));
|
||||
@@ -347,7 +367,24 @@ public final class Operations {
|
||||
}
|
||||
|
||||
public static void deleteUser(final TestUser user) {
|
||||
apiDelete("/v1/accounts/me").authorized(user).executeExpectSuccess();
|
||||
final AtomicInteger attempts = new AtomicInteger();
|
||||
final Retry retry = Retry.of("integration-test-delete-user",
|
||||
new RetryConfiguration().<Integer>toRetryConfigBuilder()
|
||||
.retryOnResult(statusCode -> statusCode >= 500)
|
||||
.build());
|
||||
final int statusCode = retry.executeSupplier(() -> {
|
||||
attempts.incrementAndGet();
|
||||
return apiDelete("/v1/accounts/me")
|
||||
.authorized(user)
|
||||
// disable retries, since this endpoint is not idempotent
|
||||
.withoutRetries()
|
||||
.execute()
|
||||
.getLeft();
|
||||
});
|
||||
|
||||
// If we had to retry a 500 where the account was already deleted, we would fail authorization
|
||||
Validate.isTrue(HttpUtils.isSuccessfulResponse(statusCode) || (attempts.get() > 1 && statusCode == 401),
|
||||
"Unexpected response code: %d", statusCode);
|
||||
}
|
||||
|
||||
public static String peekVerificationSessionPushChallenge(final String sessionId) {
|
||||
@@ -486,6 +523,7 @@ public final class Operations {
|
||||
|
||||
private final List<String> queryParams = new ArrayList<>();
|
||||
|
||||
private boolean retryServerErrors = true;
|
||||
|
||||
private RequestBuilder(final HttpRequest.Builder builder, final String endpoint) {
|
||||
this.builder = builder;
|
||||
@@ -523,6 +561,12 @@ public final class Operations {
|
||||
return this;
|
||||
}
|
||||
|
||||
/// Don't automatically retry 5xx responses, for requests that aren't safe to blindly retry
|
||||
public RequestBuilder withoutRetries() {
|
||||
retryServerErrors = false;
|
||||
return this;
|
||||
}
|
||||
|
||||
public Pair<Integer, Void> execute() {
|
||||
return execute(Void.class);
|
||||
}
|
||||
@@ -572,7 +616,8 @@ public final class Operations {
|
||||
private RawResponse executeRaw() {
|
||||
builder.uri(serverUri(endpoint, queryParams))
|
||||
.header(HttpHeaders.USER_AGENT, USER_AGENT);
|
||||
return CLIENT.sendAsync(builder.build(), HttpResponse.BodyHandlers.ofString(StandardCharsets.UTF_8))
|
||||
return (retryServerErrors ? CLIENT : NO_RETRY_CLIENT)
|
||||
.sendAsync(builder.build(), HttpResponse.BodyHandlers.ofString(StandardCharsets.UTF_8))
|
||||
.whenComplete((response, error) -> {
|
||||
if (error != null) {
|
||||
logger.error("request error", error);
|
||||
@@ -615,6 +660,16 @@ public final class Operations {
|
||||
}
|
||||
}
|
||||
|
||||
private static FaultTolerantHttpClient buildNoRetryClient() {
|
||||
try {
|
||||
return FaultTolerantHttpClient.newBuilder("integration-test-no-retry", Executors.newFixedThreadPool(16))
|
||||
.withTrustedServerCertificates(CONFIG.rootCerts().toArray(String[]::new))
|
||||
.build();
|
||||
} catch (final CertificateException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
|
||||
private static WebSocketClient buildWebSocketClient() {
|
||||
try {
|
||||
final KeyStore trustStore = CertificateUtil.buildKeyStoreForPem(CONFIG.rootCerts().toArray(String[]::new));
|
||||
|
||||
@@ -66,6 +66,7 @@ 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.signal.libsignal.zkgroup.internal.ByteArray;
|
||||
import org.whispersystems.textsecuregcm.entities.AccountIdentifierResponse;
|
||||
import org.whispersystems.textsecuregcm.entities.AccountIdentityResponse;
|
||||
import org.whispersystems.textsecuregcm.entities.ChangeNumberRequest;
|
||||
@@ -289,7 +290,10 @@ public class AccountTest {
|
||||
|
||||
// reserve a username
|
||||
final ReserveUsernameHashRequest reserveUsernameHashRequest = new ReserveUsernameHashRequest(
|
||||
candidates.stream().map(Username::getHash).toList());
|
||||
candidates.stream()
|
||||
.map(Username::getHash)
|
||||
.map(ByteArray::serialize)
|
||||
.toList());
|
||||
// try unauthorized
|
||||
Operations
|
||||
.apiPut("/v1/accounts/username_hash/reserve", reserveUsernameHashRequest)
|
||||
@@ -303,13 +307,13 @@ public class AccountTest {
|
||||
// find which one is the reserved username
|
||||
final byte[] reservedHash = reserveUsernameHashResponse.usernameHash();
|
||||
final Username reservedUsername = candidates.stream()
|
||||
.filter(u -> Arrays.equals(u.getHash(), reservedHash))
|
||||
.filter(u -> Arrays.equals(u.getHash().serialize(), reservedHash))
|
||||
.findAny()
|
||||
.orElseThrow();
|
||||
|
||||
// confirm a username
|
||||
final ConfirmUsernameHashRequest confirmUsernameHashRequest = new ConfirmUsernameHashRequest(
|
||||
reservedUsername.getHash(),
|
||||
reservedUsername.getHash().serialize(),
|
||||
reservedUsername.generateProof(),
|
||||
"cluck cluck i'm a parrot".getBytes()
|
||||
);
|
||||
|
||||
@@ -6,6 +6,7 @@
|
||||
package org.signal.integration;
|
||||
|
||||
import io.micrometer.common.util.StringUtils;
|
||||
import org.apache.commons.lang3.tuple.Pair;
|
||||
import org.junit.jupiter.api.Assertions;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.whispersystems.textsecuregcm.entities.CreateVerificationSessionRequest;
|
||||
@@ -54,8 +55,13 @@ public class RegistrationTest {
|
||||
// verify code
|
||||
final SubmitVerificationCodeRequest submitVerificationCodeRequest = new SubmitVerificationCodeRequest(
|
||||
params.verificationCode());
|
||||
final VerificationSessionResponse codeVerified = Operations
|
||||
final Pair<Integer, VerificationSessionResponse> codeVerified = Operations
|
||||
.apiPut("/v1/verification/session/%s/code".formatted(sessionId), submitVerificationCodeRequest)
|
||||
.executeExpectSuccess(VerificationSessionResponse.class);
|
||||
.execute(VerificationSessionResponse.class);
|
||||
|
||||
// If we succeeded but then retried a 500, we might have submitted a code when we were already verified
|
||||
Assertions.assertTrue(codeVerified.getLeft() == 200 || codeVerified.getLeft() == 409,
|
||||
"Unexpected response code: " + codeVerified.getLeft());
|
||||
Assertions.assertTrue(codeVerified.getRight().verified());
|
||||
}
|
||||
}
|
||||
@@ -45,12 +45,12 @@
|
||||
</modules>
|
||||
|
||||
<properties>
|
||||
<aws.sdk2.version>2.57.6</aws.sdk2.version>
|
||||
<braintree.version>3.55.1</braintree.version>
|
||||
<aws.sdk2.version>2.59.1</aws.sdk2.version>
|
||||
<braintree.version>3.56.0</braintree.version>
|
||||
<!-- Weird stuff happens with parameter annotation counts under Java 27 with versions of Byte Buddy older than
|
||||
1.18.9, so we need to pull in a newer version than we'd get via Dropwizard -> Mockito -> Byte Buddy. We can drop
|
||||
this when Dropwizard updates and pulls in a newer version of Byte Buddy. -->
|
||||
<byte-buddy.version>1.18.16-jdk5</byte-buddy.version>
|
||||
<byte-buddy.version>1.18.17-jdk5</byte-buddy.version>
|
||||
<commons-csv.version>1.14.1</commons-csv.version>
|
||||
<commons-io.version>2.22.0</commons-io.version>
|
||||
<dropwizard.version>5.0.2</dropwizard.version>
|
||||
@@ -59,12 +59,12 @@
|
||||
<foundationdb.version>7.3.76</foundationdb.version>
|
||||
<foundationdb.api-version>730</foundationdb.api-version>
|
||||
<foundationdb.client-library-sha256>af099848721d08904ff9e5d38fade0de24d92e86451ea491d9ab5ce84adcf62a</foundationdb.client-library-sha256>
|
||||
<google-cloud-libraries.version>26.91.0</google-cloud-libraries.version>
|
||||
<google-cloud-libraries.version>26.93.0</google-cloud-libraries.version>
|
||||
<grpc.version>1.76.3</grpc.version> <!-- should be kept in sync with the value from Google libraries-bom -->
|
||||
<guava.version>33.7.2-jre</guava.version>
|
||||
<guava.version>33.8.0-jre</guava.version>
|
||||
<!-- several libraries (AWS, Google Cloud) use Apache httpclient transitively, and we need to align them -->
|
||||
<httpclient.version>4.5.14</httpclient.version>
|
||||
<jackson.version>2.22.4</jackson.version>
|
||||
<jackson.version>2.23.0</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>
|
||||
@@ -74,8 +74,7 @@
|
||||
<logback.version>1.5.38</logback.version>
|
||||
<logback-access-common.version>2.0.15</logback-access-common.version>
|
||||
<lettuce.version>7.9.0.RELEASE</lettuce.version>
|
||||
<libphonenumber.version>9.0.42</libphonenumber.version>
|
||||
<logstash.logback.version>9.0</logstash.logback.version>
|
||||
<libphonenumber.version>9.0.43</libphonenumber.version>
|
||||
<log4j-bom.version>2.26.1</log4j-bom.version>
|
||||
<luajava.version>4.1.0</luajava.version>
|
||||
<micrometer.version>1.17.2</micrometer.version>
|
||||
@@ -91,12 +90,12 @@
|
||||
<reactor-bom.version>2025.0.8</reactor-bom.version> <!-- 3.8.4, see https://github.com/reactor/reactor#bom-versioning-scheme -->
|
||||
<resilience4j.version>2.4.0</resilience4j.version>
|
||||
<semver4j.version>3.1.0</semver4j.version>
|
||||
<simple-grpc.version>0.2.1</simple-grpc.version>
|
||||
<simple-grpc.version>0.3.0</simple-grpc.version>
|
||||
<slf4j.version>2.0.20</slf4j.version>
|
||||
<stripe.version>33.4.2</stripe.version>
|
||||
<stripe.version>34.1.0</stripe.version>
|
||||
<swagger.version>2.2.55</swagger.version>
|
||||
<testcontainers.version>2.0.5</testcontainers.version>
|
||||
<webauthn4j.version>0.31.11.RELEASE</webauthn4j.version>
|
||||
<webauthn4j.version>0.32.0.RELEASE</webauthn4j.version>
|
||||
|
||||
<!-- Images to use in tests via testcontainers. See also: prepull-testcontainers-images <profile> -->
|
||||
<dynamodb.image>amazon/dynamodb-local:3.3.1@sha256:ff89bd48ff32cd8d9be5fee8873b65b8854dc408f1afe881be6eb00247bc0dab</dynamodb.image>
|
||||
@@ -267,11 +266,6 @@
|
||||
<artifactId>lettuce-core</artifactId>
|
||||
<version>${lettuce.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>net.logstash.logback</groupId>
|
||||
<artifactId>logstash-logback-encoder</artifactId>
|
||||
<version>${logstash.logback.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
<artifactId>commons-csv</artifactId>
|
||||
@@ -327,7 +321,7 @@
|
||||
<dependency>
|
||||
<groupId>org.signal</groupId>
|
||||
<artifactId>libsignal-server</artifactId>
|
||||
<version>0.106.1</version>
|
||||
<version>0.108.0</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.signal</groupId>
|
||||
@@ -529,12 +523,12 @@
|
||||
<plugin>
|
||||
<groupId>org.codehaus.mojo</groupId>
|
||||
<artifactId>exec-maven-plugin</artifactId>
|
||||
<version>3.6.4</version>
|
||||
<version>3.7.0</version>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.codehaus.mojo</groupId>
|
||||
<artifactId>properties-maven-plugin</artifactId>
|
||||
<version>1.3.1</version>
|
||||
<version>1.4.0</version>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</pluginManagement>
|
||||
|
||||
+3
-22
@@ -14,8 +14,8 @@
|
||||
<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.5.0</dynamodb-lock-client.version>
|
||||
<firebase-admin.version>9.11.0</firebase-admin.version>
|
||||
<libphonenumber-geocoder.version>3.42</libphonenumber-geocoder.version>
|
||||
<firebase-admin.version>9.12.0</firebase-admin.version>
|
||||
<libphonenumber-geocoder.version>3.43</libphonenumber-geocoder.version>
|
||||
<google-androidpublisher.version>v3-rev20250904-2.0.0</google-androidpublisher.version>
|
||||
<java-jwt.version>4.6.2</java-jwt.version>
|
||||
<java-uuid-generator.version>5.2.0</java-uuid-generator.version>
|
||||
@@ -177,25 +177,6 @@
|
||||
<groupId>ch.qos.logback</groupId>
|
||||
<artifactId>logback-classic</artifactId>
|
||||
</dependency>
|
||||
<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.3</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>io.dropwizard.metrics</groupId>
|
||||
<artifactId>metrics-core</artifactId>
|
||||
@@ -875,7 +856,7 @@
|
||||
<plugin>
|
||||
<groupId>org.codehaus.mojo</groupId>
|
||||
<artifactId>templating-maven-plugin</artifactId>
|
||||
<version>3.1.1</version>
|
||||
<version>3.2.0</version>
|
||||
<executions>
|
||||
<execution>
|
||||
<id>filter-src</id>
|
||||
|
||||
+2
-1
@@ -40,6 +40,7 @@ import javax.annotation.Nullable;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.glassfish.jersey.server.ManagedAsync;
|
||||
import org.signal.libsignal.usernames.BaseUsernameException;
|
||||
import org.signal.libsignal.zkgroup.InvalidInputException;
|
||||
import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
|
||||
import org.whispersystems.textsecuregcm.auth.SaltedTokenHash;
|
||||
import org.whispersystems.textsecuregcm.entities.AccountAttributes;
|
||||
@@ -356,7 +357,7 @@ public class AccountController {
|
||||
|
||||
try {
|
||||
usernameHashZkProofVerifier.verifyProof(confirmRequest.zkProof(), confirmRequest.usernameHash());
|
||||
} catch (final BaseUsernameException e) {
|
||||
} catch (final BaseUsernameException | InvalidInputException e) {
|
||||
throw new WebApplicationException(Response.status(422).build());
|
||||
}
|
||||
|
||||
|
||||
-5
@@ -168,7 +168,6 @@ public class ProfileController {
|
||||
@ApiResponse(responseCode = "400", description = "Invalid create profile request.")
|
||||
@ApiResponse(responseCode = "401", description = "Account authentication check failed.")
|
||||
@ApiResponse(responseCode = "403", description = "The request contained a payment address, but payments are not supported in the region of the account’s phone number or the caller's ASN if the account does not have a phone number.")
|
||||
@ApiResponse(responseCode = "412", description = "The requesting account has the profiles_v2 capability")
|
||||
@ApiResponse(responseCode = "422", description = "Invalid request format")
|
||||
@ManagedAsync
|
||||
public Response setProfile(@Auth AuthenticatedDevice auth,
|
||||
@@ -178,10 +177,6 @@ public class ProfileController {
|
||||
final Account account = accountsManager.getByAccountIdentifier(auth.accountIdentifier())
|
||||
.orElseThrow(() -> new WebApplicationException(Response.Status.UNAUTHORIZED));
|
||||
|
||||
if (account.hasCapability(DeviceCapability.PROFILES_V2)) {
|
||||
return Response.status(Response.Status.PRECONDITION_FAILED).build();
|
||||
}
|
||||
|
||||
final Optional<VersionedProfileV1> currentProfile =
|
||||
profilesManager.getV1(auth.accountIdentifier(), request.version());
|
||||
|
||||
|
||||
+1
-1
@@ -263,7 +263,7 @@ public class AccountsGrpcService extends SimpleAccountsGrpc.AccountsImplBase {
|
||||
|
||||
try {
|
||||
usernameHashZkProofVerifier.verifyProof(request.getZkProof().toByteArray(), request.getUsernameHash().toByteArray());
|
||||
} catch (final BaseUsernameException e) {
|
||||
} catch (final BaseUsernameException | InvalidInputException e) {
|
||||
throw GrpcExceptions.invalidArguments("Could not verify proof");
|
||||
}
|
||||
|
||||
|
||||
+6
-2
@@ -18,9 +18,11 @@ public class DeviceCapabilityUtil {
|
||||
case DEVICE_CAPABILITY_TRANSFER -> DeviceCapability.TRANSFER;
|
||||
case DEVICE_CAPABILITY_ATTACHMENT_BACKFILL -> DeviceCapability.ATTACHMENT_BACKFILL;
|
||||
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_REPLY_PRIVATELY -> DeviceCapability.REPLY_PRIVATELY;
|
||||
case DEVICE_CAPABILITY_CONTACT_DELETE -> DeviceCapability.CONTACT_DELETE;
|
||||
case DEVICE_CAPABILITY_ADMIN_REMOVE_AND_DELETE -> DeviceCapability.ADMIN_REMOVE_AND_DELETE;
|
||||
case DEVICE_CAPABILITY_UNSPECIFIED, UNRECOGNIZED ->
|
||||
throw GrpcExceptions.invalidArguments("unrecognized device capability");
|
||||
};
|
||||
@@ -32,9 +34,11 @@ public class DeviceCapabilityUtil {
|
||||
case TRANSFER -> org.signal.chat.common.DeviceCapability.DEVICE_CAPABILITY_TRANSFER;
|
||||
case ATTACHMENT_BACKFILL -> org.signal.chat.common.DeviceCapability.DEVICE_CAPABILITY_ATTACHMENT_BACKFILL;
|
||||
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;
|
||||
case REPLY_PRIVATELY -> org.signal.chat.common.DeviceCapability.DEVICE_CAPABILITY_REPLY_PRIVATELY;
|
||||
case CONTACT_DELETE -> org.signal.chat.common.DeviceCapability.DEVICE_CAPABILITY_CONTACT_DELETE;
|
||||
case ADMIN_REMOVE_AND_DELETE -> org.signal.chat.common.DeviceCapability.DEVICE_CAPABILITY_ADMIN_REMOVE_AND_DELETE;
|
||||
};
|
||||
}
|
||||
}
|
||||
+13
-8
@@ -6,6 +6,7 @@
|
||||
package org.whispersystems.textsecuregcm.grpc;
|
||||
|
||||
import com.google.protobuf.ByteString;
|
||||
import com.google.protobuf.Empty;
|
||||
import java.security.MessageDigest;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import java.time.Clock;
|
||||
@@ -33,6 +34,8 @@ import reactor.util.function.Tuples;
|
||||
|
||||
public class KeysAnonymousGrpcService extends SimpleKeysAnonymousGrpc.KeysAnonymousImplBase {
|
||||
|
||||
private static final int CHECK_KEYS_MAX_CONCURRENCY = 16;
|
||||
|
||||
private final AccountsManager accountsManager;
|
||||
private final KeysManager keysManager;
|
||||
private final GroupSendTokenUtil groupSendTokenUtil;
|
||||
@@ -99,20 +102,22 @@ public class KeysAnonymousGrpcService extends SimpleKeysAnonymousGrpc.KeysAnonym
|
||||
return JdkFlowAdapter.publisherToFlowPublisher(JdkFlowAdapter.flowPublisherToFlux(requests)
|
||||
.map(request -> Tuples.of(GrpcServiceIdentifierUtil.fromGrpcServiceIdentifier(request.getTargetIdentifier()),
|
||||
request.getFingerprint().toByteArray()))
|
||||
.flatMap(serviceIdentifierAndFingerprint -> Mono.fromFuture(
|
||||
.flatMapSequential(serviceIdentifierAndFingerprint -> Mono.fromFuture(
|
||||
() -> accountsManager.getByServiceIdentifierAsync(serviceIdentifierAndFingerprint.getT1()))
|
||||
.map(maybeAccount -> maybeAccount.flatMap(
|
||||
account -> switch (serviceIdentifierAndFingerprint.getT1().identityType()) {
|
||||
case ACI -> Optional.of(account.getAccountIdentityKey());
|
||||
case PNI -> account.getPhoneNumberIdentityKey();
|
||||
}))
|
||||
.flatMap(Mono::justOrEmpty)
|
||||
.filter(identityKey -> !fingerprintMatches(identityKey, serviceIdentifierAndFingerprint.getT2()))
|
||||
.map(identityKey -> CheckIdentityKeyResponse.newBuilder()
|
||||
.setTargetIdentifier(
|
||||
GrpcServiceIdentifierUtil.toGrpcServiceIdentifier(serviceIdentifierAndFingerprint.getT1()))
|
||||
.setIdentityKey(ByteString.copyFrom(identityKey.serialize()))
|
||||
.build())));
|
||||
.map(maybeIdentityKey -> {
|
||||
final CheckIdentityKeyResponse.Builder builder = CheckIdentityKeyResponse.newBuilder();
|
||||
|
||||
return maybeIdentityKey.map(identityKey ->
|
||||
fingerprintMatches(identityKey, serviceIdentifierAndFingerprint.getT2())
|
||||
? builder.setMatched(Empty.getDefaultInstance()).build()
|
||||
: builder.setIdentityKey(ByteString.copyFrom(identityKey.serialize())).build())
|
||||
.orElseGet(() -> builder.setTargetNotFound(NotFound.getDefaultInstance()).build());
|
||||
}), CHECK_KEYS_MAX_CONCURRENCY));
|
||||
}
|
||||
|
||||
private static boolean fingerprintMatches(final IdentityKey identityKey, final byte[] fingerprint) {
|
||||
|
||||
@@ -8,10 +8,10 @@ import com.google.common.annotations.VisibleForTesting;
|
||||
import com.google.protobuf.Empty;
|
||||
import io.grpc.StatusRuntimeException;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
|
||||
import java.time.Clock;
|
||||
import java.time.Duration;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
import javax.annotation.Nullable;
|
||||
import org.signal.chat.messages.GetMessagesResponse;
|
||||
import org.signal.chat.messages.GetMessagesStreamClosed;
|
||||
@@ -48,7 +48,8 @@ public class MessageDispatcher {
|
||||
private static final Logger log = LoggerFactory.getLogger(MessageDispatcher.class);
|
||||
|
||||
@VisibleForTesting
|
||||
static final int MAX_UNACKED_MESSAGES = 256;
|
||||
static final int DEFAULT_MAX_UNACKED_MESSAGES = 256;
|
||||
|
||||
@VisibleForTesting
|
||||
static final Duration CLOSE_WITH_PENDING_MESSAGES_NOTIFICATION_DELAY = Duration.ofMinutes(1);
|
||||
private static final int MESSAGE_PUBLISHER_LIMIT_RATE = 100;
|
||||
@@ -133,10 +134,21 @@ public class MessageDispatcher {
|
||||
|
||||
pushNotificationManager.handleMessagesRetrieved(account, device, userAgentString);
|
||||
|
||||
final Flux<GetMessagesResponse> messages = JdkFlowAdapter.flowPublisherToFlux(messageStream.getMessages())
|
||||
.name(SEND_MESSAGES_FLUX_NAME)
|
||||
.tap(Micrometer.metrics(Metrics.globalRegistry))
|
||||
.limitRate(MESSAGE_PUBLISHER_LIMIT_RATE)
|
||||
final AtomicInteger maxUnacknowledgedMessages = new AtomicInteger(DEFAULT_MAX_UNACKED_MESSAGES);
|
||||
|
||||
final Flux<GetMessagesResponse> messages = Mono.fromFuture(() -> messagesManager.hasSuspectedDeliveryLoop(account.getAccountIdentifier(), device.getId()))
|
||||
.flatMapMany(hasSuspectedDeliveryLoop -> {
|
||||
if (hasSuspectedDeliveryLoop) {
|
||||
maxUnacknowledgedMessages.set(1);
|
||||
MessageMetrics.recordSuspectedDeliveryLoop(MessageMetrics.GRPC_CHANNEL, userAgent, clientReleaseManager);
|
||||
}
|
||||
|
||||
return JdkFlowAdapter.flowPublisherToFlux(messageStream.getMessages())
|
||||
.name(SEND_MESSAGES_FLUX_NAME)
|
||||
.tag("hasSuspectedDeliveryLoop", String.valueOf(hasSuspectedDeliveryLoop))
|
||||
.tap(Micrometer.metrics(Metrics.globalRegistry))
|
||||
.limitRate(maxUnacknowledgedMessages.get());
|
||||
})
|
||||
.flatMapSequential(entry -> switch (entry) {
|
||||
case MessageStreamEntry.Envelope(final MessageProtos.Envelope envelope) -> {
|
||||
final UUID serverGuid = UUIDUtil.fromByteString(envelope.getServerGuid());
|
||||
@@ -156,7 +168,7 @@ public class MessageDispatcher {
|
||||
pendingAcknowledgementTracker.markEndOfQueue();
|
||||
yield Mono.empty();
|
||||
}
|
||||
}, MAX_UNACKED_MESSAGES)
|
||||
}, maxUnacknowledgedMessages.get())
|
||||
.onErrorMap(ConflictingMessageConsumerException.class, _ -> {
|
||||
messageMetrics.measureMessageStreamDisplaced(MessageMetrics.GRPC_CHANNEL, userAgent, true);
|
||||
return CONFLICTING_STREAM_EXCEPTION;
|
||||
@@ -165,7 +177,7 @@ public class MessageDispatcher {
|
||||
// Only emit envelopes when the permit flux emits a value. Initially it is seeded MAX_UNACKED_MESSAGES permits,
|
||||
// after that a permit is emitted every time we receive an ack.
|
||||
final Sinks.Many<Boolean> ackPermits = Sinks.many().unicast().onBackpressureBuffer();
|
||||
final Flux<Boolean> permits = Flux.range(0, MAX_UNACKED_MESSAGES)
|
||||
final Flux<Boolean> permits = Flux.range(0, maxUnacknowledgedMessages.get())
|
||||
.map(_ -> true)
|
||||
.concatWith(ackPermits.asFlux());
|
||||
final Mono<GetMessagesResponse> ackCompletions = acknowledgedMessageGuids
|
||||
@@ -185,7 +197,7 @@ public class MessageDispatcher {
|
||||
.doOnSuccess(_ -> unacked.handleMessageAcknowledged())
|
||||
// Just have to emit some value that indicates we can release a permit
|
||||
.thenReturn(true);
|
||||
}, MAX_UNACKED_MESSAGES)
|
||||
}, maxUnacknowledgedMessages.get())
|
||||
.doOnNext(_ -> ackPermits.tryEmitNext(true))
|
||||
.ignoreElements()
|
||||
.cast(GetMessagesResponse.class);
|
||||
|
||||
@@ -33,7 +33,6 @@ import org.whispersystems.textsecuregcm.auth.UnidentifiedAccessChecksum;
|
||||
import org.whispersystems.textsecuregcm.badges.ProfileBadgeConverter;
|
||||
import org.whispersystems.textsecuregcm.s3.PostPolicyGenerator;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.DeviceCapability;
|
||||
import org.whispersystems.textsecuregcm.storage.ProfilesManager;
|
||||
import org.whispersystems.textsecuregcm.storage.VersionedProfile;
|
||||
import org.whispersystems.textsecuregcm.storage.VersionedProfileV1;
|
||||
@@ -97,9 +96,7 @@ public class ProfileGrpcHelper {
|
||||
final ProfileBadgeConverter profileBadgeConverter,
|
||||
final byte[] requestVersion) {
|
||||
|
||||
final Optional<VersionedProfile> maybeProfile = account.hasCapability(DeviceCapability.PROFILES_V2)
|
||||
? profilesManager.get(account.getAccountIdentifier(), requestVersion)
|
||||
: Optional.empty();
|
||||
final Optional<VersionedProfile> maybeProfile = profilesManager.get(account.getAccountIdentifier(), requestVersion);
|
||||
if (maybeProfile.isEmpty()) {
|
||||
return Optional.empty();
|
||||
}
|
||||
@@ -141,14 +138,8 @@ public class ProfileGrpcHelper {
|
||||
final ProfilesManager profilesManager,
|
||||
final ServerZkProfileOperations zkProfileOperations) {
|
||||
|
||||
final Optional<VersionedProfile> versionedProfile;
|
||||
if (account.hasCapability(DeviceCapability.PROFILES_V2)) {
|
||||
versionedProfile = profilesManager.get(account.getAccountIdentifier(), version);
|
||||
} else {
|
||||
versionedProfile = Optional.empty();
|
||||
}
|
||||
|
||||
return versionedProfile.map(VersionedProfile::commitment)
|
||||
return profilesManager.get(account.getAccountIdentifier(), version)
|
||||
.map(VersionedProfile::commitment)
|
||||
.or(() -> profilesManager.getV1(account.getAccountIdentifier(), HexFormat.of().formatHex(version))
|
||||
.map(VersionedProfileV1::commitment))
|
||||
.map(commitment -> {
|
||||
@@ -157,7 +148,8 @@ public class ProfileGrpcHelper {
|
||||
try {
|
||||
profileKeyCredentialResponse = ProfileHelper.getExpiringProfileKeyCredential(
|
||||
new ProfileKeyCredentialRequest(encodedCredentialRequest),
|
||||
new ProfileKeyCommitment(commitment), new ServiceId.Aci(account.getAccountIdentifier()), zkProfileOperations);
|
||||
new ProfileKeyCommitment(commitment), new ServiceId.Aci(account.getAccountIdentifier()),
|
||||
zkProfileOperations);
|
||||
} catch (VerificationFailedException | InvalidInputException e) {
|
||||
throw GrpcExceptions.invalidArguments("invalid credential request");
|
||||
}
|
||||
|
||||
@@ -51,6 +51,8 @@ public final class MessageMetrics {
|
||||
private static final String DISPLACEMENT_COUNTER_NAME = name(WebSocketConnection.class, "displacement");
|
||||
private static final Duration SLOW_DRAIN_THRESHOLD = Duration.ofSeconds(10);
|
||||
|
||||
private static final String SUSPECTED_DELIVERY_LOOP_COUNTER_NAME = name(MessageMetrics.class, "suspectedDeliveryLoop");
|
||||
|
||||
private final MeterRegistry metricRegistry;
|
||||
private final Counter sendMessageCounter;
|
||||
private final Counter bytesSentCounter;
|
||||
@@ -145,4 +147,16 @@ public final class MessageMetrics {
|
||||
.tags(Tags.of(UserAgentTagUtil.getPlatformTag(userAgent), Tag.of("channel", channel)))
|
||||
.register(metricRegistry));
|
||||
}
|
||||
|
||||
public static void recordSuspectedDeliveryLoop(final String channel,
|
||||
@Nullable final UserAgent userAgent,
|
||||
final ClientReleaseManager clientReleaseManager) {
|
||||
|
||||
final Tags tags = UserAgentTagUtil.getClientVersionTag(userAgent, clientReleaseManager)
|
||||
.map(Tags::of)
|
||||
.orElseGet(Tags::empty)
|
||||
.and(UserAgentTagUtil.getPlatformTag(userAgent));
|
||||
|
||||
Metrics.counter(SUSPECTED_DELIVERY_LOOP_COUNTER_NAME, tags).increment();
|
||||
}
|
||||
}
|
||||
+1
-6
@@ -8,7 +8,6 @@ package org.whispersystems.textsecuregcm.metrics;
|
||||
import ch.qos.logback.classic.LoggerContext;
|
||||
import ch.qos.logback.classic.spi.ILoggingEvent;
|
||||
import ch.qos.logback.core.Appender;
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import com.fasterxml.jackson.annotation.JsonTypeName;
|
||||
import io.dropwizard.logging.common.AbstractAppenderFactory;
|
||||
import io.dropwizard.logging.common.async.AsyncAppenderFactory;
|
||||
@@ -19,9 +18,6 @@ import io.opentelemetry.instrumentation.logback.appender.v1_0.OpenTelemetryAppen
|
||||
@JsonTypeName("otlp")
|
||||
public class OpenTelemetryAppenderFactory extends AbstractAppenderFactory<ILoggingEvent> {
|
||||
|
||||
@JsonProperty
|
||||
private String destination;
|
||||
|
||||
@Override
|
||||
public Appender<ILoggingEvent> build(
|
||||
final LoggerContext context,
|
||||
@@ -32,8 +28,7 @@ public class OpenTelemetryAppenderFactory extends AbstractAppenderFactory<ILoggi
|
||||
|
||||
final OpenTelemetryAppender appender = new OpenTelemetryAppender();
|
||||
appender.setCaptureCodeAttributes(true);
|
||||
appender.setCaptureLoggerContext(true);
|
||||
appender.setCaptureLogstashMarkerAttributes(true);
|
||||
appender.setKeyValuePairAttributesIncluded("*");
|
||||
|
||||
// The installation of an OpenTelemetry configuration happens in
|
||||
// WhisperServerService (or CommandDependencies), in order to let us tie
|
||||
|
||||
+4
-6
@@ -8,10 +8,8 @@ package org.whispersystems.textsecuregcm.metrics;
|
||||
import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
|
||||
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import net.logstash.logback.marker.Markers;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountsManager;
|
||||
@@ -49,10 +47,10 @@ public class ReportedMessageMetricsListener implements ReportedMessageListener {
|
||||
accountsManager.getByAccountIdentifier(reporterUuid).ifPresent(reporter -> {
|
||||
final String destinationCountryCode = Util.getCountryCode(reporter);
|
||||
|
||||
logger.info(Markers.appendEntries(Map.of(
|
||||
"sourceCountry", sourceCountryCode,
|
||||
"destinationCountry", destinationCountryCode)),
|
||||
"Message reported");
|
||||
logger.atInfo()
|
||||
.addKeyValue("sourceCountry", sourceCountryCode)
|
||||
.addKeyValue("destinationCountry", destinationCountryCode)
|
||||
.log("Message reported");
|
||||
|
||||
Metrics.counter(REPORTER_COUNTER_NAME, COUNTRY_CODE_TAG_NAME, destinationCountryCode).increment();
|
||||
});
|
||||
|
||||
@@ -365,7 +365,7 @@ public class StripeManager implements CustomerAwareSubscriptionPaymentProcessor,
|
||||
// since badge redemption is untrackable by design and unrevokable, subscription changes must be immediate and
|
||||
// not prorated
|
||||
.setProrationBehavior(ProrationBehavior.NONE)
|
||||
.setBillingCycleAnchor(BillingCycleAnchor.NOW)
|
||||
.setBillingCycleAnchor(BillingCycleAnchor.builder().setType(BillingCycleAnchor.Type.NOW).build())
|
||||
.setOffSession(true)
|
||||
.setPaymentBehavior(SubscriptionUpdateParams.PaymentBehavior.ERROR_IF_INCOMPLETE)
|
||||
.addAllItem(items)
|
||||
|
||||
+5
-5
@@ -170,22 +170,22 @@ public class RegistrationServiceClient implements Managed {
|
||||
throw new RegistrationServiceException(buildSessionResponseFromMetadata(response.getSessionMetadata()));
|
||||
|
||||
case SEND_VERIFICATION_CODE_ERROR_TYPE_SENDER_REJECTED ->
|
||||
throw RegistrationServiceSenderException.rejected(response.getError().getMayRetry());
|
||||
throw RegistrationServiceSenderException.rejected(!response.getError().getMayRetry());
|
||||
|
||||
case SEND_VERIFICATION_CODE_ERROR_TYPE_SUSPECTED_FRAUD ->
|
||||
throw new RegistrationFraudException(
|
||||
RegistrationServiceSenderException.rejected(response.getError().getMayRetry()));
|
||||
RegistrationServiceSenderException.rejected(!response.getError().getMayRetry()));
|
||||
|
||||
case SEND_VERIFICATION_CODE_ERROR_TYPE_SENDER_ILLEGAL_ARGUMENT ->
|
||||
throw RegistrationServiceSenderException.illegalArgument(response.getError().getMayRetry());
|
||||
throw RegistrationServiceSenderException.illegalArgument(!response.getError().getMayRetry());
|
||||
|
||||
case SEND_VERIFICATION_CODE_ERROR_TYPE_UNSPECIFIED ->
|
||||
throw RegistrationServiceSenderException.unknown(response.getError().getMayRetry());
|
||||
throw RegistrationServiceSenderException.unknown(!response.getError().getMayRetry());
|
||||
|
||||
case SEND_VERIFICATION_CODE_ERROR_TYPE_TRANSPORT_NOT_ALLOWED ->
|
||||
throw new TransportNotAllowedException(buildSessionResponseFromMetadata(response.getSessionMetadata()));
|
||||
case SEND_VERIFICATION_CODE_ERROR_NO_SENDER_AVAILABLE ->
|
||||
throw RegistrationServiceSenderException.unavailable(response.getError().getMayRetry());
|
||||
throw RegistrationServiceSenderException.unavailable(!response.getError().getMayRetry());
|
||||
|
||||
default -> throw new RuntimeException("Failed to send verification code: " + response.getError().getErrorType());
|
||||
}
|
||||
|
||||
+4
-2
@@ -17,9 +17,11 @@ public enum DeviceCapability {
|
||||
TRANSFER("transfer", AccountCapabilityMode.PRIMARY_DEVICE, AccountCapabilityVisibility.SERVER, false, false),
|
||||
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),
|
||||
OPTIONAL_PHONE_NUMBER("optionalPhoneNumber", AccountCapabilityMode.ALL_DEVICES, AccountCapabilityVisibility.SERVER, false, false);
|
||||
OPTIONAL_PHONE_NUMBER("optionalPhoneNumber", AccountCapabilityMode.ALL_DEVICES, AccountCapabilityVisibility.SERVER, false, false),
|
||||
REPLY_PRIVATELY("replyPrivately", AccountCapabilityMode.ALL_DEVICES, AccountCapabilityVisibility.PUBLIC, false, false),
|
||||
CONTACT_DELETE("contactDelete", AccountCapabilityMode.ALL_DEVICES, AccountCapabilityVisibility.PUBLIC, false, false),
|
||||
ADMIN_REMOVE_AND_DELETE("adminRemoveAndDelete", AccountCapabilityMode.ALL_DEVICES, AccountCapabilityVisibility.PUBLIC, false, false);
|
||||
|
||||
public static final List<DeviceCapability> PUBLIC_VISIBLE_CAPABILITIES = Arrays.stream(DeviceCapability.values())
|
||||
.filter(c -> c.accountCapabilityVisibility == AccountCapabilityVisibility.PUBLIC)
|
||||
|
||||
@@ -5,6 +5,7 @@
|
||||
package org.whispersystems.textsecuregcm.storage;
|
||||
|
||||
import com.apple.foundationdb.FDBException;
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import com.google.protobuf.ByteString;
|
||||
import java.time.Clock;
|
||||
import java.time.Instant;
|
||||
@@ -40,6 +41,9 @@ public class MessagesManager {
|
||||
private final ExecutorService messageDeletionExecutor;
|
||||
private final Clock clock;
|
||||
|
||||
@VisibleForTesting
|
||||
static final long DELIVERY_LOOP_READ_THRESHOLD = 10;
|
||||
|
||||
public MessagesManager(
|
||||
final MessagesDynamoDb messagesDynamoDb,
|
||||
final FoundationDbMessageStore foundationDbMessageStore,
|
||||
@@ -223,6 +227,19 @@ public class MessagesManager {
|
||||
.toFuture();
|
||||
}
|
||||
|
||||
/// Checks whether the given device is in a suspected "delivery loop" where it is repeatedly requesting but not
|
||||
/// acknowledging messages.
|
||||
///
|
||||
/// @param accountIdentifier the identifier of the account to check for a delivery loop
|
||||
/// @param deviceId the ID of the device to check for a delivery loop
|
||||
///
|
||||
/// @return a future that yields `true` if the identified device is suspected of being stuck in a message delivery
|
||||
/// loop or `false` otherwise
|
||||
public CompletableFuture<Boolean> hasSuspectedDeliveryLoop(final UUID accountIdentifier, final byte deviceId) {
|
||||
return foundationDbMessageStore.getReadsSinceLastAcknowledgedMessage(new AciServiceIdentifier(accountIdentifier), deviceId)
|
||||
.thenApply(readsSinceLastAcknowledgedMessage -> readsSinceLastAcknowledgedMessage >= DELIVERY_LOOP_READ_THRESHOLD);
|
||||
}
|
||||
|
||||
/// Record versionstamps for the current time in the FoundationDB database(s).
|
||||
public void recordFoundationDbVersionstamps() {
|
||||
foundationDbMessageStore.recordVersionstamps();
|
||||
|
||||
@@ -102,11 +102,7 @@ public class ProfilesManager {
|
||||
redisSet(uuid, null, versionedProfile);
|
||||
|
||||
try {
|
||||
// until the PROFILES_V2 capability prevents downgrades, if a client sets a v2 profile, and then the account
|
||||
// downgrades to v1, all v2 profiles are stale
|
||||
assert !DeviceCapability.PROFILES_V2.preventDowngrade();
|
||||
|
||||
profilesV2.deleteAll(uuid);
|
||||
profilesV2.deleteAll(uuid).join();
|
||||
} catch (final Exception e) {
|
||||
logger.warn("Failed to delete v2 profile data: {}", uuid, e);
|
||||
}
|
||||
|
||||
-84
@@ -1,84 +0,0 @@
|
||||
/*
|
||||
* Copyright 2026 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
package org.whispersystems.textsecuregcm.storage.devicecheck;
|
||||
|
||||
import com.webauthn4j.appattest.DeviceCheckManager;
|
||||
import com.webauthn4j.appattest.data.DCAssertion;
|
||||
import com.webauthn4j.appattest.data.DCAssertionData;
|
||||
import com.webauthn4j.appattest.data.DCAssertionRequest;
|
||||
import com.webauthn4j.converter.AuthenticatorDataConverter;
|
||||
import com.webauthn4j.converter.exception.DataConversionException;
|
||||
import com.webauthn4j.converter.util.ObjectConverter;
|
||||
import com.webauthn4j.data.attestation.authenticator.AuthenticatorData;
|
||||
import com.webauthn4j.data.extension.authenticator.AuthenticationExtensionAuthenticatorOutput;
|
||||
import tools.jackson.core.JacksonException;
|
||||
import java.util.Arrays;
|
||||
|
||||
/// Parses Apple App Attest assertions
|
||||
///
|
||||
/// App Attest assertions since iOS 27 include an extensions map and don't include attested credential data. They
|
||||
/// set the AT flag which indicates data, so a standards-compliant parser barfs because there's an extensions map where
|
||||
/// the AT data should/ be.
|
||||
///
|
||||
/// If Apple fixes their headers or webauthn4j adopts some workaround, this class should be removed
|
||||
///
|
||||
/// [webauthn4j #1497](https://github.com/webauthn4j/webauthn4j/issues/1497)
|
||||
/// [webauthn4j #1518](https://github.com/webauthn4j/webauthn4j/pull/1518)
|
||||
class AppAttestAssertionConverter {
|
||||
|
||||
// https://www.w3.org/TR/webauthn/#sctn-authenticator-data
|
||||
// rpIdHash(32) || flags(1) || signCount(4) || attestedCredentialData(variable) || extensions(variable)
|
||||
private static final int FLAGS_OFFSET = 32;
|
||||
private static final int HEADER_LENGTH = 37;
|
||||
|
||||
// https://www.rfc-editor.org/info/rfc8949/#section-3.1:~:text=the%20CBOR%20Encoding-,3.1%20Major%20Types,-3.2%20Indefinite%20Lengths
|
||||
// CBOR major type 5 (map), covering both definite and indefinite length maps
|
||||
private static final int CBOR_MAJOR_TYPE_MASK = 0xe0;
|
||||
private static final int CBOR_MAP_MAJOR_TYPE = 0xa0;
|
||||
|
||||
private static final ObjectConverter OBJECT_CONVERTER = DeviceCheckManager.createObjectConverter();
|
||||
private static final AuthenticatorDataConverter AUTHENTICATOR_DATA_CONVERTER = new AuthenticatorDataConverter(OBJECT_CONVERTER);
|
||||
|
||||
/// Parse an assertion request that potentially has misconfigured FLAGS. The returned data must still be verified.
|
||||
static DCAssertionData parseAppleAssertion(final DCAssertionRequest request) throws DataConversionException {
|
||||
final DCAssertion assertion = OBJECT_CONVERTER.getCborMapper().readValue(request.getAssertion(), DCAssertion.class);
|
||||
final byte[] authenticatorDataBytes = assertion == null ? null : assertion.getAuthenticatorData();
|
||||
final AuthenticatorData<AuthenticationExtensionAuthenticatorOutput> authenticatorData =
|
||||
authenticatorDataBytes == null ? null : convertAuthenticatorData(authenticatorDataBytes);
|
||||
return new DCAssertionData(request.getKeyId(), authenticatorData, authenticatorDataBytes,
|
||||
request.getClientDataHash(), assertion == null ? null : assertion.getSignature());
|
||||
}
|
||||
|
||||
private static AuthenticatorData<AuthenticationExtensionAuthenticatorOutput> convertAuthenticatorData(final byte[] original) {
|
||||
if (!hasAppleAssertionExtensions(original)) {
|
||||
return AUTHENTICATOR_DATA_CONVERTER.convert(original);
|
||||
}
|
||||
|
||||
final AuthenticatorData<AuthenticationExtensionAuthenticatorOutput> parsed;
|
||||
try {
|
||||
// Create a copy just for parsing and set the flags as Apple should have set them
|
||||
final byte[] modified = Arrays.copyOf(original, original.length);
|
||||
modified[FLAGS_OFFSET] = (byte) ((original[FLAGS_OFFSET] & ~AuthenticatorData.BIT_AT) | AuthenticatorData.BIT_ED);
|
||||
parsed = AUTHENTICATOR_DATA_CONVERTER.convert(modified);
|
||||
} catch (final JacksonException _) {
|
||||
// Jackson error messages can include the (untrusted) extension contents
|
||||
throw new DataConversionException("Invalid App Attest assertion extension data");
|
||||
}
|
||||
|
||||
// Return the parsed structures but keep the original (incorrect) flags, so signature validation works
|
||||
return new AuthenticatorData<>(parsed.getRpIdHash(), original[FLAGS_OFFSET], parsed.getSignCount(),
|
||||
parsed.getExtensions());
|
||||
}
|
||||
|
||||
private static boolean hasAppleAssertionExtensions(final byte[] data) {
|
||||
// If we don't have AT or Extensions at all, webauthn can handle them being incorrectly set without any conversion
|
||||
return data.length > HEADER_LENGTH
|
||||
// If the data correctly sets the AT flag, webauthn can also handle it
|
||||
&& AuthenticatorData.checkFlagAT(data[FLAGS_OFFSET])
|
||||
// If the first byte after the header looks like an extension, this is the special case. Valid assertions
|
||||
// shouldn't have attestedCredentialData anyway, and if it did it should be a CBOR string
|
||||
&& (data[HEADER_LENGTH] & CBOR_MAJOR_TYPE_MASK) == CBOR_MAP_MAJOR_TYPE;
|
||||
}
|
||||
}
|
||||
+3
-2
@@ -138,7 +138,8 @@ public class AppleDeviceCheckManager {
|
||||
final DCAttestationData dcAttestationData;
|
||||
try {
|
||||
dcAttestationData = deviceCheckManager.validate(dcAttestationRequest,
|
||||
new DCAttestationParameters(new DCServerProperty(teamId, bundleId, new DefaultChallenge(challenge))));
|
||||
new DCAttestationParameters(new DCServerProperty(teamId, bundleId,
|
||||
new DefaultChallenge(challenge.getBytes(StandardCharsets.UTF_8)))));
|
||||
} catch (VerificationException e) {
|
||||
logger.info("Failed to verify attestation", e);
|
||||
throw new DeviceCheckVerificationFailedException(e);
|
||||
@@ -204,7 +205,7 @@ public class AppleDeviceCheckManager {
|
||||
new DCAssertionParameters(new DCServerProperty(teamId, bundleId, new DefaultChallenge(request)), appleDevice);
|
||||
|
||||
try {
|
||||
deviceCheckManager.validate(AppAttestAssertionConverter.parseAppleAssertion(dcAssertionRequest), dcAssertionParameters);
|
||||
deviceCheckManager.validate(dcAssertionRequest, dcAssertionParameters);
|
||||
} catch (MaliciousCounterValueException e) {
|
||||
// We will only accept assertions that have a sign count greater than the last assertion we saw. Step 5 here:
|
||||
// https://developer.apple.com/documentation/devicecheck/validating-apps-that-connect-to-your-server#Verify-the-assertion
|
||||
|
||||
+34
-2
@@ -1,6 +1,7 @@
|
||||
package org.whispersystems.textsecuregcm.storage.foundationdb;
|
||||
|
||||
import com.apple.foundationdb.KeySelector;
|
||||
import com.apple.foundationdb.MutationType;
|
||||
import com.apple.foundationdb.StreamingMode;
|
||||
import com.apple.foundationdb.Transaction;
|
||||
import com.apple.foundationdb.tuple.Versionstamp;
|
||||
@@ -8,6 +9,8 @@ import com.google.common.annotations.VisibleForTesting;
|
||||
import com.google.protobuf.InvalidProtocolBufferException;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import java.io.UncheckedIOException;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.ByteOrder;
|
||||
import java.time.Clock;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collections;
|
||||
@@ -42,6 +45,8 @@ class FoundationDbMessagePublisher {
|
||||
/// time the publisher was created. For an infinite publisher, this is the end of subspace range.
|
||||
private final KeySelector endKeyExclusive;
|
||||
|
||||
private final byte[] readsSinceLastAcknowledgedMessageKey;
|
||||
|
||||
/// The key that stores the server ID/timestamp indicating when/where the connected client was last known to be
|
||||
/// present. Active publishers refresh this key at regular intervals (see [#renewPresenceFuture]).
|
||||
@Nullable private final byte[] presenceKey;
|
||||
@@ -87,6 +92,12 @@ class FoundationDbMessagePublisher {
|
||||
|
||||
private static final int STREAM_ID_UNASSIGNED = -1;
|
||||
|
||||
// FoundationDB's `ADD` mutation operate on little-endian, 64-bit integers rather than on tuple-encoded integers
|
||||
private static final byte[] ONE_LITTLE_ENDIAN = ByteBuffer.allocate(Long.BYTES)
|
||||
.order(ByteOrder.LITTLE_ENDIAN)
|
||||
.putLong(1L)
|
||||
.array();
|
||||
|
||||
private static final Logger LOGGER = LoggerFactory.getLogger(FoundationDbMessagePublisher.class);
|
||||
|
||||
private static final String WATCHES_COUNTER = MetricsUtil.name(FoundationDbMessagePublisher.class, "watches");
|
||||
@@ -131,6 +142,7 @@ class FoundationDbMessagePublisher {
|
||||
final KeySelector beginKeyInclusive,
|
||||
final KeySelector endKeyExclusive,
|
||||
final int streamId,
|
||||
final byte[] readsSinceLastAcknowledgedMessageKey,
|
||||
@Nullable final byte[] presenceKey,
|
||||
@Nullable final ScheduledExecutorService presenceRenewalExecutorService,
|
||||
@Nullable final byte[] messagesAvailableWatchKey,
|
||||
@@ -141,6 +153,7 @@ class FoundationDbMessagePublisher {
|
||||
this.beginKeyCursor = beginKeyInclusive;
|
||||
this.endKeyExclusive = endKeyExclusive;
|
||||
this.streamId = streamId;
|
||||
this.readsSinceLastAcknowledgedMessageKey = readsSinceLastAcknowledgedMessageKey;
|
||||
this.presenceKey = presenceKey;
|
||||
this.presenceRenewalExecutorService = presenceRenewalExecutorService;
|
||||
this.messagesAvailableWatchKey = messagesAvailableWatchKey;
|
||||
@@ -176,13 +189,15 @@ class FoundationDbMessagePublisher {
|
||||
final FaultTolerantDatabase database,
|
||||
final Clock clock,
|
||||
final KeySelector beginKeyInclusive,
|
||||
final KeySelector endKeyExclusive) {
|
||||
final KeySelector endKeyExclusive,
|
||||
final byte[] readsSinceHeadAcknowledgedKey) {
|
||||
|
||||
return new FoundationDbMessagePublisher(database,
|
||||
clock,
|
||||
beginKeyInclusive,
|
||||
endKeyExclusive,
|
||||
STREAM_ID_UNASSIGNED,
|
||||
readsSinceHeadAcknowledgedKey,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
@@ -198,6 +213,7 @@ class FoundationDbMessagePublisher {
|
||||
final KeySelector beginKeyInclusive,
|
||||
final KeySelector endKeyExclusive,
|
||||
final int streamId,
|
||||
final byte[] readsSinceHeadAcknowledgedKey,
|
||||
final byte[] presenceKey,
|
||||
final ScheduledExecutorService presenceRenewalExecutorService,
|
||||
final byte[] messagesAvailableWatchKey) {
|
||||
@@ -207,6 +223,7 @@ class FoundationDbMessagePublisher {
|
||||
beginKeyInclusive,
|
||||
endKeyExclusive,
|
||||
streamId,
|
||||
readsSinceHeadAcknowledgedKey,
|
||||
presenceKey,
|
||||
presenceRenewalExecutorService,
|
||||
messagesAvailableWatchKey,
|
||||
@@ -345,7 +362,14 @@ class FoundationDbMessagePublisher {
|
||||
transaction.getRange(beginKeyCursor, endKeyExclusive, maxMessages, false, StreamingMode.EXACT).asList(),
|
||||
(_, keyValues) -> keyValues)
|
||||
.thenApply(keyValues -> {
|
||||
if (keyValues.size() < maxMessages && !terminateOnQueueEmpty) {
|
||||
final int keyValuesSize = keyValues.size();
|
||||
|
||||
if (keyValuesSize > 0 && !hasEmittedEntry()) {
|
||||
// We're about to emit our first message; increment the "sent head of queue since last ACK" counter
|
||||
incrementReadsSinceHeadAcknowledged(transaction);
|
||||
}
|
||||
|
||||
if (keyValuesSize < maxMessages && !terminateOnQueueEmpty) {
|
||||
setWatch(transaction);
|
||||
}
|
||||
|
||||
@@ -398,6 +422,10 @@ class FoundationDbMessagePublisher {
|
||||
return (int) Math.min(totalRequested - totalEmitted, Integer.MAX_VALUE);
|
||||
}
|
||||
|
||||
private synchronized boolean hasEmittedEntry() {
|
||||
return totalEmitted > 0;
|
||||
}
|
||||
|
||||
/// Fetch and publish messages. Messages are fetched in batches to avoid excessive memory consumption. After each
|
||||
/// fetch operation, [#beginKeyCursor] is updated to the next key we need to start reading from. If the fetch
|
||||
/// operation returns fewer items than the batch size, we infer that we have fetched all available messages and
|
||||
@@ -426,6 +454,10 @@ class FoundationDbMessagePublisher {
|
||||
return this.messagePublisher;
|
||||
}
|
||||
|
||||
private void incrementReadsSinceHeadAcknowledged(final Transaction transaction) {
|
||||
transaction.mutate(MutationType.ADD, readsSinceLastAcknowledgedMessageKey, ONE_LITTLE_ENDIAN);
|
||||
}
|
||||
|
||||
private synchronized void setWatch(final Transaction transaction) {
|
||||
assert messagesAvailableWatchKey != null;
|
||||
if (isTerminated()) {
|
||||
|
||||
+26
-1
@@ -21,6 +21,7 @@ import io.micrometer.core.instrument.Tags;
|
||||
import io.micrometer.core.instrument.Timer;
|
||||
import java.io.UncheckedIOException;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.ByteOrder;
|
||||
import java.time.Clock;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
@@ -79,7 +80,7 @@ public class FoundationDbMessageStore {
|
||||
private final ScheduledExecutorService presenceRenewalExecutorService;
|
||||
private final Clock clock;
|
||||
|
||||
// Per-attempt timeout and retry limit for batch priority transacitons, e.g. expired-message trim.
|
||||
// Per-attempt timeout and retry limit for batch priority transactions, e.g. expired-message trim.
|
||||
private final Duration batchPriorityTransactionTimeout;
|
||||
private final long batchPriorityTransactionRetryLimit;
|
||||
|
||||
@@ -397,6 +398,8 @@ public class FoundationDbMessageStore {
|
||||
|
||||
return databasesByEpoch[getConfigurationEpoch(versionstamp)][getShardId(versionstamp)].runAsync(transaction -> {
|
||||
transaction.clear(messageKey);
|
||||
transaction.clear(getReadsSinceLastAcknowledgedMessageKey(aci, deviceId));
|
||||
|
||||
return CompletableFuture.completedFuture(null);
|
||||
}, FaultTolerantDatabase.Context.DELETE_MESSAGE)
|
||||
.thenRun(() -> {
|
||||
@@ -795,6 +798,24 @@ public class FoundationDbMessageStore {
|
||||
}, FaultTolerantDatabase.Context.TRIM_QUEUE);
|
||||
}
|
||||
|
||||
/// Returns the number of times a subscriber has started reading a message queue since the last time any message in
|
||||
/// the queue was acknowledged. In cases where a caller's messages span multiple database shards (i.e. during a
|
||||
/// migration), this method returns the maximum count across all shards.
|
||||
///
|
||||
/// @param aci the account identifier for which to retrieve a read-without-acknowledging-head count
|
||||
/// @param deviceId the device ID for which to retrieve a read-without-acknowledging-head count
|
||||
///
|
||||
/// @return the number of times a subscriber has started reading messages from the identified message queue since the
|
||||
/// last time any message in the queue was acknowledged
|
||||
public CompletableFuture<Long> getReadsSinceLastAcknowledgedMessage(final AciServiceIdentifier aci, final byte deviceId) {
|
||||
return Flux.fromArray(getDistinctDatabasesForAci(aci))
|
||||
.flatMap(database -> Mono.fromFuture(() -> database.readAsync(transaction ->
|
||||
transaction.get(getReadsSinceLastAcknowledgedMessageKey(aci, deviceId)), FaultTolerantDatabase.Context.TEST)))
|
||||
.map(countBytes -> ByteBuffer.wrap(countBytes).order(ByteOrder.LITTLE_ENDIAN).getLong())
|
||||
.reduce(0L, Math::max)
|
||||
.toFuture();
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
public static Subspace getAccountSubspace(final AciServiceIdentifier aci) {
|
||||
return getAccountSubspace(MESSAGES_SUBSPACE, aci);
|
||||
@@ -809,6 +830,10 @@ public class FoundationDbMessageStore {
|
||||
return getAccountSubspace(aci).pack("l");
|
||||
}
|
||||
|
||||
static byte[] getReadsSinceLastAcknowledgedMessageKey(final AciServiceIdentifier aci, final byte deviceId) {
|
||||
return getDeviceSubspace(aci, deviceId).pack("r");
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
static byte[] getServerId() {
|
||||
return SERVER_ID;
|
||||
|
||||
+3
-1
@@ -137,7 +137,8 @@ public class FoundationDbMessageStream implements MessageStream {
|
||||
database,
|
||||
clock,
|
||||
KeySelector.firstGreaterOrEqual(deviceQueueSubspace.range().begin),
|
||||
endOfQueueKeyExclusive)
|
||||
endOfQueueKeyExclusive,
|
||||
FoundationDbMessageStore.getReadsSinceLastAcknowledgedMessageKey(aciServiceIdentifier, deviceId))
|
||||
.getMessages())
|
||||
.orElseGet(Flux::empty)
|
||||
.handle((fdbMessageStreamEntry, sink) -> {
|
||||
@@ -170,6 +171,7 @@ public class FoundationDbMessageStream implements MessageStream {
|
||||
infinitePublisherBeginKey,
|
||||
KeySelector.firstGreaterThan(deviceQueueSubspace.range().end),
|
||||
NEXT_STREAM_ID.getAndIncrement(),
|
||||
FoundationDbMessageStore.getReadsSinceLastAcknowledgedMessageKey(aciServiceIdentifier, deviceId),
|
||||
presenceKey,
|
||||
presenceRenewalExecutorService,
|
||||
messagesAvailableWatchKey).getMessages();
|
||||
|
||||
+1
@@ -23,6 +23,7 @@
|
||||
/// | | device was present
|
||||
/// | | + {device ID (byte)} (device subspace)
|
||||
/// | | | * "p" => presence: server-id || last-seen-time
|
||||
/// | | | * "r" => reads since last message acknowledgement: 64-bit integer (little-endian)
|
||||
/// | | | + "Q" (device message queue subspace)
|
||||
/// | | | | * versionstamp => serialized envelope
|
||||
/// ```
|
||||
|
||||
+4
-2
@@ -7,9 +7,11 @@ package org.whispersystems.textsecuregcm.util;
|
||||
|
||||
import org.signal.libsignal.usernames.BaseUsernameException;
|
||||
import org.signal.libsignal.usernames.Username;
|
||||
import org.signal.libsignal.usernames.UsernameHash;
|
||||
import org.signal.libsignal.zkgroup.InvalidInputException;
|
||||
|
||||
public class UsernameHashZkProofVerifier {
|
||||
public void verifyProof(final byte[] proof, final byte[] hash) throws BaseUsernameException {
|
||||
Username.verifyProof(proof, hash);
|
||||
public void verifyProof(final byte[] proof, final byte[] hash) throws BaseUsernameException, InvalidInputException {
|
||||
Username.verifyProof(proof, new UsernameHash(hash));
|
||||
}
|
||||
}
|
||||
@@ -230,17 +230,6 @@ public class Util {
|
||||
return workingCopy == prefix;
|
||||
}
|
||||
|
||||
/**
|
||||
* Benin changed phone number formats from +229 XXXXXXXX to +229 01XXXXXXXX on November 30, 2024
|
||||
*
|
||||
* @param phoneNumber the phone number to check.
|
||||
* @return whether the provided phone number is an old-format Benin phone number
|
||||
*/
|
||||
public static boolean isOldFormatBeninPhoneNumber(final Phonenumber.PhoneNumber phoneNumber) {
|
||||
return "BJ".equals(PHONE_NUMBER_UTIL.getRegionCodeForNumber(phoneNumber)) &&
|
||||
PHONE_NUMBER_UTIL.getNationalSignificantNumber(phoneNumber).length() == 8;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return whether the E164-formatted {@code number} is in a range that registration-service treats as fictitious
|
||||
*/
|
||||
@@ -257,9 +246,6 @@ public class Util {
|
||||
*/
|
||||
public static Phonenumber.PhoneNumber canonicalizePhoneNumber(final Phonenumber.PhoneNumber phoneNumber)
|
||||
throws NumberParseException, ObsoletePhoneNumberFormatException {
|
||||
if (isOldFormatBeninPhoneNumber(phoneNumber)) {
|
||||
throw new ObsoletePhoneNumberFormatException("bj");
|
||||
}
|
||||
return phoneNumber;
|
||||
}
|
||||
|
||||
|
||||
+1
-4
@@ -9,14 +9,11 @@ import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
|
||||
|
||||
import io.micrometer.core.instrument.Counter;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import net.logstash.logback.marker.Markers;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.Marker;
|
||||
|
||||
/// Log errors that represent a programming logic error
|
||||
public final class ImpossibleEvents {
|
||||
|
||||
private static final Marker IMPOSSIBLE = Markers.append("impossible", true);
|
||||
private static final Counter COUNTER = Metrics.counter(name(ImpossibleEvents.class, "count"));
|
||||
|
||||
private ImpossibleEvents() {
|
||||
@@ -25,6 +22,6 @@ public final class ImpossibleEvents {
|
||||
/// Log that an event should never happen.
|
||||
public static void logImpossible(final Logger logger, final String message, final Object... args) {
|
||||
COUNTER.increment();
|
||||
logger.error(IMPOSSIBLE, message, args);
|
||||
logger.atError().addKeyValue("impossible", true).log(message, args);
|
||||
}
|
||||
}
|
||||
+17
-5
@@ -19,6 +19,7 @@ import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.TimeoutException;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
import java.util.concurrent.atomic.LongAdder;
|
||||
import javax.annotation.Nullable;
|
||||
@@ -141,10 +142,21 @@ public class WebSocketConnection {
|
||||
|
||||
final Timer.Sample queueDrainStart = Timer.start();
|
||||
|
||||
messageSubscription.set(JdkFlowAdapter.flowPublisherToFlux(messageStream.getMessages())
|
||||
.name(SEND_MESSAGES_FLUX_NAME)
|
||||
.tap(Micrometer.metrics(Metrics.globalRegistry))
|
||||
.limitRate(MESSAGE_PUBLISHER_LIMIT_RATE)
|
||||
final AtomicInteger maxConcurrency = new AtomicInteger(MESSAGE_SENDER_MAX_CONCURRENCY);
|
||||
|
||||
messageSubscription.set(Mono.fromFuture(() -> messagesManager.hasSuspectedDeliveryLoop(authenticatedAccount.getAccountIdentifier(), authenticatedDevice.getId()))
|
||||
.flatMapMany(hasSuspectedDeliveryLoop -> {
|
||||
if (hasSuspectedDeliveryLoop) {
|
||||
maxConcurrency.set(1);
|
||||
MessageMetrics.recordSuspectedDeliveryLoop(MessageMetrics.WEBSOCKET_CHANNEL, userAgent, clientReleaseManager);
|
||||
}
|
||||
|
||||
return JdkFlowAdapter.flowPublisherToFlux(messageStream.getMessages())
|
||||
.name(SEND_MESSAGES_FLUX_NAME)
|
||||
.tag("hasSuspectedDeliveryLoop", String.valueOf(hasSuspectedDeliveryLoop))
|
||||
.tap(Micrometer.metrics(Metrics.globalRegistry))
|
||||
.limitRate(maxConcurrency.get());
|
||||
})
|
||||
// We want to handle conflicting connections as soon as possible, and so do this before we start processing
|
||||
// messages in the `flatMapSequential` stage below. If we didn't do this first, then we'd wait for clients to
|
||||
// process messages before sending the "connected elsewhere" signal, and while that's ultimately not harmful,
|
||||
@@ -156,7 +168,7 @@ public class WebSocketConnection {
|
||||
.flatMapSequential(entry -> switch (entry) {
|
||||
case MessageStreamEntry.Envelope envelope -> Mono.fromFuture(() -> sendMessage(envelope.message())).thenReturn(entry);
|
||||
case MessageStreamEntry.QueueEmpty _ -> Mono.just(entry);
|
||||
}, MESSAGE_SENDER_MAX_CONCURRENCY)
|
||||
}, maxConcurrency.get())
|
||||
.subscribeOn(messageDeliveryScheduler)
|
||||
.subscribe(
|
||||
entry -> {
|
||||
|
||||
@@ -90,9 +90,12 @@ enum DeviceCapability {
|
||||
reserved 5;
|
||||
DEVICE_CAPABILITY_ATTACHMENT_BACKFILL = 6;
|
||||
DEVICE_CAPABILITY_SPARSE_POST_QUANTUM_RATCHET = 7;
|
||||
DEVICE_CAPABILITY_PROFILES_V2 = 8;
|
||||
reserved 8;
|
||||
DEVICE_CAPABILITY_USERNAME_CHANGE_SYNC_MESSAGE = 9;
|
||||
DEVICE_CAPABILITY_OPTIONAL_PHONE_NUMBER = 10;
|
||||
DEVICE_CAPABILITY_REPLY_PRIVATELY = 11;
|
||||
DEVICE_CAPABILITY_CONTACT_DELETE = 12;
|
||||
DEVICE_CAPABILITY_ADMIN_REMOVE_AND_DELETE = 13;
|
||||
}
|
||||
|
||||
message ZkCredential {
|
||||
|
||||
@@ -230,8 +230,16 @@ message CheckIdentityKeyRequest {
|
||||
}
|
||||
|
||||
message CheckIdentityKeyResponse {
|
||||
// The service identifier of the account for which there is a mismatch between the client and server identity key fingerprints.
|
||||
common.ServiceIdentifier target_identifier = 1;
|
||||
// The identity key that is stored by the server for the target account/identity type.
|
||||
bytes identity_key = 2;
|
||||
|
||||
oneof response {
|
||||
// The key for the target account/identity type matched.
|
||||
google.protobuf.Empty matched = 1;
|
||||
|
||||
// The identity key that is stored by the server for the target account/identity type.
|
||||
bytes identity_key = 2;
|
||||
|
||||
// Either the target account was not found, or it has no identity key for
|
||||
// the requested identity type.
|
||||
errors.NotFound target_not_found = 3 [(tag.reason) = "not_found"];
|
||||
}
|
||||
}
|
||||
@@ -30,8 +30,8 @@ service OneTimeDonations {
|
||||
// and token.
|
||||
//
|
||||
// The PayPal approval page presented to the user may be localized. Callers
|
||||
// should set their language preferences via an "Accept-Language" header on
|
||||
// the request:
|
||||
// should set their language preferences via gRPC metadata on the request with
|
||||
// the key "Accept-Language" header:
|
||||
// https://datatracker.ietf.org/doc/html/rfc3282#section-3
|
||||
rpc CreatePayPalBoost(CreatePayPalBoostRequest) returns (CreatePayPalBoostResponse) {}
|
||||
|
||||
|
||||
@@ -25,8 +25,8 @@ service RemoteConfiguration {
|
||||
// Returns detailed information for all configured badges, keyed by badge ID.
|
||||
//
|
||||
// Badge descriptions may contain localized strings. Callers should set their
|
||||
// language preferences via an "Accept-Language" header on the request
|
||||
// https://datatracker.ietf.org/doc/html/rfc3282#section-3
|
||||
// language preferences via gRPC metadata on the request with the key
|
||||
// "Accept-Language": https://datatracker.ietf.org/doc/html/rfc3282#section-3
|
||||
//
|
||||
// Callers may cache a badges result for up to 1 day before checking (via
|
||||
// etag) if there are any new updates.
|
||||
|
||||
@@ -39,8 +39,8 @@ service Subscriptions {
|
||||
// Returns a PayPal billing agreement approval URL and token that can be used to set up PayPal as a payment method.
|
||||
//
|
||||
// The presented billing agreement may be localized. Callers should set their
|
||||
// language preferences via an "Accept-Language" header on the request:
|
||||
// https://datatracker.ietf.org/doc/html/rfc3282#section-3
|
||||
// language preferences via gRPC metadata on the request with the key
|
||||
// "Accept-Language": https://datatracker.ietf.org/doc/html/rfc3282#section-3
|
||||
rpc CreatePayPalPaymentMethod(CreatePayPalPaymentMethodRequest) returns (CreatePayPalPaymentMethodResponse) {}
|
||||
|
||||
// Sets the default payment method for a subscriber.
|
||||
|
||||
+6
-5
@@ -60,6 +60,7 @@ import org.junit.jupiter.params.provider.MethodSource;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
import org.signal.libsignal.usernames.BaseUsernameException;
|
||||
import org.signal.libsignal.zkgroup.InvalidInputException;
|
||||
import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
|
||||
import org.whispersystems.textsecuregcm.auth.SaltedTokenHash;
|
||||
import org.whispersystems.textsecuregcm.auth.StoredRegistrationLock;
|
||||
@@ -675,7 +676,7 @@ class AccountControllerTest {
|
||||
|
||||
@Test
|
||||
void testConfirmUsernameHash()
|
||||
throws BaseUsernameException, UsernameHashNotAvailableException, UsernameReservationNotFoundException {
|
||||
throws BaseUsernameException, UsernameHashNotAvailableException, UsernameReservationNotFoundException, InvalidInputException {
|
||||
Account account = mock(Account.class);
|
||||
final UUID uuid = UUID.randomUUID();
|
||||
when(account.getUsernameHash()).thenReturn(Optional.of(USERNAME_HASH_1));
|
||||
@@ -713,7 +714,7 @@ class AccountControllerTest {
|
||||
|
||||
@Test
|
||||
void testConfirmUsernameHashOld()
|
||||
throws BaseUsernameException, UsernameHashNotAvailableException, UsernameReservationNotFoundException {
|
||||
throws BaseUsernameException, UsernameHashNotAvailableException, UsernameReservationNotFoundException, InvalidInputException {
|
||||
Account account = mock(Account.class);
|
||||
when(account.getUsernameHash()).thenReturn(Optional.of(USERNAME_HASH_1));
|
||||
when(account.getUsernameLinkHandle()).thenReturn(null);
|
||||
@@ -737,7 +738,7 @@ class AccountControllerTest {
|
||||
|
||||
@Test
|
||||
void testConfirmUnreservedUsernameHash()
|
||||
throws BaseUsernameException, UsernameHashNotAvailableException, UsernameReservationNotFoundException {
|
||||
throws BaseUsernameException, UsernameHashNotAvailableException, UsernameReservationNotFoundException, InvalidInputException {
|
||||
when(accountsManager.confirmReservedUsernameHash(any(), eq(USERNAME_HASH_1), any()))
|
||||
.thenThrow(new UsernameReservationNotFoundException());
|
||||
|
||||
@@ -754,7 +755,7 @@ class AccountControllerTest {
|
||||
|
||||
@Test
|
||||
void testConfirmLapsedUsernameHash()
|
||||
throws BaseUsernameException, UsernameHashNotAvailableException, UsernameReservationNotFoundException {
|
||||
throws BaseUsernameException, UsernameHashNotAvailableException, UsernameReservationNotFoundException, InvalidInputException {
|
||||
when(accountsManager.confirmReservedUsernameHash(any(), eq(USERNAME_HASH_1), any()))
|
||||
.thenThrow(new UsernameHashNotAvailableException());
|
||||
|
||||
@@ -805,7 +806,7 @@ class AccountControllerTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
void testCommitUsernameHashWithInvalidProof() throws BaseUsernameException {
|
||||
void testCommitUsernameHashWithInvalidProof() throws BaseUsernameException, InvalidInputException {
|
||||
doThrow(new BaseUsernameException("invalid username")).when(usernameZkProofVerifier).verifyProof(eq(ZK_PROOF), eq(USERNAME_HASH_1));
|
||||
|
||||
try (final Response response = resources.getJerseyTest()
|
||||
|
||||
-19
@@ -259,25 +259,6 @@ class VerificationControllerTest {
|
||||
);
|
||||
}
|
||||
|
||||
@Test
|
||||
void createBeninSessionFailure() throws RateLimitExceededException {
|
||||
// libphonenumber 8.13.50 and on generate new-format numbers for Benin
|
||||
final String newFormatBeninE164 = PhoneNumberUtil.getInstance()
|
||||
.format(PhoneNumberUtil.getInstance().getExampleNumber("BJ"), PhoneNumberUtil.PhoneNumberFormat.E164);
|
||||
final String oldFormatBeninE164 = newFormatBeninE164.replaceFirst("01", "");
|
||||
|
||||
when(registrationServiceClient.createRegistrationSession(any(), anyString(), anyBoolean(), any(), any(), any()))
|
||||
.thenReturn(new RegistrationServiceSession(SESSION_ID, NUMBER, false, null, null, null, SESSION_EXPIRATION_SECONDS));
|
||||
|
||||
final Invocation.Builder request = resources.getJerseyTest()
|
||||
.target("/v1/verification/session")
|
||||
.request()
|
||||
.header(HttpHeaders.X_FORWARDED_FOR, "127.0.0.1");
|
||||
try (Response response = request.post(Entity.json(createSessionJson(oldFormatBeninE164, "token", "fcm")))) {
|
||||
assertEquals(499, response.getStatus());
|
||||
}
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@MethodSource
|
||||
void createSessionSuccess(final String pushToken, final String pushTokenType,
|
||||
|
||||
+2
-1
@@ -112,6 +112,7 @@ import org.signal.chat.errors.FailedPrecondition;
|
||||
import org.signal.libsignal.protocol.IdentityKey;
|
||||
import org.signal.libsignal.protocol.ecc.ECKeyPair;
|
||||
import org.signal.libsignal.usernames.BaseUsernameException;
|
||||
import org.signal.libsignal.zkgroup.InvalidInputException;
|
||||
import org.signal.libsignal.zkgroup.ZkCredentialKeyPair;
|
||||
import org.signal.libsignal.zkgroup.ZkCredentialPublicKey;
|
||||
import org.whispersystems.textsecuregcm.auth.InvalidRegistrationSessionException;
|
||||
@@ -520,7 +521,7 @@ class AccountsGrpcServiceTest extends SimpleBaseGrpcTest<AccountsGrpcService, Ac
|
||||
}
|
||||
|
||||
@Test
|
||||
void confirmUsernameHashInvalidProof() throws BaseUsernameException {
|
||||
void confirmUsernameHashInvalidProof() throws BaseUsernameException, InvalidInputException {
|
||||
final byte[] usernameHash = TestRandomUtil.nextBytes(AccountController.USERNAME_HASH_LENGTH);
|
||||
|
||||
final byte[] usernameCiphertext = TestRandomUtil.nextBytes(32);
|
||||
|
||||
+28
-1
@@ -449,7 +449,10 @@ class DevicesGrpcServiceTest extends SimpleBaseGrpcTest<DevicesGrpcService, Devi
|
||||
@CartesianTest.Values(booleans = {true, false}) final boolean transfer,
|
||||
@CartesianTest.Values(booleans = {true, false}) final boolean attachmentBackfill,
|
||||
@CartesianTest.Values(booleans = {true, false}) final boolean spqr,
|
||||
@CartesianTest.Values(booleans = {true, false}) final boolean usernameChangeSyncMessage) {
|
||||
@CartesianTest.Values(booleans = {true, false}) final boolean usernameChangeSyncMessage,
|
||||
@CartesianTest.Values(booleans = {true, false}) final boolean replyPrivately,
|
||||
@CartesianTest.Values(booleans = {true, false}) final boolean contactDelete,
|
||||
@CartesianTest.Values(booleans = {true, false}) final boolean adminRemoveAndDelete) {
|
||||
|
||||
mockAuthenticationInterceptor().setAuthenticatedDevice(AUTHENTICATED_ACI, deviceId);
|
||||
|
||||
@@ -478,6 +481,18 @@ class DevicesGrpcServiceTest extends SimpleBaseGrpcTest<DevicesGrpcService, Devi
|
||||
requestBuilder.addCapabilities(org.signal.chat.common.DeviceCapability.DEVICE_CAPABILITY_USERNAME_CHANGE_SYNC_MESSAGE);
|
||||
}
|
||||
|
||||
if (replyPrivately) {
|
||||
requestBuilder.addCapabilities(org.signal.chat.common.DeviceCapability.DEVICE_CAPABILITY_REPLY_PRIVATELY);
|
||||
}
|
||||
|
||||
if (contactDelete) {
|
||||
requestBuilder.addCapabilities(org.signal.chat.common.DeviceCapability.DEVICE_CAPABILITY_CONTACT_DELETE);
|
||||
}
|
||||
|
||||
if (adminRemoveAndDelete) {
|
||||
requestBuilder.addCapabilities(org.signal.chat.common.DeviceCapability.DEVICE_CAPABILITY_ADMIN_REMOVE_AND_DELETE);
|
||||
}
|
||||
|
||||
final SetCapabilitiesResponse ignored = authenticatedServiceStub().setCapabilities(requestBuilder.build());
|
||||
|
||||
final Set<DeviceCapability> expectedCapabilities = new HashSet<>();
|
||||
@@ -503,6 +518,18 @@ class DevicesGrpcServiceTest extends SimpleBaseGrpcTest<DevicesGrpcService, Devi
|
||||
expectedCapabilities.add(DeviceCapability.USERNAME_CHANGE_SYNC_MESSAGE);
|
||||
}
|
||||
|
||||
if (replyPrivately) {
|
||||
expectedCapabilities.add(DeviceCapability.REPLY_PRIVATELY);
|
||||
}
|
||||
|
||||
if (contactDelete) {
|
||||
expectedCapabilities.add(DeviceCapability.CONTACT_DELETE);
|
||||
}
|
||||
|
||||
if (adminRemoveAndDelete) {
|
||||
expectedCapabilities.add(DeviceCapability.ADMIN_REMOVE_AND_DELETE);
|
||||
}
|
||||
|
||||
verify(device).setCapabilities(expectedCapabilities);
|
||||
}
|
||||
|
||||
|
||||
+17
-15
@@ -26,13 +26,12 @@ import java.security.NoSuchAlgorithmException;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.time.temporal.ChronoUnit;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.CountDownLatch;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
@@ -45,6 +44,7 @@ import org.signal.chat.common.EcPreKey;
|
||||
import org.signal.chat.common.EcSignedPreKey;
|
||||
import org.signal.chat.common.KemSignedPreKey;
|
||||
import org.signal.chat.common.ServiceIdentifier;
|
||||
import org.signal.chat.errors.NotFound;
|
||||
import org.signal.chat.keys.AccountPreKeyBundles;
|
||||
import org.signal.chat.keys.CheckIdentityKeyRequest;
|
||||
import org.signal.chat.keys.CheckIdentityKeyResponse;
|
||||
@@ -54,7 +54,6 @@ import org.signal.chat.keys.GetPreKeysAnonymousResponse;
|
||||
import org.signal.chat.keys.GetPreKeysRequest;
|
||||
import org.signal.chat.keys.KeysAnonymousGrpc;
|
||||
import org.signal.libsignal.protocol.IdentityKey;
|
||||
import org.signal.libsignal.protocol.InvalidKeyException;
|
||||
import org.signal.libsignal.protocol.ecc.ECKeyPair;
|
||||
import org.signal.libsignal.zkgroup.ServerSecretParams;
|
||||
import org.whispersystems.textsecuregcm.auth.UnidentifiedAccessChecksum;
|
||||
@@ -463,7 +462,6 @@ class KeysAnonymousGrpcServiceTest extends SimpleBaseGrpcTest<KeysAnonymousGrpcS
|
||||
final IdentityKey mismatchedPniFingerpringAccountIdentityKey = new IdentityKey(ECKeyPair.generate().getPublicKey());
|
||||
|
||||
// Complete futures asynchronously to catch potential async/context-propagation issues
|
||||
final Duration futureDelay = Duration.ofMillis(1);
|
||||
when(mismatchedAciFingerprintAccount.getAccountIdentityKey()).thenReturn(mismatchedAciFingerprintAccountIdentityKey);
|
||||
when(accountsManager.getByServiceIdentifierAsync(new AciServiceIdentifier(mismatchedAciFingerprintAccountIdentifier)))
|
||||
.thenReturn(delayedAccount(mismatchedAciFingerprintAccount));
|
||||
@@ -476,11 +474,21 @@ class KeysAnonymousGrpcServiceTest extends SimpleBaseGrpcTest<KeysAnonymousGrpcS
|
||||
when(accountsManager.getByServiceIdentifierAsync(new PniServiceIdentifier(mismatchedPniFingerprintAccountIdentifier)))
|
||||
.thenReturn(delayedAccount(mismatchedPniFingerprintAccount));
|
||||
|
||||
final Map<UUID, IdentityKey> expectedResponses = Map.of(
|
||||
mismatchedAciFingerprintAccountIdentifier, mismatchedAciFingerprintAccountIdentityKey,
|
||||
mismatchedPniFingerprintAccountIdentifier, mismatchedPniFingerpringAccountIdentityKey);
|
||||
final List<CheckIdentityKeyResponse> expectedResponses = List.of(
|
||||
CheckIdentityKeyResponse.newBuilder()
|
||||
.setIdentityKey(ByteString.copyFrom(mismatchedAciFingerprintAccountIdentityKey.serialize()))
|
||||
.build(),
|
||||
CheckIdentityKeyResponse.newBuilder()
|
||||
.setMatched(Empty.getDefaultInstance())
|
||||
.build(),
|
||||
CheckIdentityKeyResponse.newBuilder()
|
||||
.setTargetNotFound(NotFound.getDefaultInstance())
|
||||
.build(),
|
||||
CheckIdentityKeyResponse.newBuilder()
|
||||
.setIdentityKey(ByteString.copyFrom(mismatchedPniFingerpringAccountIdentityKey.serialize()))
|
||||
.build());
|
||||
|
||||
final Map<UUID, IdentityKey> responses = new ConcurrentHashMap<>();
|
||||
final List<CheckIdentityKeyResponse> responses = Collections.synchronizedList(new ArrayList<>());
|
||||
final CountDownLatch completedLatch = new CountDownLatch(1);
|
||||
final AtomicReference<Throwable> error = new AtomicReference<>();
|
||||
|
||||
@@ -488,13 +496,7 @@ class KeysAnonymousGrpcServiceTest extends SimpleBaseGrpcTest<KeysAnonymousGrpcS
|
||||
keysAnonymousStub.checkIdentityKeys(new StreamObserver<>() {
|
||||
@Override
|
||||
public void onNext(final CheckIdentityKeyResponse checkIdentityKeyResponse) {
|
||||
try {
|
||||
responses.put(
|
||||
GrpcServiceIdentifierUtil.fromGrpcServiceIdentifier(checkIdentityKeyResponse.getTargetIdentifier()).uuid(),
|
||||
new IdentityKey(checkIdentityKeyResponse.getIdentityKey().toByteArray()));
|
||||
} catch (final InvalidKeyException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
responses.add(checkIdentityKeyResponse);
|
||||
}
|
||||
|
||||
@Override
|
||||
|
||||
+17
-13
@@ -7,6 +7,7 @@ package org.whispersystems.textsecuregcm.grpc;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyByte;
|
||||
import static org.mockito.ArgumentMatchers.anyLong;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.mock;
|
||||
@@ -94,6 +95,9 @@ class MessageDispatcherTest {
|
||||
when(device.getId()).thenReturn(DEVICE_ID);
|
||||
when(device.isPrimary()).thenReturn(true);
|
||||
|
||||
when(messagesManager.hasSuspectedDeliveryLoop(any(), anyByte()))
|
||||
.thenReturn(CompletableFuture.completedFuture(false));
|
||||
|
||||
dispatcher = new MessageDispatcher(
|
||||
receiptSender,
|
||||
messagesManager,
|
||||
@@ -140,7 +144,7 @@ class MessageDispatcherTest {
|
||||
final AciServiceIdentifier sourceServiceId = new AciServiceIdentifier(UUID.randomUUID());
|
||||
|
||||
final List<Envelope> messages = IntStream
|
||||
.range(0, MessageDispatcher.MAX_UNACKED_MESSAGES + 2)
|
||||
.range(0, MessageDispatcher.DEFAULT_MAX_UNACKED_MESSAGES + 2)
|
||||
.mapToObj(i -> createMessage(sourceServiceId, ACI, i, "hello"))
|
||||
.toList();
|
||||
final List<UUID> guids = messages.stream().map(Envelope::getServerGuid).map(UUIDUtil::fromByteString).toList();
|
||||
@@ -158,18 +162,18 @@ class MessageDispatcherTest {
|
||||
dispatcher.getMessages(true, TEST_UA, account, device, acks.flux());
|
||||
|
||||
StepVerifier.create(responses)
|
||||
.expectNext(expectedMessages.subList(0, MessageDispatcher.MAX_UNACKED_MESSAGES).toArray(GetMessagesResponse[]::new))
|
||||
.expectNext(expectedMessages.subList(0, MessageDispatcher.DEFAULT_MAX_UNACKED_MESSAGES).toArray(GetMessagesResponse[]::new))
|
||||
.expectNoEvent(Duration.ofMillis(1))
|
||||
|
||||
// Sending an ack should allow another message to come back
|
||||
.then(() -> acks.next(guids.get(0)))
|
||||
.expectNext(expectedMessages.get(MessageDispatcher.MAX_UNACKED_MESSAGES))
|
||||
.expectNext(expectedMessages.get(MessageDispatcher.DEFAULT_MAX_UNACKED_MESSAGES))
|
||||
.then(() -> verify(messageStream, times(1)).acknowledgeMessage(guids.get(0), timestamps.get(0)))
|
||||
.expectNoEvent(Duration.ofMillis(1))
|
||||
|
||||
// Send another one
|
||||
.then(() -> acks.next(guids.get(1)))
|
||||
.expectNext(expectedMessages.get(MessageDispatcher.MAX_UNACKED_MESSAGES + 1))
|
||||
.expectNext(expectedMessages.get(MessageDispatcher.DEFAULT_MAX_UNACKED_MESSAGES + 1))
|
||||
.then(() -> verify(messageStream, times(1)).acknowledgeMessage(guids.get(1), timestamps.get(1)))
|
||||
.expectNoEvent(Duration.ofMillis(1))
|
||||
|
||||
@@ -187,7 +191,7 @@ class MessageDispatcherTest {
|
||||
void maxOutstandingAllowsGaps() {
|
||||
final AciServiceIdentifier sourceServiceId = new AciServiceIdentifier(UUID.randomUUID());
|
||||
|
||||
final int totalMessages = MessageDispatcher.MAX_UNACKED_MESSAGES * 2;
|
||||
final int totalMessages = MessageDispatcher.DEFAULT_MAX_UNACKED_MESSAGES * 2;
|
||||
|
||||
final List<Envelope> messages = IntStream
|
||||
.range(0, totalMessages)
|
||||
@@ -208,22 +212,22 @@ class MessageDispatcherTest {
|
||||
dispatcher.getMessages(true, TEST_UA, account, device, acks.flux());
|
||||
|
||||
StepVerifier.create(responses)
|
||||
.expectNext(expectedMessages.subList(0, MessageDispatcher.MAX_UNACKED_MESSAGES).toArray(GetMessagesResponse[]::new))
|
||||
.expectNext(expectedMessages.subList(0, MessageDispatcher.DEFAULT_MAX_UNACKED_MESSAGES).toArray(GetMessagesResponse[]::new))
|
||||
.expectNoEvent(Duration.ofMillis(1))
|
||||
.then(() -> {
|
||||
for (int i = 0; i < MessageDispatcher.MAX_UNACKED_MESSAGES; i++) {
|
||||
for (int i = 0; i < MessageDispatcher.DEFAULT_MAX_UNACKED_MESSAGES; i++) {
|
||||
if (i != 2) {
|
||||
acks.next(ackRequests.get(i));
|
||||
}
|
||||
}
|
||||
})
|
||||
.expectNext(expectedMessages.subList(MessageDispatcher.MAX_UNACKED_MESSAGES, totalMessages - 1).toArray(GetMessagesResponse[]::new))
|
||||
.expectNext(expectedMessages.subList(MessageDispatcher.DEFAULT_MAX_UNACKED_MESSAGES, totalMessages - 1).toArray(GetMessagesResponse[]::new))
|
||||
.expectNoEvent(Duration.ofMillis(1))
|
||||
.then(() -> acks.next(ackRequests.get(2)))
|
||||
.expectNext(expectedMessages.get(totalMessages - 1))
|
||||
.expectNoEvent(Duration.ofMillis(1))
|
||||
.then(() -> {
|
||||
for (int i = MessageDispatcher.MAX_UNACKED_MESSAGES; i < totalMessages; i++) {
|
||||
for (int i = MessageDispatcher.DEFAULT_MAX_UNACKED_MESSAGES; i < totalMessages; i++) {
|
||||
acks.next(ackRequests.get(i));
|
||||
}
|
||||
})
|
||||
@@ -236,7 +240,7 @@ class MessageDispatcherTest {
|
||||
void duplicateAckIgnored() {
|
||||
final AciServiceIdentifier sourceServiceId = new AciServiceIdentifier(UUID.randomUUID());
|
||||
final List<Envelope> messages = IntStream
|
||||
.range(0, MessageDispatcher.MAX_UNACKED_MESSAGES + 2)
|
||||
.range(0, MessageDispatcher.DEFAULT_MAX_UNACKED_MESSAGES + 2)
|
||||
.mapToObj(i -> createMessage(sourceServiceId, ACI, i, "hello"))
|
||||
.toList();
|
||||
|
||||
@@ -249,7 +253,7 @@ class MessageDispatcherTest {
|
||||
|
||||
StepVerifier
|
||||
.create(dispatcher.getMessages(true, TEST_UA, account, device, acks.flux()))
|
||||
.expectNextCount(MessageDispatcher.MAX_UNACKED_MESSAGES)
|
||||
.expectNextCount(MessageDispatcher.DEFAULT_MAX_UNACKED_MESSAGES)
|
||||
.expectNoEvent(Duration.ofMillis(1))
|
||||
|
||||
// Ack a message, we should then get a new message
|
||||
@@ -312,7 +316,7 @@ class MessageDispatcherTest {
|
||||
void conflictingConsumerWhileWaitingForAcks() {
|
||||
final AciServiceIdentifier sourceServiceId = new AciServiceIdentifier(UUID.randomUUID());
|
||||
final List<MessageStreamEntry.Envelope> messages = IntStream
|
||||
.range(0, MessageDispatcher.MAX_UNACKED_MESSAGES + 2)
|
||||
.range(0, MessageDispatcher.DEFAULT_MAX_UNACKED_MESSAGES + 2)
|
||||
.mapToObj(i -> createMessage(sourceServiceId, ACI, i, "hello"))
|
||||
.map(MessageStreamEntry.Envelope::new)
|
||||
.toList();
|
||||
@@ -323,7 +327,7 @@ class MessageDispatcherTest {
|
||||
StepVerifier
|
||||
.create(dispatcher.getMessages(true, TEST_UA, account, device, Flux.never()))
|
||||
.then(() -> messages.forEach(source::next))
|
||||
.expectNextCount(MessageDispatcher.MAX_UNACKED_MESSAGES)
|
||||
.expectNextCount(MessageDispatcher.DEFAULT_MAX_UNACKED_MESSAGES)
|
||||
.expectNoEvent(Duration.ofMillis(1))
|
||||
// The error should make it to us immediately even though there are max-unacked messages outstanding
|
||||
.then(() -> source.error(new ConflictingMessageConsumerException()))
|
||||
|
||||
-4
@@ -98,7 +98,6 @@ import org.whispersystems.textsecuregcm.limits.RateLimiters;
|
||||
import org.whispersystems.textsecuregcm.s3.PostPolicyGenerator;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.DeviceCapability;
|
||||
import org.whispersystems.textsecuregcm.storage.ProfilesManager;
|
||||
import org.whispersystems.textsecuregcm.storage.VersionedProfile;
|
||||
import org.whispersystems.textsecuregcm.storage.VersionedProfileV1;
|
||||
@@ -264,7 +263,6 @@ public class ProfileAnonymousGrpcServiceTest extends SimpleBaseGrpcTest<ProfileA
|
||||
when(account.getCurrentProfileVersion()).thenReturn(Optional.of(version));
|
||||
when(account.isUnrestrictedUnidentifiedAccess()).thenReturn(true);
|
||||
when(account.getUnidentifiedAccessKey()).thenReturn(Optional.of(unidentifiedAccessKey));
|
||||
when(account.hasCapability(DeviceCapability.PROFILES_V2)).thenReturn(true);
|
||||
when(account.getAccountIdentityKey()).thenReturn(identityKey);
|
||||
when(account.getBadges()).thenReturn(Collections.emptyList());
|
||||
|
||||
@@ -320,7 +318,6 @@ public class ProfileAnonymousGrpcServiceTest extends SimpleBaseGrpcTest<ProfileA
|
||||
when(account.getCurrentProfileVersion()).thenReturn(Optional.of(version));
|
||||
when(account.isUnrestrictedUnidentifiedAccess()).thenReturn(true);
|
||||
when(account.getUnidentifiedAccessKey()).thenReturn(Optional.of(unidentifiedAccessKey));
|
||||
when(account.hasCapability(DeviceCapability.PROFILES_V2)).thenReturn(true);
|
||||
when(account.getAccountIdentityKey()).thenReturn(identityKey);
|
||||
when(account.getBadges()).thenReturn(Collections.emptyList());
|
||||
|
||||
@@ -518,7 +515,6 @@ public class ProfileAnonymousGrpcServiceTest extends SimpleBaseGrpcTest<ProfileA
|
||||
final ProfileKeyCredentialRequestContext profileKeyCredentialRequestContext =
|
||||
clientZkProfile.createProfileKeyCredentialRequestContext(new ServiceId.Aci(targetUuid), profileKey);
|
||||
|
||||
when(account.hasCapability(DeviceCapability.PROFILES_V2)).thenReturn(hasV2Capability);
|
||||
if (hasV2Capability) {
|
||||
final VersionedProfile profile = mock(VersionedProfile.class);
|
||||
when(profile.commitment()).thenReturn(profileKeyCommitment.serialize());
|
||||
|
||||
-4
@@ -103,7 +103,6 @@ import org.whispersystems.textsecuregcm.s3.PostPolicyGenerator;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountBadge;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.DeviceCapability;
|
||||
import org.whispersystems.textsecuregcm.storage.DynamicConfigurationManager;
|
||||
import org.whispersystems.textsecuregcm.storage.ProfilesManager;
|
||||
import org.whispersystems.textsecuregcm.storage.VersionedProfile;
|
||||
@@ -194,7 +193,6 @@ public class ProfileGrpcServiceTest extends SimpleBaseGrpcTest<ProfileGrpcServic
|
||||
when(account.getAccountIdentifier()).thenReturn(AUTHENTICATED_ACI);
|
||||
when(account.getNumber()).thenReturn(Optional.of(phoneNumber));
|
||||
when(account.getBadges()).thenReturn(Collections.emptyList());
|
||||
when(account.hasCapability(DeviceCapability.PROFILES_V2)).thenReturn(true);
|
||||
|
||||
when(profile.paymentAddress()).thenReturn(null);
|
||||
when(profile.avatar()).thenReturn("");
|
||||
@@ -698,7 +696,6 @@ public class ProfileGrpcServiceTest extends SimpleBaseGrpcTest<ProfileGrpcServic
|
||||
|
||||
when(account.getAccountIdentifier()).thenReturn(targetAci);
|
||||
when(account.getCurrentProfileVersion()).thenReturn(Optional.of(version));
|
||||
when(account.hasCapability(DeviceCapability.PROFILES_V2)).thenReturn(true);
|
||||
when(account.getAccountIdentityKey()).thenReturn(identityKey);
|
||||
when(account.isUnrestrictedUnidentifiedAccess()).thenReturn(true);
|
||||
when(account.getUnidentifiedAccessKey()).thenReturn(Optional.of(unidentifiedAccessKey));
|
||||
@@ -750,7 +747,6 @@ public class ProfileGrpcServiceTest extends SimpleBaseGrpcTest<ProfileGrpcServic
|
||||
|
||||
final UUID targetAci = UUID.randomUUID();
|
||||
when(account.getAccountIdentifier()).thenReturn(targetAci);
|
||||
when(account.hasCapability(DeviceCapability.PROFILES_V2)).thenReturn(true);
|
||||
when(accountsManager.getByServiceIdentifier(new AciServiceIdentifier(targetAci))).thenReturn(Optional.of(account));
|
||||
|
||||
when(account.getAccountIdentityKey()).thenReturn(identityKey);
|
||||
|
||||
+23
@@ -34,8 +34,10 @@ import java.util.stream.Collectors;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.Arguments;
|
||||
import org.junit.jupiter.params.provider.CsvSource;
|
||||
import org.junit.jupiter.params.provider.EnumSource;
|
||||
import org.junit.jupiter.params.provider.MethodSource;
|
||||
import org.junitpioneer.jupiter.cartesian.CartesianTest;
|
||||
import org.signal.libsignal.protocol.InvalidMessageException;
|
||||
import org.signal.libsignal.protocol.InvalidVersionException;
|
||||
@@ -297,4 +299,25 @@ class MessagesManagerTest {
|
||||
messagesManager.getEarliestUndeliveredTimestampForDevice(accountIdentifier, device).join();
|
||||
assertEquals(Optional.ofNullable(expected).map(Instant::ofEpochMilli), earliest);
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@MethodSource
|
||||
void hasSuspectedDeliveryLoop(final long readsSinceLastAcknowledgedMessage, final boolean expectSuspectedLoop) {
|
||||
final AciServiceIdentifier aciServiceIdentifier = new AciServiceIdentifier(UUID.randomUUID());
|
||||
final byte deviceId = Device.PRIMARY_ID;
|
||||
|
||||
when(foundationDbMessageStore.getReadsSinceLastAcknowledgedMessage(aciServiceIdentifier, deviceId))
|
||||
.thenReturn(CompletableFuture.completedFuture(readsSinceLastAcknowledgedMessage));
|
||||
|
||||
assertEquals(expectSuspectedLoop,
|
||||
messagesManager.hasSuspectedDeliveryLoop(aciServiceIdentifier.uuid(), deviceId).join());
|
||||
}
|
||||
|
||||
private static List<Arguments> hasSuspectedDeliveryLoop() {
|
||||
return List.of(
|
||||
Arguments.of(MessagesManager.DELIVERY_LOOP_READ_THRESHOLD - 1, false),
|
||||
Arguments.of(MessagesManager.DELIVERY_LOOP_READ_THRESHOLD, true),
|
||||
Arguments.of(MessagesManager.DELIVERY_LOOP_READ_THRESHOLD + 1, true)
|
||||
);
|
||||
}
|
||||
}
|
||||
-69
@@ -1,69 +0,0 @@
|
||||
/*
|
||||
* Copyright 2026 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
package org.whispersystems.textsecuregcm.storage.devicecheck;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
|
||||
|
||||
import com.webauthn4j.appattest.DeviceCheckManager;
|
||||
import com.webauthn4j.appattest.data.DCAssertionData;
|
||||
import com.webauthn4j.appattest.data.DCAssertionRequest;
|
||||
import com.webauthn4j.converter.exception.DataConversionException;
|
||||
import com.webauthn4j.converter.util.ObjectConverter;
|
||||
import com.webauthn4j.data.attestation.authenticator.AuthenticatorData;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.util.Map;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
|
||||
class AppAttestAssertionConverterTest {
|
||||
|
||||
private static final ObjectConverter OBJECT_CONVERTER = DeviceCheckManager.createObjectConverter();
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(bytes = {AuthenticatorData.BIT_AT, AuthenticatorData.BIT_ED, AuthenticatorData.BIT_AT | AuthenticatorData.BIT_ED})
|
||||
void parseBadAssertion(byte flags) {
|
||||
final DCAssertionData data = AppAttestAssertionConverter.parseAppleAssertion(
|
||||
new DCAssertionRequest(new byte[32], createAssertion(flags), new byte[32]));
|
||||
|
||||
assertThat(data.getAuthenticatorDataBytes()).isEqualTo(createAuthenticatorData(flags));
|
||||
assertThat(data.getAuthenticatorData().getFlags()).isEqualTo(flags);
|
||||
assertThat(data.getAuthenticatorData().getSignCount()).isEqualTo(32);
|
||||
assertThat(data.getAuthenticatorData().getAttestedCredentialData()).isNull();
|
||||
assertThat(data.getAuthenticatorData().getExtensions().getKeys())
|
||||
.containsExactlyInAnyOrder("apple_bundle_version_01", "apple_validation_category_01");
|
||||
}
|
||||
|
||||
// If this test fails, we have updated to a version of webauthn4j that handles misformatted attestations, and
|
||||
// the helper class can be removed.
|
||||
@Test
|
||||
void webauthn4jRejectsIOS27Assertion() {
|
||||
final DeviceCheckManager deviceCheckManager = new DeviceCheckManager(new AppleDeviceCheckTrustAnchor());
|
||||
final byte[] appAttestAssertion = createAssertion((byte) (AuthenticatorData.BIT_AT | AuthenticatorData.BIT_ED));
|
||||
assertThatExceptionOfType(DataConversionException.class).isThrownBy(() ->
|
||||
deviceCheckManager.parse(new DCAssertionRequest(new byte[32], appAttestAssertion, new byte[32])));
|
||||
}
|
||||
|
||||
/// An assertion that has extensions and no attestedCredentialData but potentially with mismatched flags
|
||||
private static byte[] createAssertion(final byte flags) {
|
||||
return OBJECT_CONVERTER.getCborMapper().writeValueAsBytes(Map.of(
|
||||
"signature", new byte[64],
|
||||
"authenticatorData", createAuthenticatorData(flags)));
|
||||
}
|
||||
|
||||
private static byte[] createAuthenticatorData(final byte flags) {
|
||||
final byte[] extensions = OBJECT_CONVERTER.getCborMapper().writeValueAsBytes(Map.of(
|
||||
"apple_bundle_version_01", "1",
|
||||
"apple_validation_category_01", new byte[]{2, 0, 0, 0}));
|
||||
|
||||
return ByteBuffer.allocate(37 + extensions.length)
|
||||
.put(new byte[32]) // rpIdHash
|
||||
.put((byte) flags) // flags
|
||||
.putInt(32) // signCount
|
||||
.put(extensions)
|
||||
.array();
|
||||
}
|
||||
}
|
||||
+4
-7
@@ -14,7 +14,6 @@ import com.webauthn4j.appattest.data.DCAttestationParameters;
|
||||
import com.webauthn4j.appattest.data.DCAttestationRequest;
|
||||
import com.webauthn4j.appattest.server.DCServerProperty;
|
||||
import com.webauthn4j.data.attestation.AttestationObject;
|
||||
import com.webauthn4j.data.client.challenge.DefaultChallenge;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.UncheckedIOException;
|
||||
@@ -74,7 +73,7 @@ public class DeviceCheckTestUtil {
|
||||
|
||||
public static DCAppleDevice sampleDevice() {
|
||||
final byte[] clientDataHash = sha256(SAMPLE_CHALLENGE.getBytes(StandardCharsets.UTF_8));
|
||||
return validate(SAMPLE_CHALLENGE, clientDataHash, SAMPLE_KEY_ID, SAMPLE_ATTESTATION, SAMPLE_TEAM_ID,
|
||||
return validate(clientDataHash, SAMPLE_KEY_ID, SAMPLE_ATTESTATION, SAMPLE_TEAM_ID,
|
||||
SAMPLE_BUNDLE_ID, SAMPLE_TIME);
|
||||
}
|
||||
|
||||
@@ -83,11 +82,11 @@ public class DeviceCheckTestUtil {
|
||||
// despite them referring to the value as a challenge
|
||||
final byte[] clientDataHash = APPLE_SAMPLE_CHALLENGE.getBytes(StandardCharsets.UTF_8);
|
||||
|
||||
return validate(APPLE_SAMPLE_CHALLENGE, clientDataHash, APPLE_SAMPLE_KEY_ID, APPLE_SAMPLE_ATTESTATION,
|
||||
return validate(clientDataHash, APPLE_SAMPLE_KEY_ID, APPLE_SAMPLE_ATTESTATION,
|
||||
APPLE_SAMPLE_TEAM_ID, APPLE_SAMPLE_BUNDLE_ID, APPLE_SAMPLE_TIME);
|
||||
}
|
||||
|
||||
private static DCAppleDevice validate(final String challengePlainText, final byte[] clientDataHash,
|
||||
private static DCAppleDevice validate(final byte[] clientDataHash,
|
||||
final byte[] keyId, final byte[] attestation, final String teamId, final String bundleId, final Instant now) {
|
||||
|
||||
final DCAttestationRequest dcAttestationRequest = new DCAttestationRequest(keyId, attestation, clientDataHash);
|
||||
@@ -97,9 +96,7 @@ public class DeviceCheckTestUtil {
|
||||
instantMock.when(Instant::now).thenReturn(now);
|
||||
|
||||
dcAttestationData = appleDeviceCheckManager().validate(dcAttestationRequest, new DCAttestationParameters(
|
||||
new DCServerProperty(
|
||||
teamId, bundleId,
|
||||
new DefaultChallenge(challengePlainText.getBytes(StandardCharsets.UTF_8)))));
|
||||
new DCServerProperty(teamId, bundleId, clientDataHash)));
|
||||
}
|
||||
|
||||
final AttestationObject attestationObject = dcAttestationData.getAttestationObject();
|
||||
|
||||
+8
@@ -130,6 +130,7 @@ class FoundationDbMessagePublisherTest {
|
||||
KeySelector.firstGreaterOrEqual(SUBSPACE_RANGE.begin),
|
||||
KeySelector.firstGreaterOrEqual(SUBSPACE_RANGE.end),
|
||||
STREAM_ID,
|
||||
FoundationDbMessageStore.getReadsSinceLastAcknowledgedMessageKey(SERVICE_IDENTIFIER, Device.PRIMARY_ID),
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
@@ -207,6 +208,7 @@ class FoundationDbMessagePublisherTest {
|
||||
KeySelector.firstGreaterOrEqual(SUBSPACE_RANGE.begin),
|
||||
KeySelector.firstGreaterOrEqual(new byte[]{(byte) 10}),
|
||||
STREAM_ID,
|
||||
FoundationDbMessageStore.getReadsSinceLastAcknowledgedMessageKey(SERVICE_IDENTIFIER, Device.PRIMARY_ID),
|
||||
FoundationDbMessageStore.getPresenceKey(SERVICE_IDENTIFIER, Device.PRIMARY_ID),
|
||||
presenceRenewalExecutorService,
|
||||
MESSAGES_AVAILABLE_WATCH_KEY,
|
||||
@@ -297,6 +299,7 @@ class FoundationDbMessagePublisherTest {
|
||||
KeySelector.firstGreaterOrEqual(SUBSPACE_RANGE.begin),
|
||||
KeySelector.firstGreaterOrEqual(new byte[]{(byte) 10}),
|
||||
STREAM_ID,
|
||||
FoundationDbMessageStore.getReadsSinceLastAcknowledgedMessageKey(SERVICE_IDENTIFIER, Device.PRIMARY_ID),
|
||||
FoundationDbMessageStore.getPresenceKey(SERVICE_IDENTIFIER, Device.PRIMARY_ID),
|
||||
presenceRenewalExecutorService,
|
||||
MESSAGES_AVAILABLE_WATCH_KEY,
|
||||
@@ -351,6 +354,7 @@ class FoundationDbMessagePublisherTest {
|
||||
KeySelector.firstGreaterOrEqual(SUBSPACE_RANGE.begin),
|
||||
KeySelector.firstGreaterOrEqual(new byte[]{(byte) 10}),
|
||||
STREAM_ID,
|
||||
FoundationDbMessageStore.getReadsSinceLastAcknowledgedMessageKey(SERVICE_IDENTIFIER, Device.PRIMARY_ID),
|
||||
FoundationDbMessageStore.getPresenceKey(SERVICE_IDENTIFIER, Device.PRIMARY_ID),
|
||||
presenceRenewalExecutorService,
|
||||
MESSAGES_AVAILABLE_WATCH_KEY,
|
||||
@@ -399,6 +403,7 @@ class FoundationDbMessagePublisherTest {
|
||||
KeySelector.firstGreaterOrEqual(SUBSPACE_RANGE.begin),
|
||||
KeySelector.firstGreaterThan(SUBSPACE_RANGE.end),
|
||||
STREAM_ID,
|
||||
FoundationDbMessageStore.getReadsSinceLastAcknowledgedMessageKey(SERVICE_IDENTIFIER, Device.PRIMARY_ID),
|
||||
FoundationDbMessageStore.getPresenceKey(SERVICE_IDENTIFIER, Device.PRIMARY_ID),
|
||||
presenceRenewalExecutorService,
|
||||
MESSAGES_AVAILABLE_WATCH_KEY);
|
||||
@@ -461,6 +466,7 @@ class FoundationDbMessagePublisherTest {
|
||||
KeySelector.firstGreaterOrEqual(SUBSPACE_RANGE.begin),
|
||||
KeySelector.firstGreaterOrEqual(new byte[]{(byte) 10}),
|
||||
STREAM_ID,
|
||||
FoundationDbMessageStore.getReadsSinceLastAcknowledgedMessageKey(SERVICE_IDENTIFIER, Device.PRIMARY_ID),
|
||||
FoundationDbMessageStore.getPresenceKey(SERVICE_IDENTIFIER, Device.PRIMARY_ID),
|
||||
presenceRenewalExecutorService,
|
||||
MESSAGES_AVAILABLE_WATCH_KEY,
|
||||
@@ -527,6 +533,7 @@ class FoundationDbMessagePublisherTest {
|
||||
KeySelector.firstGreaterOrEqual(SUBSPACE_RANGE.begin),
|
||||
KeySelector.firstGreaterOrEqual(SUBSPACE_RANGE.end),
|
||||
STREAM_ID,
|
||||
FoundationDbMessageStore.getReadsSinceLastAcknowledgedMessageKey(SERVICE_IDENTIFIER, Device.PRIMARY_ID),
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
@@ -585,6 +592,7 @@ class FoundationDbMessagePublisherTest {
|
||||
KeySelector.firstGreaterOrEqual(SUBSPACE_RANGE.begin),
|
||||
KeySelector.firstGreaterOrEqual(SUBSPACE_RANGE.end),
|
||||
STREAM_ID,
|
||||
FoundationDbMessageStore.getReadsSinceLastAcknowledgedMessageKey(SERVICE_IDENTIFIER, Device.PRIMARY_ID),
|
||||
FoundationDbMessageStore.getPresenceKey(SERVICE_IDENTIFIER, Device.PRIMARY_ID),
|
||||
presenceRenewalExecutorService,
|
||||
MESSAGES_AVAILABLE_WATCH_KEY,
|
||||
|
||||
+40
@@ -1314,6 +1314,46 @@ class FoundationDbMessageStoreTest {
|
||||
foundationDbMessageStore.getEarliestUndeliveredMessageTimestamp(aci, deviceId).join());
|
||||
}
|
||||
|
||||
@Test
|
||||
void getReadsSinceLastAcknowledgedMessage() {
|
||||
final AciServiceIdentifier aci = new AciServiceIdentifier(UUID.randomUUID());
|
||||
final int messageCount = 16;
|
||||
final UUID[] messageGuids = new UUID[messageCount];
|
||||
|
||||
for (int i = 0; i < messageCount; i++) {
|
||||
final Map<Byte, FoundationDbMessageStore.InsertResult> insertResults =
|
||||
foundationDbMessageStore.insert(aci, Map.of(Device.PRIMARY_ID, generateRandomMessage(false))).join();
|
||||
|
||||
messageGuids[i] = insertResults.get(Device.PRIMARY_ID).messageGuid().orElseThrow();
|
||||
}
|
||||
|
||||
assertEquals(0, foundationDbMessageStore.getReadsSinceLastAcknowledgedMessage(aci, Device.PRIMARY_ID).join(),
|
||||
"Initial \"Reads since last acknowledged message\" count should be zero");
|
||||
|
||||
JdkFlowAdapter.flowPublisherToFlux(foundationDbMessageStore.getMessages(aci, Device.PRIMARY_ID).getMessages())
|
||||
.take(messageCount)
|
||||
.then()
|
||||
.block();
|
||||
|
||||
assertEquals(1, foundationDbMessageStore.getReadsSinceLastAcknowledgedMessage(aci, Device.PRIMARY_ID).join(),
|
||||
"\"Reads since last acknowledged message\" count should increment on first read");
|
||||
|
||||
final FoundationDbMessageStream messageStream = foundationDbMessageStore.getMessages(aci, Device.PRIMARY_ID);
|
||||
|
||||
JdkFlowAdapter.flowPublisherToFlux(messageStream.getMessages())
|
||||
.take(messageCount)
|
||||
.then()
|
||||
.block();
|
||||
|
||||
assertEquals(2, foundationDbMessageStore.getReadsSinceLastAcknowledgedMessage(aci, Device.PRIMARY_ID).join(),
|
||||
"\"Reads since last acknowledged message\" count should increment on subsequent reads");
|
||||
|
||||
messageStream.acknowledgeMessage(messageGuids[1], 0L).join();
|
||||
|
||||
assertEquals(0, foundationDbMessageStore.getReadsSinceLastAcknowledgedMessage(aci, Device.PRIMARY_ID).join(),
|
||||
"\"Reads since last acknowledged message\" count should reset when acknowledging any message");
|
||||
}
|
||||
|
||||
static MessageProtos.Envelope generateRandomMessage(final boolean ephemeral, final int contentSize) {
|
||||
return generateRandomMessage(ephemeral, contentSize, CLOCK.millis());
|
||||
}
|
||||
|
||||
@@ -6,17 +6,10 @@
|
||||
package org.whispersystems.textsecuregcm.util;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
import com.google.i18n.phonenumbers.NumberParseException;
|
||||
import com.google.i18n.phonenumbers.PhoneNumberUtil;
|
||||
import com.google.i18n.phonenumbers.Phonenumber;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.stream.Stream;
|
||||
import javax.annotation.Nullable;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.Arguments;
|
||||
@@ -75,47 +68,4 @@ class UtilTest {
|
||||
void startsWithDecimal(final long number, final long prefix, final boolean expectStartsWithPrefix) {
|
||||
assertEquals(expectStartsWithPrefix, Util.startsWithDecimal(number, prefix));
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@MethodSource
|
||||
void isOldFormatBeninPhoneNumber4(final Phonenumber.PhoneNumber beninNumber, final boolean isOldFormatBeninNumber) {
|
||||
if (isOldFormatBeninNumber) {
|
||||
assertTrue(Util.isOldFormatBeninPhoneNumber(beninNumber));
|
||||
} else {
|
||||
assertFalse(Util.isOldFormatBeninPhoneNumber(beninNumber));
|
||||
}
|
||||
}
|
||||
|
||||
private static Stream<Arguments> isOldFormatBeninPhoneNumber4() throws NumberParseException {
|
||||
final Phonenumber.PhoneNumber oldFormatBeninE164 = PhoneNumberUtil.getInstance().parse(OLD_FORMAT_BENIN_E164_STRING, null);
|
||||
final Phonenumber.PhoneNumber newFormatBeninE164 = PhoneNumberUtil.getInstance().parse(NEW_FORMAT_BENIN_E164_STRING, null);
|
||||
|
||||
return Stream.of(
|
||||
Arguments.of(oldFormatBeninE164, true),
|
||||
Arguments.of(newFormatBeninE164, false),
|
||||
Arguments.of(PhoneNumberUtil.getInstance().getExampleNumber("US"), false)
|
||||
);
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@MethodSource
|
||||
void normalizeBeninPhoneNumber(final Phonenumber.PhoneNumber beninNumber, final Phonenumber.PhoneNumber expectedBeninNumber, @Nullable Class<? extends Throwable> exception)
|
||||
throws Exception {
|
||||
if (exception == null) {
|
||||
assertTrue(expectedBeninNumber.exactlySameAs(Util.canonicalizePhoneNumber(beninNumber)));
|
||||
} else {
|
||||
assertThrows(exception, () -> Util.canonicalizePhoneNumber(beninNumber));
|
||||
}
|
||||
}
|
||||
|
||||
private static Stream<Arguments> normalizeBeninPhoneNumber() throws NumberParseException {
|
||||
final Phonenumber.PhoneNumber oldFormatBeninPhoneNumber = PhoneNumberUtil.getInstance().parse(OLD_FORMAT_BENIN_E164_STRING, null);
|
||||
final Phonenumber.PhoneNumber newFormatBeninPhoneNumber = PhoneNumberUtil.getInstance().parse(NEW_FORMAT_BENIN_E164_STRING, null);
|
||||
final Phonenumber.PhoneNumber usPhoneNumber = PhoneNumberUtil.getInstance().getExampleNumber("US");
|
||||
return Stream.of(
|
||||
Arguments.of(newFormatBeninPhoneNumber, newFormatBeninPhoneNumber, null),
|
||||
Arguments.of(oldFormatBeninPhoneNumber, null, ObsoletePhoneNumberFormatException.class),
|
||||
Arguments.of(usPhoneNumber, usPhoneNumber, null)
|
||||
);
|
||||
}
|
||||
}
|
||||
+2
-1
@@ -10,6 +10,7 @@ import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyByte;
|
||||
import static org.mockito.ArgumentMatchers.anyLong;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.mock;
|
||||
@@ -50,7 +51,6 @@ import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
|
||||
import org.whispersystems.textsecuregcm.auth.DisconnectionRequestListener;
|
||||
import org.whispersystems.textsecuregcm.auth.DisconnectionRequestManager;
|
||||
import org.whispersystems.textsecuregcm.entities.MessageProtos;
|
||||
import org.whispersystems.textsecuregcm.experiment.ExperimentEnrollmentManager;
|
||||
import org.whispersystems.textsecuregcm.filters.PriorityFilter;
|
||||
import org.whispersystems.textsecuregcm.filters.RemoteAddressFilter;
|
||||
import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier;
|
||||
@@ -102,6 +102,7 @@ class AuthenticatedConnectListenerIntegrationTest {
|
||||
void setUp() throws Exception {
|
||||
reset(messagesManager, disconnectionRequestManager, accountsManager, account, device);
|
||||
when(messagesManager.mayHaveMessages(any(), any())).thenReturn(CompletableFuture.completedFuture(false));
|
||||
when(messagesManager.hasSuspectedDeliveryLoop(any(), anyByte())).thenReturn(CompletableFuture.completedFuture(false));
|
||||
when(account.getNumber()).thenReturn(Optional.of(E164));
|
||||
when(account.getAccountIdentifier()).thenReturn(ACCOUNT_UUID);
|
||||
when(account.getDevice(DEVICE_ID)).thenReturn(Optional.of(device));
|
||||
|
||||
+4
-2
@@ -7,6 +7,7 @@ package org.whispersystems.textsecuregcm.websocket;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.ArgumentMatchers.anyByte;
|
||||
import static org.mockito.ArgumentMatchers.anyList;
|
||||
import static org.mockito.ArgumentMatchers.anyLong;
|
||||
import static org.mockito.ArgumentMatchers.argThat;
|
||||
@@ -43,9 +44,7 @@ import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
import org.mockito.InOrder;
|
||||
import org.whispersystems.textsecuregcm.experiment.ExperimentEnrollmentManager;
|
||||
import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.identity.IdentityType;
|
||||
import org.whispersystems.textsecuregcm.identity.PniServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.identity.ServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.metrics.MessageMetrics;
|
||||
@@ -98,6 +97,9 @@ class WebSocketConnectionTest {
|
||||
messageDeliveryScheduler = Schedulers.newBoundedElastic(10, 10_000, "messageDelivery");
|
||||
clientReleaseManager = mock(ClientReleaseManager.class);
|
||||
|
||||
when(messagesManager.hasSuspectedDeliveryLoop(any(), anyByte()))
|
||||
.thenReturn(CompletableFuture.completedFuture(false));
|
||||
|
||||
ON_ERROR_DROPPED_COUNTER.set(0);
|
||||
}
|
||||
|
||||
|
||||
+1
-1
Submodule spam-filter updated: 99e0589ff3...af45edd85b.
Reference in new issue
Block a user