mirror of
https://github.com/signalapp/Signal-Server.git
synced 2026-12-01 08:16:47 +00:00
Compare commits
246
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c171a89f03 | ||
|
|
4bc550320b | ||
|
|
361b982357 | ||
|
|
534825fb68 | ||
|
|
9e3d10a6e8 | ||
|
|
ddb4b5d5dd | ||
|
|
ca34692cbb | ||
|
|
2bffd909a5 | ||
|
|
d400e700ac | ||
|
|
755a87c74d | ||
|
|
b30fc7aa8b | ||
|
|
4f4bd431f5 | ||
|
|
79757458d6 | ||
|
|
c09aab080f | ||
|
|
580960d958 | ||
|
|
c21475e3e7 | ||
|
|
09b5289d83 | ||
|
|
f66bd0858d | ||
|
|
ce8cc80f66 | ||
|
|
66b5412103 | ||
|
|
11b6894dae | ||
|
|
02b86d67ad | ||
|
|
f55c3c22fe | ||
|
|
eb601cd51e | ||
|
|
2ee739dbe1 | ||
|
|
a15b70476d | ||
|
|
5f124cc812 | ||
|
|
ce3378354d | ||
|
|
cb02200a24 | ||
|
|
fd36a8909c | ||
|
|
78c15d2a9a | ||
|
|
5815bb8e3f | ||
|
|
d366cdbcb0 | ||
|
|
52b32ce2d4 | ||
|
|
e976c4fbb5 | ||
|
|
81f38c1db7 | ||
|
|
5221b3fb84 | ||
|
|
53bd7a5587 | ||
|
|
100ab61c82 | ||
|
|
4d48c40ce1 | ||
|
|
93ade07c57 | ||
|
|
c1d8ca3c14 | ||
|
|
38707313d7 | ||
|
|
8eb2f5cec6 | ||
|
|
a7d66cb8e6 | ||
|
|
9db804f7c0 | ||
|
|
e93395e334 | ||
|
|
c9b8645469 | ||
|
|
f92681dbae | ||
|
|
7489c62fb7 | ||
|
|
23932b1087 | ||
|
|
6b3f66ddc1 | ||
|
|
77e3675fc9 | ||
|
|
2f712b3f93 | ||
|
|
9b5ad238cf | ||
|
|
8c62a7f819 | ||
|
|
3a75f705c2 | ||
|
|
d79e37230e | ||
|
|
7bc8b93c18 | ||
|
|
b6bed9d772 | ||
|
|
18e58dd21f | ||
|
|
6ab0acadfd | ||
|
|
6209466d1d | ||
|
|
9483f358cd | ||
|
|
1c28620b65 | ||
|
|
cc50ff7074 | ||
|
|
c60ba6677a | ||
|
|
32fc76fd47 | ||
|
|
370c3a9992 | ||
|
|
b3506b186d | ||
|
|
a91585d3c0 | ||
|
|
5469341fd6 | ||
|
|
9ee081ef28 | ||
|
|
33bf9ccae5 | ||
|
|
2321f42e20 | ||
|
|
355d95c6c6 | ||
|
|
3dde05de8a | ||
|
|
1ed282a790 | ||
|
|
d1ec5d7d9c | ||
|
|
c09e167f3f | ||
|
|
eaa3c5f20f | ||
|
|
eb0ffb0c4d | ||
|
|
31b34ed06f | ||
|
|
b247fc24c1 | ||
|
|
56a91f104e | ||
|
|
461fce800a | ||
|
|
7f08e8bf4e | ||
|
|
08ca97ba00 | ||
|
|
4577a4aa9b | ||
|
|
8fac5de9af | ||
|
|
1dd7383af0 | ||
|
|
5f66f1c51d | ||
|
|
867ec4a3df | ||
|
|
a5f2f7f3e5 | ||
|
|
4c2cd0c999 | ||
|
|
14fb2fb29d | ||
|
|
c612bd4b73 | ||
|
|
4157cadf44 | ||
|
|
0cabb53aed | ||
|
|
f04e716347 | ||
|
|
558649ba65 | ||
|
|
43dc9d11fd | ||
|
|
9547655a9c | ||
|
|
547bde4869 | ||
|
|
fe1082d8ba | ||
|
|
7c77dd20bc | ||
|
|
f0370b75af | ||
|
|
ed08d1dc23 | ||
|
|
369ca0b514 | ||
|
|
218a1cd75f | ||
|
|
b04e41803a | ||
|
|
e92c3bb8aa | ||
|
|
2bcecc7f7d | ||
|
|
e8979082a7 | ||
|
|
5c99b03eb2 | ||
|
|
9814fee556 | ||
|
|
5b18ecafaa | ||
|
|
f31fb14667 | ||
|
|
c6d6469008 | ||
|
|
863057d659 | ||
|
|
2b3a6e1aa5 | ||
|
|
38ca4e6b27 | ||
|
|
65bc5e3257 | ||
|
|
ec5613b92a | ||
|
|
e77d3cb9cb | ||
|
|
02e6fb0ecf | ||
|
|
fbf53cd3e8 | ||
|
|
4bcf33d666 | ||
|
|
31b0a096f4 | ||
|
|
1b303cbf01 | ||
|
|
bb76feff71 | ||
|
|
c155696488 | ||
|
|
446c4b2553 | ||
|
|
662c040bd0 | ||
|
|
8a48910d6c | ||
|
|
7375db1c7a | ||
|
|
93083f2ca9 | ||
|
|
8d37c148d6 | ||
|
|
3ca228c0e3 | ||
|
|
85d81271ce | ||
|
|
b2a450b264 | ||
|
|
7946caa817 | ||
|
|
3ac7a2f356 | ||
|
|
2f482f68f7 | ||
|
|
0786627bef | ||
|
|
bc7cd0cc95 | ||
|
|
48954c9f62 | ||
|
|
336e0472f6 | ||
|
|
df026777c4 | ||
|
|
c7bcaac310 | ||
|
|
1366fbba8a | ||
|
|
40601b8297 | ||
|
|
3aed88d8cf | ||
|
|
15129c4ec9 | ||
|
|
af0565c9ad | ||
|
|
341fe88853 | ||
|
|
a5457f81b9 | ||
|
|
e09a9c1707 | ||
|
|
178f6452bb | ||
|
|
a8a4a70a68 | ||
|
|
ae04fae1b9 | ||
|
|
150a4952a1 | ||
|
|
17a824954e | ||
|
|
48fd25f01e | ||
|
|
2c18e4aa1f | ||
|
|
f8e049bb6c | ||
|
|
8ba7da0568 | ||
|
|
30c642324a | ||
|
|
647b25b87c | ||
|
|
e7ec47aa25 | ||
|
|
7d39f2952b | ||
|
|
7ec1f78406 | ||
|
|
9d601047c8 | ||
|
|
d99515e31e | ||
|
|
edce40958b | ||
|
|
4d431fbdbf | ||
|
|
fcf12face8 | ||
|
|
e36e740bc0 | ||
|
|
10c98c5f87 | ||
|
|
8d0ea9f67a | ||
|
|
9870accbae | ||
|
|
6610c37fea | ||
|
|
2d705a23f5 | ||
|
|
5c29072212 | ||
|
|
af6e2c2f2b | ||
|
|
713ab0314e | ||
|
|
3201ab324e | ||
|
|
5eb1a76e99 | ||
|
|
132c9531e1 | ||
|
|
a86cd5dcf5 | ||
|
|
65175c16d0 | ||
|
|
f6ea81cf5e | ||
|
|
1c12a9a258 | ||
|
|
b63f176ad7 | ||
|
|
d69a5f1f33 | ||
|
|
101fa4010d | ||
|
|
fba6037e3a | ||
|
|
7e863e9dba | ||
|
|
1ebb4177fe | ||
|
|
3e5ccb82de | ||
|
|
6e3106297b | ||
|
|
d6b80dfd16 | ||
|
|
7a34493d53 | ||
|
|
894cd8e0a3 | ||
|
|
674d03ef0c | ||
|
|
f8a5e59a30 | ||
|
|
5f465a9f32 | ||
|
|
4e329ae48f | ||
|
|
2dd46b3b85 | ||
|
|
57c3fe949e | ||
|
|
453222ba17 | ||
|
|
c64aeec36a | ||
|
|
8cbc8b0ce6 | ||
|
|
f4f2ffff21 | ||
|
|
5b6d6f28c9 | ||
|
|
e4b09112f1 | ||
|
|
cbc89f541c | ||
|
|
8c86e2e5ef | ||
|
|
376f3b22d7 | ||
|
|
1e2a873753 | ||
|
|
e60daa75a8 | ||
|
|
a3d01a94d4 | ||
|
|
0117ed1a0b | ||
|
|
f3194cf45b | ||
|
|
29c5f8b218 | ||
|
|
d7447b111d | ||
|
|
850286dbfc | ||
|
|
f55a0af55e | ||
|
|
2f1843d5d2 | ||
|
|
78e7e992da | ||
|
|
ef2d25704e | ||
|
|
fc44fb1235 | ||
|
|
20dc6390b9 | ||
|
|
262f7de742 | ||
|
|
fad055aa44 | ||
|
|
9426d0bd9e | ||
|
|
e1d2b3aac7 | ||
|
|
d415a3365a | ||
|
|
8fc63dd4d6 | ||
|
|
ac4d61978b | ||
|
|
79935ea22a | ||
|
|
478a4bda7d | ||
|
|
70d0bda779 | ||
|
|
4f4284d1cc | ||
|
|
c12206ace0 | ||
|
|
d46818e465 |
No files matched your search
+28
-1
@@ -10,9 +10,36 @@ updates:
|
||||
update-types: [ minor, patch ]
|
||||
|
||||
- package-ecosystem: maven
|
||||
directory: /
|
||||
directories: [ "**/*" ]
|
||||
schedule:
|
||||
interval: monthly
|
||||
ignore:
|
||||
# Only patch updates don't require coordination with the deployed database
|
||||
- dependency-name: "org.foundationdb:fdb-java"
|
||||
update-types:
|
||||
- version-update:semver-major
|
||||
- version-update:semver-minor
|
||||
# Ignore the latest pre-release version
|
||||
versions: ["<=7.3.79"]
|
||||
|
||||
# Temporary exclusions, pending upstream fixes
|
||||
# https://github.com/dropwizard/dropwizard/pull/11273
|
||||
- dependency-name: "ch.qos.logback:*"
|
||||
versions: [">=1.6.0"]
|
||||
# https://github.com/jetty/jetty.project/issues/15657
|
||||
- dependency-name: "org.eclipse.jetty:*"
|
||||
versions: ["<=12.1.12"]
|
||||
- dependency-name: "org.eclipse.jetty.ee10:*"
|
||||
versions: ["<=12.1.12"]
|
||||
|
||||
# Temporary exclusions, pending adaptation to upstream changes
|
||||
- dependency-name: "io.lettuce:lettuce-core"
|
||||
versions: [">=7.7.0.RELEASE"]
|
||||
|
||||
# Dependency convergence sentinels, pinned to specific versions
|
||||
- dependency-name: "tools.jackson.core:jackson-databind"
|
||||
- dependency-name: "com.squareup.okio:okio-jvm"
|
||||
|
||||
groups:
|
||||
minor-java-dependencies:
|
||||
# Java: Only group minor and patch updates (we want to carefully review major updates)
|
||||
|
||||
@@ -11,17 +11,18 @@ jobs:
|
||||
contents: write
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0
|
||||
- uses: actions/setup-java@1bcf9fb12cf4aa7d266a90ae39939e61372fe520 # v5.4.0
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
- name: Install APT packages
|
||||
run: |
|
||||
sudo apt-get update
|
||||
# setup-java requires gpg
|
||||
sudo apt-get install -y protobuf-compiler gpg
|
||||
pip install sabledocs
|
||||
- uses: actions/setup-java@dd06d9cba3e5552c54d9f8ea23572deb30010f7c # v6.0.0
|
||||
with:
|
||||
distribution: 'temurin'
|
||||
java-version-file: .java-version
|
||||
cache: 'maven'
|
||||
- name: Install gRPC documentation tooling
|
||||
run: |
|
||||
sudo apt-get update
|
||||
sudo apt-get install -y protobuf-compiler
|
||||
pip install sabledocs
|
||||
- name: Generate OpenAPI documentation
|
||||
run: ./mvnw compile
|
||||
- name: Generate gRPC documentation
|
||||
|
||||
@@ -19,13 +19,18 @@ jobs:
|
||||
contents: read
|
||||
issues: write
|
||||
steps:
|
||||
- uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0
|
||||
- uses: actions/setup-java@1bcf9fb12cf4aa7d266a90ae39939e61372fe520 # v5.4.0
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
- name: Install APT packages
|
||||
run: |
|
||||
# setup-java requires gpg
|
||||
sudo apt update
|
||||
sudo apt install -y gpg
|
||||
- uses: actions/setup-java@dd06d9cba3e5552c54d9f8ea23572deb30010f7c # v6.0.0
|
||||
with:
|
||||
distribution: 'temurin'
|
||||
java-version-file: .java-version
|
||||
cache: 'maven'
|
||||
- uses: aws-actions/configure-aws-credentials@254c19bd240aabef8777f48595e9d2d7b972184b # v6.2.1
|
||||
- uses: aws-actions/configure-aws-credentials@e6de054238d6b7531b4efff3b6587d9aade6a06c # v6.2.3
|
||||
name: Configure AWS credentials from Test account
|
||||
with:
|
||||
role-to-assume: ${{ vars.AWS_ROLE }}
|
||||
|
||||
@@ -28,15 +28,15 @@ jobs:
|
||||
options: --name foundationdb1
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
- name: Install APT packages
|
||||
# ca-certificates: required for AWS CRT client
|
||||
run: |
|
||||
# Add Docker's official GPG key:
|
||||
apt update
|
||||
apt install -y ca-certificates curl
|
||||
# Maven Wrapper requires `unzip`; see https://github.com/apache/maven-wrapper/issues/425
|
||||
apt install -y unzip
|
||||
# setup-java requires gpg
|
||||
apt install -y ca-certificates curl gpg unzip
|
||||
# Add Docker's official GPG key:
|
||||
install -m 0755 -d /etc/apt/keyrings
|
||||
curl -fsSL https://download.docker.com/linux/ubuntu/gpg -o /etc/apt/keyrings/docker.asc
|
||||
chmod a+r /etc/apt/keyrings/docker.asc
|
||||
@@ -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@1bcf9fb12cf4aa7d266a90ae39939e61372fe520 # v5.4.0
|
||||
uses: actions/setup-java@dd06d9cba3e5552c54d9f8ea23572deb30010f7c # v6.0.0
|
||||
with:
|
||||
distribution: 'temurin'
|
||||
java-version-file: .java-version
|
||||
|
||||
+1
-1
@@ -1 +1 @@
|
||||
temurin-25
|
||||
temurin-26
|
||||
@@ -10,10 +10,6 @@
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<artifactId>integration-tests</artifactId>
|
||||
|
||||
<properties>
|
||||
<jetty.http2-client.version>12.1.5</jetty.http2-client.version>
|
||||
</properties>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.whispersystems.textsecure</groupId>
|
||||
@@ -39,7 +35,12 @@
|
||||
<dependency>
|
||||
<groupId>org.eclipse.jetty.http2</groupId>
|
||||
<artifactId>jetty-http2-client-transport</artifactId>
|
||||
<version>${jetty.http2-client.version}</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>com.webauthn4j</groupId>
|
||||
<artifactId>webauthn4j-test</artifactId>
|
||||
<version>${webauthn4j.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
|
||||
@@ -1,101 +0,0 @@
|
||||
/*
|
||||
* Copyright 2023 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.signal.integration;
|
||||
|
||||
import com.fasterxml.jackson.core.JsonGenerator;
|
||||
import com.fasterxml.jackson.core.JsonParser;
|
||||
import com.fasterxml.jackson.databind.DeserializationContext;
|
||||
import com.fasterxml.jackson.databind.JsonDeserializer;
|
||||
import com.fasterxml.jackson.databind.JsonSerializer;
|
||||
import com.fasterxml.jackson.databind.SerializerProvider;
|
||||
import java.io.IOException;
|
||||
import java.util.Base64;
|
||||
import org.signal.libsignal.protocol.IdentityKey;
|
||||
import org.signal.libsignal.protocol.ecc.ECPublicKey;
|
||||
|
||||
public final class Codecs {
|
||||
|
||||
private Codecs() {
|
||||
// utility class
|
||||
}
|
||||
|
||||
@FunctionalInterface
|
||||
public interface CheckedFunction<T, R> {
|
||||
R apply(T t) throws Exception;
|
||||
}
|
||||
|
||||
public static class Base64BasedSerializer<T> extends JsonSerializer<T> {
|
||||
|
||||
private final CheckedFunction<T, byte[]> mapper;
|
||||
|
||||
public Base64BasedSerializer(final CheckedFunction<T, byte[]> mapper) {
|
||||
this.mapper = mapper;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void serialize(final T value, final JsonGenerator gen, final SerializerProvider serializers) throws IOException {
|
||||
try {
|
||||
gen.writeString(Base64.getEncoder().withoutPadding().encodeToString(mapper.apply(value)));
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static class Base64BasedDeserializer<T> extends JsonDeserializer<T> {
|
||||
|
||||
private final CheckedFunction<byte[], T> mapper;
|
||||
|
||||
public Base64BasedDeserializer(final CheckedFunction<byte[], T> mapper) {
|
||||
this.mapper = mapper;
|
||||
}
|
||||
|
||||
@Override
|
||||
public T deserialize(final JsonParser p, final DeserializationContext ctxt) throws IOException {
|
||||
try {
|
||||
return mapper.apply(Base64.getDecoder().decode(p.getValueAsString()));
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static class ByteArraySerializer extends Base64BasedSerializer<byte[]> {
|
||||
public ByteArraySerializer() {
|
||||
super(bytes -> bytes);
|
||||
}
|
||||
}
|
||||
|
||||
public static class ByteArrayDeserializer extends Base64BasedDeserializer<byte[]> {
|
||||
public ByteArrayDeserializer() {
|
||||
super(bytes -> bytes);
|
||||
}
|
||||
}
|
||||
|
||||
public static class ECPublicKeySerializer extends Base64BasedSerializer<ECPublicKey> {
|
||||
public ECPublicKeySerializer() {
|
||||
super(ECPublicKey::serialize);
|
||||
}
|
||||
}
|
||||
|
||||
public static class ECPublicKeyDeserializer extends Base64BasedDeserializer<ECPublicKey> {
|
||||
public ECPublicKeyDeserializer() {
|
||||
super(ECPublicKey::new);
|
||||
}
|
||||
}
|
||||
|
||||
public static class IdentityKeySerializer extends Base64BasedSerializer<IdentityKey> {
|
||||
public IdentityKeySerializer() {
|
||||
super(IdentityKey::serialize);
|
||||
}
|
||||
}
|
||||
|
||||
public static class IdentityKeyDeserializer extends Base64BasedDeserializer<IdentityKey> {
|
||||
public IdentityKeyDeserializer() {
|
||||
super(bytes -> new IdentityKey(bytes, 0));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -13,12 +13,14 @@ import java.util.concurrent.ExecutionException;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.TimeoutException;
|
||||
import org.signal.integration.config.Config;
|
||||
import org.signal.libsignal.zkgroup.receipts.ReceiptSerial;
|
||||
import org.whispersystems.textsecuregcm.metrics.NoopAwsSdkMetricPublisher;
|
||||
import org.whispersystems.textsecuregcm.registration.VerificationSession;
|
||||
import org.whispersystems.textsecuregcm.storage.ChangeNumberWaitingPeriods;
|
||||
import org.whispersystems.textsecuregcm.storage.PhoneNumberIdentifiers;
|
||||
import org.whispersystems.textsecuregcm.storage.RegistrationRecoveryPasswords;
|
||||
import org.whispersystems.textsecuregcm.storage.RegistrationRecoveryPasswordsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.PhoneNumberRecoveryPasswords;
|
||||
import org.whispersystems.textsecuregcm.storage.PhoneNumberRecoveryPasswordsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.RedeemedReceiptsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.VerificationSessionManager;
|
||||
import org.whispersystems.textsecuregcm.storage.VerificationSessions;
|
||||
import software.amazon.awssdk.auth.credentials.AwsCredentialsProvider;
|
||||
@@ -28,7 +30,7 @@ import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
|
||||
|
||||
public class IntegrationTools {
|
||||
|
||||
private final RegistrationRecoveryPasswordsManager registrationRecoveryPasswordsManager;
|
||||
private final PhoneNumberRecoveryPasswordsManager phoneNumberRecoveryPasswordsManager;
|
||||
|
||||
private final VerificationSessionManager verificationSessionManager;
|
||||
|
||||
@@ -36,6 +38,8 @@ public class IntegrationTools {
|
||||
|
||||
private final ChangeNumberWaitingPeriods changeNumberWaitingPeriods;
|
||||
|
||||
private final RedeemedReceiptsManager redeemedReceiptsManager;
|
||||
|
||||
public static IntegrationTools create(final Config config) {
|
||||
final AwsCredentialsProvider credentialsProvider = DefaultCredentialsProvider.builder().build();
|
||||
|
||||
@@ -45,36 +49,39 @@ public class IntegrationTools {
|
||||
final DynamoDbClient dynamoDbClient =
|
||||
config.dynamoDbClient().buildSyncClient(credentialsProvider, new NoopAwsSdkMetricPublisher());
|
||||
|
||||
final RegistrationRecoveryPasswords registrationRecoveryPasswords = new RegistrationRecoveryPasswords(
|
||||
final PhoneNumberRecoveryPasswords phoneNumberRecoveryPasswords = new PhoneNumberRecoveryPasswords(
|
||||
config.dynamoDbTables().registrationRecovery(), Duration.ofDays(1), dynamoDbClient, Clock.systemUTC());
|
||||
|
||||
final VerificationSessions verificationSessions = new VerificationSessions(
|
||||
dynamoDbClient, config.dynamoDbTables().verificationSessions(), Clock.systemUTC());
|
||||
|
||||
return new IntegrationTools(
|
||||
new RegistrationRecoveryPasswordsManager(registrationRecoveryPasswords),
|
||||
new PhoneNumberRecoveryPasswordsManager(phoneNumberRecoveryPasswords),
|
||||
new VerificationSessionManager(verificationSessions),
|
||||
new PhoneNumberIdentifiers(dynamoDbAsyncClient, config.dynamoDbTables().phoneNumberIdentifiers()),
|
||||
new ChangeNumberWaitingPeriods(config.dynamoDbTables().changeNumberWaitingPeriods(), dynamoDbClient)
|
||||
new ChangeNumberWaitingPeriods(config.dynamoDbTables().changeNumberWaitingPeriods(), dynamoDbClient),
|
||||
new RedeemedReceiptsManager(Clock.systemUTC(), config.dynamoDbTables().redeemedReceipts(), dynamoDbClient)
|
||||
);
|
||||
}
|
||||
|
||||
private IntegrationTools(
|
||||
final RegistrationRecoveryPasswordsManager registrationRecoveryPasswordsManager,
|
||||
final PhoneNumberRecoveryPasswordsManager phoneNumberRecoveryPasswordsManager,
|
||||
final VerificationSessionManager verificationSessionManager,
|
||||
final PhoneNumberIdentifiers phoneNumberIdentifiers,
|
||||
final ChangeNumberWaitingPeriods changeNumberWaitingPeriods) {
|
||||
this.registrationRecoveryPasswordsManager = registrationRecoveryPasswordsManager;
|
||||
final ChangeNumberWaitingPeriods changeNumberWaitingPeriods,
|
||||
final RedeemedReceiptsManager redeemedReceiptsManager) {
|
||||
this.phoneNumberRecoveryPasswordsManager = phoneNumberRecoveryPasswordsManager;
|
||||
this.verificationSessionManager = verificationSessionManager;
|
||||
this.phoneNumberIdentifiers = phoneNumberIdentifiers;
|
||||
this.changeNumberWaitingPeriods = changeNumberWaitingPeriods;
|
||||
this.redeemedReceiptsManager = redeemedReceiptsManager;
|
||||
}
|
||||
|
||||
public void populateRecoveryPassword(final String phoneNumber, final byte[] password) {
|
||||
try {
|
||||
final UUID pni = phoneNumberIdentifiers
|
||||
.getPhoneNumberIdentifier(phoneNumber).get(5, TimeUnit.SECONDS);
|
||||
registrationRecoveryPasswordsManager.store(pni, password);
|
||||
phoneNumberRecoveryPasswordsManager.store(pni, password);
|
||||
} catch (ExecutionException | InterruptedException | TimeoutException e) {
|
||||
throw new RuntimeException("failed to get pni", e);
|
||||
}
|
||||
@@ -87,4 +94,8 @@ public class IntegrationTools {
|
||||
public void clearChangeNumberWaitingPeriod(TestUser user) {
|
||||
changeNumberWaitingPeriods.delete(user.aciUuid());
|
||||
}
|
||||
|
||||
public void deleteRedeemedReceipt(final ReceiptSerial receiptSerial) {
|
||||
redeemedReceiptsManager.deleteReceipt(receiptSerial);
|
||||
}
|
||||
}
|
||||
@@ -10,10 +10,27 @@ import static java.util.Objects.requireNonNull;
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.google.common.io.Resources;
|
||||
import com.google.common.net.HttpHeaders;
|
||||
import com.webauthn4j.data.AuthenticatorAssertionResponse;
|
||||
import com.webauthn4j.data.PublicKeyCredential;
|
||||
import com.webauthn4j.data.PublicKeyCredentialDescriptor;
|
||||
import com.webauthn4j.data.PublicKeyCredentialRequestOptions;
|
||||
import com.webauthn4j.data.PublicKeyCredentialType;
|
||||
import com.webauthn4j.data.UserVerificationRequirement;
|
||||
import com.webauthn4j.data.client.challenge.DefaultChallenge;
|
||||
import com.webauthn4j.test.client.ClientPlatform;
|
||||
import io.dropwizard.configuration.ConfigurationValidationException;
|
||||
import io.dropwizard.jersey.validation.Validators;
|
||||
import io.grpc.ChannelCredentials;
|
||||
import io.grpc.ClientInterceptor;
|
||||
import io.grpc.Grpc;
|
||||
import io.grpc.ManagedChannel;
|
||||
import io.grpc.Metadata;
|
||||
import io.grpc.TlsChannelCredentials;
|
||||
import io.grpc.stub.MetadataUtils;
|
||||
import jakarta.validation.ConstraintViolation;
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.UncheckedIOException;
|
||||
import java.lang.invoke.MethodHandles;
|
||||
import java.net.URI;
|
||||
import java.net.URL;
|
||||
@@ -24,6 +41,7 @@ import java.security.KeyStore;
|
||||
import java.security.SecureRandom;
|
||||
import java.security.cert.CertificateException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.Base64;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
@@ -32,6 +50,7 @@ import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import javax.annotation.Nullable;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.apache.commons.lang3.Validate;
|
||||
import org.apache.commons.lang3.tuple.Pair;
|
||||
@@ -43,14 +62,23 @@ import org.eclipse.jetty.util.ssl.SslContextFactory;
|
||||
import org.eclipse.jetty.websocket.client.ClientUpgradeRequest;
|
||||
import org.eclipse.jetty.websocket.client.WebSocketClient;
|
||||
import org.signal.integration.config.Config;
|
||||
import org.signal.integration.config.WebAuthnConfiguration;
|
||||
import org.signal.libsignal.protocol.IdentityKey;
|
||||
import org.signal.libsignal.protocol.ecc.ECKeyPair;
|
||||
import org.signal.libsignal.protocol.ecc.ECPublicKey;
|
||||
import org.signal.libsignal.protocol.kem.KEMKeyPair;
|
||||
import org.signal.libsignal.protocol.kem.KEMKeyType;
|
||||
import org.signal.libsignal.protocol.kem.KEMPublicKey;
|
||||
import org.signal.libsignal.zkgroup.InvalidInputException;
|
||||
import org.signal.libsignal.zkgroup.ServerPublicParams;
|
||||
import org.signal.libsignal.zkgroup.VerificationFailedException;
|
||||
import org.signal.libsignal.zkgroup.receipts.ClientZkReceiptOperations;
|
||||
import org.signal.libsignal.zkgroup.receipts.ReceiptCredential;
|
||||
import org.signal.libsignal.zkgroup.receipts.ReceiptCredentialPresentation;
|
||||
import org.signal.libsignal.zkgroup.receipts.ReceiptSerial;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.auth.grpc.RequireAuthenticationInterceptor;
|
||||
import org.whispersystems.textsecuregcm.entities.AccountAttributes;
|
||||
import org.whispersystems.textsecuregcm.entities.AccountIdentityResponse;
|
||||
import org.whispersystems.textsecuregcm.entities.DeviceActivationRequest;
|
||||
@@ -58,6 +86,7 @@ import org.whispersystems.textsecuregcm.entities.ECSignedPreKey;
|
||||
import org.whispersystems.textsecuregcm.entities.KEMSignedPreKey;
|
||||
import org.whispersystems.textsecuregcm.entities.RegistrationRequest;
|
||||
import org.whispersystems.textsecuregcm.http.FaultTolerantHttpClient;
|
||||
import org.whispersystems.textsecuregcm.mappers.MfaFailureExceptionMapper;
|
||||
import org.whispersystems.textsecuregcm.storage.Device;
|
||||
import org.whispersystems.textsecuregcm.util.CertificateUtil;
|
||||
import org.whispersystems.textsecuregcm.util.HeaderUtils;
|
||||
@@ -70,6 +99,8 @@ public final class Operations {
|
||||
|
||||
private static final Config CONFIG = loadConfigFromClasspath("config.yml");
|
||||
|
||||
private static final String GRPC_DOMAIN = "grpc." + CONFIG.domain();
|
||||
|
||||
private static final IntegrationTools INTEGRATION_TOOLS = IntegrationTools.create(CONFIG);
|
||||
|
||||
private static final String USER_AGENT = "integration-test";
|
||||
@@ -78,11 +109,161 @@ public final class Operations {
|
||||
|
||||
private static final WebSocketClient WEB_SOCKET_CLIENT = buildWebSocketClient();
|
||||
|
||||
private static final ManagedChannel GRPC_CHANNEL = buildGrpcChannel();
|
||||
|
||||
private Operations() {
|
||||
// utility class
|
||||
}
|
||||
|
||||
public record Receipt(ReceiptSerial serial, ReceiptCredential credential) {}
|
||||
|
||||
public static Receipt getPrescribedReceipt() throws InvalidInputException {
|
||||
return new Receipt(
|
||||
new ReceiptSerial(Base64.getUrlDecoder().decode(CONFIG.prescribedReceiptSerial())),
|
||||
new ReceiptCredential(Base64.getUrlDecoder().decode(CONFIG.prescribedReceiptCredential()))
|
||||
);
|
||||
}
|
||||
|
||||
public static WebAuthnConfiguration getWebAuthnConfiguration() {
|
||||
return CONFIG.webAuthn();
|
||||
}
|
||||
|
||||
public static TestUser registerNumberlessUser(final ReceiptCredential receiptCredential)
|
||||
throws InvalidInputException, VerificationFailedException {
|
||||
final String accountPassword = Base64.getEncoder().encodeToString(randomBytes(32));
|
||||
final byte[] recoveryPassword = randomBytes(32);
|
||||
final TestUser user = TestUser.createNumberless(accountPassword, recoveryPassword);
|
||||
|
||||
final ClientZkReceiptOperations clientOps = new ClientZkReceiptOperations(new ServerPublicParams(Base64.getDecoder().decode(CONFIG.serverZkPublicParams())));
|
||||
final ReceiptCredentialPresentation receiptCredentialPresentation = clientOps.createReceiptCredentialPresentation(receiptCredential);
|
||||
|
||||
final ECKeyPair aciIdentityKeyPair = ECKeyPair.generate();
|
||||
final RegistrationRequest registrationRequest = new RegistrationRequest(null,
|
||||
null,
|
||||
receiptCredentialPresentation.serialize(),
|
||||
null,
|
||||
null,
|
||||
user.accountAttributes(),
|
||||
true,
|
||||
new IdentityKey(aciIdentityKeyPair.getPublicKey()),
|
||||
null,
|
||||
new DeviceActivationRequest(generateSignedECPreKey(1, aciIdentityKeyPair),
|
||||
Optional.empty(),
|
||||
generateSignedKEMPreKey(3, aciIdentityKeyPair),
|
||||
Optional.empty(),
|
||||
Optional.empty(),
|
||||
Optional.empty()));
|
||||
|
||||
final AccountIdentityResponse registrationResponse = apiPost("/v1/registration", registrationRequest)
|
||||
// username must be present but can be set to anything for a numberless registration request
|
||||
.authorized("test", accountPassword)
|
||||
.executeExpectSuccess(AccountIdentityResponse.class);
|
||||
|
||||
user.setAciUuid(registrationResponse.uuid());
|
||||
return user;
|
||||
}
|
||||
|
||||
public static TestUser recoverNumberlessUserWithTotp(final TestUser testUser, @Nullable final Integer totp) {
|
||||
final TestUser recoveredUser = TestUser.createNumberlessForRecovery(testUser.accountPassword(), testUser.registrationPassword());
|
||||
|
||||
final ECKeyPair aciIdentityKeyPair = ECKeyPair.generate();
|
||||
final ECKeyPair pniIdentityKeyPair = ECKeyPair.generate();
|
||||
final RegistrationRequest registrationRequest = new RegistrationRequest(null,
|
||||
testUser.registrationPassword(),
|
||||
null,
|
||||
totp,
|
||||
null,
|
||||
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);
|
||||
|
||||
recoveredUser.setAciUuid(registrationResponse.uuid());
|
||||
return recoveredUser;
|
||||
}
|
||||
|
||||
public static TestUser recoverNumberlessUserWithWebAuthn(final TestUser testUser,
|
||||
final ClientPlatform clientPlatform,
|
||||
final byte[] credentialId,
|
||||
final String relyingPartyId) {
|
||||
final TestUser recoveredUser = TestUser.createNumberlessForRecovery(testUser.accountPassword(), testUser.registrationPassword());
|
||||
|
||||
final ECKeyPair aciIdentityKeyPair = ECKeyPair.generate();
|
||||
final ECKeyPair pniIdentityKeyPair = ECKeyPair.generate();
|
||||
final RegistrationRequest initialRequest = new RegistrationRequest(null,
|
||||
testUser.registrationPassword(),
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
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 Pair<Integer, MfaFailureExceptionMapper.MfaFailureResponse> initialResponse = apiPost("/v1/registration", initialRequest)
|
||||
// For a numberless account recovery, the username is the ACI
|
||||
.authorized(testUser.aciUuid().toString(), testUser.accountPassword())
|
||||
.execute(MfaFailureExceptionMapper.MfaFailureResponse.class);
|
||||
|
||||
// we expect (and need) failure with status 441, which will contain the WebAuthn challenge
|
||||
assert initialResponse.getLeft() == 441;
|
||||
|
||||
final MfaFailureExceptionMapper.MfaFailureResponse mfaFailureResponse = initialResponse.getRight();
|
||||
assert mfaFailureResponse.webAuthnParameters().allowedCredentialIds()
|
||||
.stream()
|
||||
.anyMatch(allowedId -> Arrays.equals(allowedId, 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 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);
|
||||
|
||||
recoveredUser.setAciUuid(registrationResponse.uuid());
|
||||
return recoveredUser;
|
||||
}
|
||||
|
||||
public static TestUser newRegisteredUser(final String number) {
|
||||
final byte[] registrationPassword = populateRandomRecoveryPassword(number);
|
||||
final String accountPassword = Base64.getEncoder().encodeToString(randomBytes(32));
|
||||
@@ -96,14 +277,17 @@ public final class Operations {
|
||||
// register account
|
||||
final RegistrationRequest registrationRequest = new RegistrationRequest(null,
|
||||
registrationPassword,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
accountAttributes,
|
||||
true,
|
||||
new IdentityKey(aciIdentityKeyPair.getPublicKey()),
|
||||
new IdentityKey(pniIdentityKeyPair.getPublicKey()),
|
||||
new DeviceActivationRequest(generateSignedECPreKey(1, aciIdentityKeyPair),
|
||||
generateSignedECPreKey(2, pniIdentityKeyPair),
|
||||
Optional.of(generateSignedECPreKey(2, pniIdentityKeyPair)),
|
||||
generateSignedKEMPreKey(3, aciIdentityKeyPair),
|
||||
generateSignedKEMPreKey(4, pniIdentityKeyPair),
|
||||
Optional.of(generateSignedKEMPreKey(4, pniIdentityKeyPair)),
|
||||
Optional.empty(),
|
||||
Optional.empty()));
|
||||
|
||||
@@ -112,7 +296,7 @@ public final class Operations {
|
||||
.executeExpectSuccess(AccountIdentityResponse.class);
|
||||
|
||||
user.setAciUuid(registrationResponse.uuid());
|
||||
user.setPniUuid(registrationResponse.pni());
|
||||
registrationResponse.pni().ifPresent(user::setPniUuid);
|
||||
|
||||
return user;
|
||||
}
|
||||
@@ -145,6 +329,10 @@ public final class Operations {
|
||||
INTEGRATION_TOOLS.clearChangeNumberWaitingPeriod(user);
|
||||
}
|
||||
|
||||
public static void deleteReceipt(final ReceiptSerial receiptSerial) {
|
||||
INTEGRATION_TOOLS.deleteRedeemedReceipt(receiptSerial);
|
||||
}
|
||||
|
||||
public static <T> T sendEmptyRequestAuthenticated(
|
||||
final String endpoint,
|
||||
final String method,
|
||||
@@ -183,7 +371,7 @@ public final class Operations {
|
||||
}
|
||||
}
|
||||
|
||||
private static byte[] randomBytes(int numBytes) {
|
||||
public static byte[] randomBytes(final int numBytes) {
|
||||
final byte[] bytes = new byte[numBytes];
|
||||
new SecureRandom().nextBytes(bytes);
|
||||
return bytes;
|
||||
@@ -216,6 +404,33 @@ public final class Operations {
|
||||
return URI.create("https://" + CONFIG.domain() + endpoint + query);
|
||||
}
|
||||
|
||||
public static ManagedChannel grpcChannel() {
|
||||
return GRPC_CHANNEL;
|
||||
}
|
||||
|
||||
public static ClientInterceptor authorizationInterceptor(final TestUser user, final byte deviceId) {
|
||||
final String username = "%s.%d".formatted(user.aciUuid().toString(), deviceId);
|
||||
|
||||
final Metadata metadata = new Metadata();
|
||||
metadata.put(RequireAuthenticationInterceptor.AUTHORIZATION_METADATA_KEY,
|
||||
HeaderUtils.basicAuthHeader(username, user.accountPassword()));
|
||||
|
||||
return MetadataUtils.newAttachHeadersInterceptor(metadata);
|
||||
}
|
||||
|
||||
private static ManagedChannel buildGrpcChannel() {
|
||||
try {
|
||||
final ByteArrayInputStream rootCert =
|
||||
new ByteArrayInputStream(CONFIG.rootCert().getBytes(StandardCharsets.UTF_8));
|
||||
final ChannelCredentials credentials = TlsChannelCredentials.newBuilder().trustManager(rootCert).build();
|
||||
return Grpc.newChannelBuilderForAddress(GRPC_DOMAIN, 443, credentials)
|
||||
.userAgent(USER_AGENT)
|
||||
.build();
|
||||
} catch (final IOException e) {
|
||||
throw new UncheckedIOException(e);
|
||||
}
|
||||
}
|
||||
|
||||
public static class RequestBuilder {
|
||||
|
||||
private final HttpRequest.Builder builder;
|
||||
@@ -266,33 +481,39 @@ public final class Operations {
|
||||
}
|
||||
|
||||
public Pair<Integer, Void> executeExpectSuccess() {
|
||||
final Pair<Integer, Void> execute = execute();
|
||||
final RawResponse response = executeRaw();
|
||||
Validate.isTrue(
|
||||
HttpUtils.isSuccessfulResponse(execute.getLeft()),
|
||||
"Unexpected response code: %d",
|
||||
execute.getLeft());
|
||||
return execute;
|
||||
HttpUtils.isSuccessfulResponse(response.statusCode()),
|
||||
"Unexpected response code: %d, body: %s",
|
||||
response.statusCode(), response.body());
|
||||
return Pair.of(response.statusCode(), null);
|
||||
}
|
||||
|
||||
public <T> T executeExpectSuccess(final Class<T> expectedType) {
|
||||
final Pair<Integer, T> execute = execute(expectedType);
|
||||
final RawResponse response = executeRaw();
|
||||
Validate.isTrue(
|
||||
HttpUtils.isSuccessfulResponse(execute.getLeft()),
|
||||
"Unexpected response code: %d : %s",
|
||||
execute.getLeft(), execute.getRight());
|
||||
return requireNonNull(execute.getRight());
|
||||
HttpUtils.isSuccessfulResponse(response.statusCode()),
|
||||
"Unexpected response code: %d, body: %s",
|
||||
response.statusCode(), response.body());
|
||||
return requireNonNull(parseBody(response.body(), expectedType));
|
||||
}
|
||||
|
||||
public void executeExpectStatusCode(final int expectedStatusCode) {
|
||||
final Pair<Integer, Void> execute = execute(Void.class);
|
||||
final RawResponse response = executeRaw();
|
||||
Validate.isTrue(
|
||||
execute.getLeft() == expectedStatusCode,
|
||||
"Unexpected response code: %d",
|
||||
execute.getLeft()
|
||||
);
|
||||
response.statusCode() == expectedStatusCode,
|
||||
"Unexpected response code: %d (expected %d), body: %s",
|
||||
response.statusCode(), expectedStatusCode, response.body());
|
||||
}
|
||||
|
||||
public <T> Pair<Integer, T> execute(final Class<T> expectedType) {
|
||||
final RawResponse response = executeRaw();
|
||||
return Pair.of(response.statusCode(), parseBody(response.body(), expectedType));
|
||||
}
|
||||
|
||||
private record RawResponse(int statusCode, String body) {}
|
||||
|
||||
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))
|
||||
@@ -302,19 +523,24 @@ public final class Operations {
|
||||
error.printStackTrace();
|
||||
}
|
||||
})
|
||||
.thenApply(response -> {
|
||||
try {
|
||||
final T result = expectedType.equals(Void.class)
|
||||
? null
|
||||
: SystemMapper.jsonMapper().readValue(response.body(), expectedType);
|
||||
return Pair.of(response.statusCode(), result);
|
||||
} catch (final IOException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
})
|
||||
.thenApply(response -> new RawResponse(response.statusCode(), response.body()))
|
||||
.join();
|
||||
}
|
||||
|
||||
@Nullable
|
||||
private static <T> T parseBody(final String body, final Class<T> expectedType) {
|
||||
if (expectedType.equals(Void.class)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
return SystemMapper.jsonMapper().readValue(body, expectedType);
|
||||
} catch (final IOException e) {
|
||||
throw new RuntimeException(
|
||||
"Could not parse response body as %s, body: %s".formatted(expectedType.getSimpleName(), body), e);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
private static FaultTolerantHttpClient buildClient() {
|
||||
@@ -360,7 +586,7 @@ public final class Operations {
|
||||
final String path,
|
||||
final Map<String, String> headers) throws IOException {
|
||||
|
||||
final URI uri = URI.create("wss://grpc." + CONFIG.domain() + path);
|
||||
final URI uri = URI.create("wss://" + GRPC_DOMAIN + path);
|
||||
final ClientUpgradeRequest request = new ClientUpgradeRequest(uri);
|
||||
headers.forEach(request::setHeader);
|
||||
|
||||
@@ -410,4 +636,34 @@ public final class Operations {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
|
||||
/// Serializes an assertion into the [specification](https://www.w3.org/TR/webauthn/#dictdef-authenticationresponsejson) format.
|
||||
static String webAuthnVerificationResponseJson(final PublicKeyCredential<AuthenticatorAssertionResponse, ?> credential) {
|
||||
final AuthenticatorAssertionResponse response = credential.getResponse();
|
||||
|
||||
return """
|
||||
{
|
||||
"id": "%s",
|
||||
"rawId": "%s",
|
||||
"type": "public-key",
|
||||
"clientExtensionResults": {},
|
||||
"response": {
|
||||
"clientDataJSON": "%s",
|
||||
"authenticatorData": "%s",
|
||||
"signature": "%s",
|
||||
"userHandle": %s
|
||||
}
|
||||
}
|
||||
""".formatted(
|
||||
base64Url(credential.getRawId()),
|
||||
base64Url(credential.getRawId()),
|
||||
base64Url(response.getClientDataJSON()),
|
||||
base64Url(response.getAuthenticatorData()),
|
||||
base64Url(response.getSignature()),
|
||||
response.getUserHandle() == null ? "null" : "\"" + base64Url(response.getUserHandle()) + "\"");
|
||||
}
|
||||
|
||||
private static String base64Url(@Nullable final byte[] bytes) {
|
||||
return Base64.getUrlEncoder().withoutPadding().encodeToString(bytes);
|
||||
}
|
||||
}
|
||||
@@ -1,58 +0,0 @@
|
||||
/*
|
||||
* Copyright 2023 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.signal.integration;
|
||||
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import org.apache.commons.lang3.tuple.Pair;
|
||||
import org.signal.libsignal.protocol.IdentityKeyPair;
|
||||
import org.signal.libsignal.protocol.ecc.ECKeyPair;
|
||||
import org.signal.libsignal.protocol.state.SignedPreKeyRecord;
|
||||
|
||||
public class TestDevice {
|
||||
|
||||
private final byte deviceId;
|
||||
|
||||
private final Map<Integer, Pair<IdentityKeyPair, SignedPreKeyRecord>> signedPreKeys = new ConcurrentHashMap<>();
|
||||
|
||||
|
||||
public static TestDevice create(
|
||||
final byte deviceId,
|
||||
final IdentityKeyPair aciIdentityKeyPair,
|
||||
final IdentityKeyPair pniIdentityKeyPair) {
|
||||
final TestDevice device = new TestDevice(deviceId);
|
||||
device.addSignedPreKey(aciIdentityKeyPair);
|
||||
device.addSignedPreKey(pniIdentityKeyPair);
|
||||
return device;
|
||||
}
|
||||
|
||||
public TestDevice(final byte deviceId) {
|
||||
this.deviceId = deviceId;
|
||||
}
|
||||
|
||||
public byte deviceId() {
|
||||
return deviceId;
|
||||
}
|
||||
|
||||
public SignedPreKeyRecord latestSignedPreKey(final IdentityKeyPair identity) {
|
||||
final int id = signedPreKeys.entrySet()
|
||||
.stream()
|
||||
.filter(p -> p.getValue().getLeft().equals(identity))
|
||||
.mapToInt(Map.Entry::getKey)
|
||||
.max()
|
||||
.orElseThrow();
|
||||
return signedPreKeys.get(id).getRight();
|
||||
}
|
||||
|
||||
public SignedPreKeyRecord addSignedPreKey(final IdentityKeyPair identity) {
|
||||
final int nextId = signedPreKeys.keySet().stream().mapToInt(k -> k + 1).max().orElse(0);
|
||||
final ECKeyPair keyPair = ECKeyPair.generate();
|
||||
final byte[] signature = keyPair.getPrivateKey().calculateSignature(keyPair.getPublicKey().serialize());
|
||||
final SignedPreKeyRecord signedPreKeyRecord = new SignedPreKeyRecord(nextId, System.currentTimeMillis(), keyPair, signature);
|
||||
signedPreKeys.put(nextId, Pair.of(identity, signedPreKeyRecord));
|
||||
return signedPreKeyRecord;
|
||||
}
|
||||
}
|
||||
@@ -5,71 +5,76 @@
|
||||
|
||||
package org.signal.integration;
|
||||
|
||||
import static java.util.Objects.requireNonNull;
|
||||
|
||||
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
|
||||
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
|
||||
import java.security.SecureRandom;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.security.SecureRandom;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import org.signal.libsignal.protocol.IdentityKey;
|
||||
import org.signal.libsignal.protocol.IdentityKeyPair;
|
||||
import org.signal.libsignal.protocol.InvalidKeyException;
|
||||
import org.signal.libsignal.protocol.ecc.ECPublicKey;
|
||||
import org.signal.libsignal.protocol.state.SignedPreKeyRecord;
|
||||
import javax.annotation.Nullable;
|
||||
import org.signal.libsignal.protocol.util.KeyHelper;
|
||||
import org.whispersystems.textsecuregcm.auth.UnidentifiedAccessUtil;
|
||||
import org.whispersystems.textsecuregcm.entities.AccountAttributes;
|
||||
import org.whispersystems.textsecuregcm.storage.Device;
|
||||
import org.whispersystems.textsecuregcm.storage.DeviceCapability;
|
||||
|
||||
public class TestUser {
|
||||
|
||||
private final int registrationId;
|
||||
|
||||
private final int pniRegistrationId;
|
||||
|
||||
private final IdentityKeyPair aciIdentityKey;
|
||||
|
||||
private final Map<Byte, TestDevice> devices = new ConcurrentHashMap<>();
|
||||
@Nullable
|
||||
private final Integer pniRegistrationId;
|
||||
|
||||
private final byte[] unidentifiedAccessKey;
|
||||
|
||||
private String phoneNumber;
|
||||
@Nullable
|
||||
private final String phoneNumber;
|
||||
|
||||
private IdentityKeyPair pniIdentityKey;
|
||||
private final String accountPassword;
|
||||
|
||||
private String accountPassword;
|
||||
|
||||
private byte[] registrationPassword;
|
||||
private final byte[] registrationPassword;
|
||||
|
||||
private UUID aciUuid;
|
||||
|
||||
@Nullable
|
||||
private UUID pniUuid;
|
||||
|
||||
public static TestUser createNumberless(final String accountPassword, final byte[] accountRecoveryPassword) {
|
||||
final int registrationId = KeyHelper.generateRegistrationId(false);
|
||||
final byte[] unidentifiedAccessKey = Operations.randomBytes(UnidentifiedAccessUtil.UNIDENTIFIED_ACCESS_KEY_LENGTH);
|
||||
|
||||
return new TestUser(
|
||||
registrationId,
|
||||
null,
|
||||
null,
|
||||
unidentifiedAccessKey,
|
||||
accountPassword,
|
||||
accountRecoveryPassword);
|
||||
}
|
||||
|
||||
public static TestUser createNumberlessForRecovery(final String accountPassword, final byte[] accountRecoveryPassword) {
|
||||
// Recovering a numberless account requires PNI keys (though they are discarded by the server)
|
||||
final int registrationId = KeyHelper.generateRegistrationId(false);
|
||||
final int pniRegistrationId = KeyHelper.generateRegistrationId(false);
|
||||
final byte[] unidentifiedAccessKey = new byte[UnidentifiedAccessUtil.UNIDENTIFIED_ACCESS_KEY_LENGTH];
|
||||
new SecureRandom().nextBytes(unidentifiedAccessKey);
|
||||
|
||||
return new TestUser(
|
||||
registrationId,
|
||||
pniRegistrationId,
|
||||
null,
|
||||
unidentifiedAccessKey,
|
||||
accountPassword,
|
||||
accountRecoveryPassword);
|
||||
}
|
||||
|
||||
public static TestUser create(final String phoneNumber, final String accountPassword, final byte[] registrationPassword) {
|
||||
// ACI identity key pair
|
||||
final IdentityKeyPair aciIdentityKey = IdentityKeyPair.generate();
|
||||
// PNI identity key pair
|
||||
final IdentityKeyPair pniIdentityKey = IdentityKeyPair.generate();
|
||||
// registration id
|
||||
final int registrationId = KeyHelper.generateRegistrationId(false);
|
||||
final int pniRegistrationId = KeyHelper.generateRegistrationId(false);
|
||||
// uak
|
||||
final byte[] unidentifiedAccessKey = new byte[UnidentifiedAccessUtil.UNIDENTIFIED_ACCESS_KEY_LENGTH];
|
||||
new SecureRandom().nextBytes(unidentifiedAccessKey);
|
||||
|
||||
return new TestUser(
|
||||
registrationId,
|
||||
pniRegistrationId,
|
||||
aciIdentityKey,
|
||||
phoneNumber,
|
||||
pniIdentityKey,
|
||||
unidentifiedAccessKey,
|
||||
accountPassword,
|
||||
registrationPassword);
|
||||
@@ -77,38 +82,25 @@ public class TestUser {
|
||||
|
||||
public TestUser(
|
||||
final int registrationId,
|
||||
final int pniRegistrationId,
|
||||
final IdentityKeyPair aciIdentityKey,
|
||||
final String phoneNumber,
|
||||
final IdentityKeyPair pniIdentityKey,
|
||||
@Nullable final Integer pniRegistrationId,
|
||||
@Nullable final String phoneNumber,
|
||||
final byte[] unidentifiedAccessKey,
|
||||
final String accountPassword,
|
||||
final byte[] registrationPassword) {
|
||||
this.registrationId = registrationId;
|
||||
this.pniRegistrationId = pniRegistrationId;
|
||||
this.aciIdentityKey = aciIdentityKey;
|
||||
this.phoneNumber = phoneNumber;
|
||||
this.pniIdentityKey = pniIdentityKey;
|
||||
this.unidentifiedAccessKey = unidentifiedAccessKey;
|
||||
this.accountPassword = accountPassword;
|
||||
this.registrationPassword = registrationPassword;
|
||||
devices.put(Device.PRIMARY_ID, TestDevice.create(Device.PRIMARY_ID, aciIdentityKey, pniIdentityKey));
|
||||
}
|
||||
|
||||
public int registrationId() {
|
||||
return registrationId;
|
||||
}
|
||||
|
||||
public IdentityKeyPair aciIdentityKey() {
|
||||
return aciIdentityKey;
|
||||
}
|
||||
|
||||
public String phoneNumber() {
|
||||
return phoneNumber;
|
||||
}
|
||||
|
||||
public IdentityKeyPair pniIdentityKey() {
|
||||
return pniIdentityKey;
|
||||
public Optional<String> phoneNumber() {
|
||||
return Optional.ofNullable(phoneNumber);
|
||||
}
|
||||
|
||||
public String accountPassword() {
|
||||
@@ -123,77 +115,21 @@ public class TestUser {
|
||||
return aciUuid;
|
||||
}
|
||||
|
||||
public UUID pniUuid() {
|
||||
return pniUuid;
|
||||
public Optional<UUID> pniUuid() {
|
||||
return Optional.ofNullable(pniUuid);
|
||||
}
|
||||
|
||||
public AccountAttributes accountAttributes() {
|
||||
return new AccountAttributes(true, registrationId, pniRegistrationId, "".getBytes(StandardCharsets.UTF_8), "", true,
|
||||
DeviceCapability.CAPABILITIES_REQUIRED_FOR_NEW_DEVICES)
|
||||
.setUnidentifiedAccessKey(unidentifiedAccessKey)
|
||||
.setRecoveryPassword(registrationPassword);
|
||||
DeviceCapability.CAPABILITIES_REQUIRED_FOR_NEW_DEVICES, registrationPassword)
|
||||
.setUnidentifiedAccessKey(unidentifiedAccessKey);
|
||||
}
|
||||
|
||||
public void setAciUuid(final UUID aciUuid) {
|
||||
this.aciUuid = aciUuid;
|
||||
}
|
||||
|
||||
public void setPniUuid(final UUID pniUuid) {
|
||||
public void setPniUuid(@Nullable final UUID pniUuid) {
|
||||
this.pniUuid = pniUuid;
|
||||
}
|
||||
|
||||
public void setPhoneNumber(final String phoneNumber) {
|
||||
this.phoneNumber = phoneNumber;
|
||||
}
|
||||
|
||||
public void setPniIdentityKey(final IdentityKeyPair pniIdentityKey) {
|
||||
this.pniIdentityKey = pniIdentityKey;
|
||||
}
|
||||
|
||||
public void setAccountPassword(final String accountPassword) {
|
||||
this.accountPassword = accountPassword;
|
||||
}
|
||||
|
||||
public void setRegistrationPassword(final byte[] registrationPassword) {
|
||||
this.registrationPassword = registrationPassword;
|
||||
}
|
||||
|
||||
public PreKeySetPublicView preKeys(final byte deviceId, final boolean pni) {
|
||||
final IdentityKeyPair identity = pni
|
||||
? pniIdentityKey
|
||||
: aciIdentityKey;
|
||||
final TestDevice device = requireNonNull(devices.get(deviceId));
|
||||
final SignedPreKeyRecord signedPreKeyRecord = device.latestSignedPreKey(identity);
|
||||
try {
|
||||
return new PreKeySetPublicView(
|
||||
Collections.emptyList(),
|
||||
identity.getPublicKey(),
|
||||
new SignedPreKeyPublicView(
|
||||
signedPreKeyRecord.getId(),
|
||||
signedPreKeyRecord.getKeyPair().getPublicKey(),
|
||||
signedPreKeyRecord.getSignature()
|
||||
)
|
||||
);
|
||||
} catch (InvalidKeyException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
|
||||
public record SignedPreKeyPublicView(
|
||||
int keyId,
|
||||
@JsonSerialize(using = Codecs.ECPublicKeySerializer.class)
|
||||
@JsonDeserialize(using = Codecs.ECPublicKeyDeserializer.class)
|
||||
ECPublicKey publicKey,
|
||||
@JsonSerialize(using = Codecs.ByteArraySerializer.class)
|
||||
@JsonDeserialize(using = Codecs.ByteArrayDeserializer.class)
|
||||
byte[] signature) {
|
||||
}
|
||||
|
||||
public record PreKeySetPublicView(
|
||||
List<String> preKeys,
|
||||
@JsonSerialize(using = Codecs.IdentityKeySerializer.class)
|
||||
@JsonDeserialize(using = Codecs.IdentityKeyDeserializer.class)
|
||||
IdentityKey identityKey,
|
||||
SignedPreKeyPublicView signedPreKey) {
|
||||
}
|
||||
}
|
||||
@@ -15,5 +15,9 @@ public record Config(@NotBlank String domain,
|
||||
@NotNull @Valid DynamoDbClientFactory dynamoDbClient,
|
||||
@NotNull @Valid DynamoDbTables dynamoDbTables,
|
||||
@NotBlank String prescribedRegistrationNumber,
|
||||
@NotBlank String prescribedRegistrationCode) {
|
||||
@NotBlank String prescribedRegistrationCode,
|
||||
@NotBlank String prescribedReceiptSerial,
|
||||
@NotBlank String prescribedReceiptCredential,
|
||||
@NotBlank String serverZkPublicParams,
|
||||
@NotNull @Valid WebAuthnConfiguration webAuthn) {
|
||||
}
|
||||
@@ -10,5 +10,6 @@ import jakarta.validation.constraints.NotBlank;
|
||||
public record DynamoDbTables(@NotBlank String registrationRecovery,
|
||||
@NotBlank String verificationSessions,
|
||||
@NotBlank String phoneNumberIdentifiers,
|
||||
@NotBlank String changeNumberWaitingPeriods) {
|
||||
@NotBlank String changeNumberWaitingPeriods,
|
||||
@NotBlank String redeemedReceipts) {
|
||||
}
|
||||
+13
@@ -0,0 +1,13 @@
|
||||
/*
|
||||
* Copyright 2026 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.signal.integration.config;
|
||||
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
|
||||
public record WebAuthnConfiguration(
|
||||
@NotBlank String relyingPartyId,
|
||||
@NotBlank String origin) {
|
||||
}
|
||||
@@ -5,21 +5,67 @@
|
||||
|
||||
package org.signal.integration;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
import com.eatthepath.otp.TimeBasedOneTimePasswordGenerator;
|
||||
import com.google.protobuf.ByteString;
|
||||
import com.webauthn4j.data.AttestationConveyancePreference;
|
||||
import com.webauthn4j.data.AuthenticatorAttestationResponse;
|
||||
import com.webauthn4j.data.AuthenticatorSelectionCriteria;
|
||||
import com.webauthn4j.data.PublicKeyCredential;
|
||||
import com.webauthn4j.data.PublicKeyCredentialCreationOptions;
|
||||
import com.webauthn4j.data.PublicKeyCredentialParameters;
|
||||
import com.webauthn4j.data.PublicKeyCredentialRpEntity;
|
||||
import com.webauthn4j.data.PublicKeyCredentialType;
|
||||
import com.webauthn4j.data.PublicKeyCredentialUserEntity;
|
||||
import com.webauthn4j.data.ResidentKeyRequirement;
|
||||
import com.webauthn4j.data.UserVerificationRequirement;
|
||||
import com.webauthn4j.data.attestation.statement.COSEAlgorithmIdentifier;
|
||||
import com.webauthn4j.data.client.Origin;
|
||||
import com.webauthn4j.data.client.challenge.DefaultChallenge;
|
||||
import com.webauthn4j.test.EmulatorUtil;
|
||||
import com.webauthn4j.test.authenticator.webauthn.WebAuthnAuthenticatorAdaptor;
|
||||
import com.webauthn4j.test.client.ClientPlatform;
|
||||
import java.security.InvalidKeyException;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.Arrays;
|
||||
import java.util.Base64;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import javax.crypto.SecretKey;
|
||||
import javax.crypto.spec.SecretKeySpec;
|
||||
import org.apache.commons.lang3.tuple.Pair;
|
||||
import org.apache.http.HttpStatus;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Nested;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.signal.chat.account.AccountsGrpc;
|
||||
import org.signal.chat.account.ConfirmTotpKeyRequest;
|
||||
import org.signal.chat.account.ConfirmTotpKeyResponse;
|
||||
import org.signal.chat.account.FinishWebAuthnRegistrationRequest;
|
||||
import org.signal.chat.account.FinishWebAuthnRegistrationResponse;
|
||||
import org.signal.chat.account.GenerateTotpKeyRequest;
|
||||
import org.signal.chat.account.GenerateTotpKeyResponse;
|
||||
import org.signal.chat.account.ListMfaKeysRequest;
|
||||
import org.signal.chat.account.ListMfaKeysResponse;
|
||||
import org.signal.chat.account.StartWebAuthnRegistrationRequest;
|
||||
import org.signal.chat.account.StartWebAuthnRegistrationResponse;
|
||||
import org.signal.chat.account.TotpParameters;
|
||||
import org.signal.integration.config.WebAuthnConfiguration;
|
||||
import org.signal.libsignal.protocol.IdentityKey;
|
||||
import org.signal.libsignal.protocol.ecc.ECKeyPair;
|
||||
import org.signal.libsignal.usernames.BaseUsernameException;
|
||||
import org.signal.libsignal.usernames.Username;
|
||||
import org.signal.libsignal.zkgroup.InvalidInputException;
|
||||
import org.signal.libsignal.zkgroup.VerificationFailedException;
|
||||
import org.whispersystems.textsecuregcm.entities.AccountIdentifierResponse;
|
||||
import org.whispersystems.textsecuregcm.entities.AccountIdentityResponse;
|
||||
import org.whispersystems.textsecuregcm.entities.ChangeNumberRequest;
|
||||
@@ -32,6 +78,153 @@ import org.whispersystems.textsecuregcm.storage.Device;
|
||||
|
||||
public class AccountTest {
|
||||
|
||||
@Test
|
||||
public void testCreateNumberlessAccount()
|
||||
throws VerificationFailedException, InvalidInputException {
|
||||
final Operations.Receipt receipt = Operations.getPrescribedReceipt();
|
||||
Operations.deleteReceipt(receipt.serial());
|
||||
TestUser user = null;
|
||||
try {
|
||||
user = Operations.registerNumberlessUser(receipt.credential());
|
||||
final Pair<Integer, AccountIdentityResponse> execute = Operations.apiGet("/v1/accounts/whoami")
|
||||
.authorized(user)
|
||||
.execute(AccountIdentityResponse.class);
|
||||
assertEquals(HttpStatus.SC_OK, execute.getLeft());
|
||||
} finally {
|
||||
Operations.deleteReceipt(receipt.serial());
|
||||
if (user != null) {
|
||||
Operations.deleteUser(user);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Nested
|
||||
class RecoverWithMfa {
|
||||
private TestUser user;
|
||||
|
||||
@BeforeEach
|
||||
void setup() throws InvalidInputException, VerificationFailedException {
|
||||
final Operations.Receipt receipt = Operations.getPrescribedReceipt();
|
||||
|
||||
// Clear receipt state in case a previous run had an unclean failure
|
||||
Operations.deleteReceipt(receipt.serial());
|
||||
user = Operations.registerNumberlessUser(receipt.credential());
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void teardown() throws InvalidInputException {
|
||||
final Operations.Receipt receipt = Operations.getPrescribedReceipt();
|
||||
Operations.deleteReceipt(receipt.serial());
|
||||
if (user != null) {
|
||||
Operations.deleteUser(user);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void testRecoverWithTotp() throws NoSuchAlgorithmException, InvalidKeyException {
|
||||
final GenerateTotpKeyResponse generateTotpKeyResponse =
|
||||
getAccountsStubForUser(user).generateTotpKey(GenerateTotpKeyRequest.getDefaultInstance());
|
||||
assertEquals(GenerateTotpKeyResponse.ResponseCase.KEY_GENERATED, generateTotpKeyResponse.getResponseCase());
|
||||
|
||||
final TotpParameters totpParameters = generateTotpKeyResponse.getKeyGenerated().getTotpParameters();
|
||||
final TimeBasedOneTimePasswordGenerator totpGenerator = new TimeBasedOneTimePasswordGenerator(
|
||||
Duration.ofSeconds(totpParameters.getTimeStepSeconds()),
|
||||
totpParameters.getPasswordLength(),
|
||||
totpParameters.getAlgorithm());
|
||||
|
||||
final SecretKey totpKey = new SecretKeySpec(
|
||||
generateTotpKeyResponse.getKeyGenerated().getKey().toByteArray(),
|
||||
totpParameters.getAlgorithm());
|
||||
|
||||
final byte[] totpMetadata = Operations.randomBytes(160);
|
||||
|
||||
final ConfirmTotpKeyResponse confirmTotpKeyResponse = getAccountsStubForUser(user)
|
||||
.confirmTotpKey(ConfirmTotpKeyRequest.newBuilder()
|
||||
.setOneTimePassword(totpGenerator.generateOneTimePassword(totpKey, Instant.now()))
|
||||
.setMetadataCiphertext(ByteString.copyFrom(totpMetadata))
|
||||
.build());
|
||||
assertEquals(ConfirmTotpKeyResponse.ResponseCase.KEY_CONFIRMED, confirmTotpKeyResponse.getResponseCase());
|
||||
final int keyId = confirmTotpKeyResponse.getKeyConfirmed().getKeyId();
|
||||
|
||||
final TestUser recoveredUser =
|
||||
Operations.recoverNumberlessUserWithTotp(user, totpGenerator.generateOneTimePassword(totpKey, Instant.now()));
|
||||
|
||||
assertEquals(user.aciUuid(), recoveredUser.aciUuid());
|
||||
|
||||
// MFA key should remain set after re-registration
|
||||
final Map<Integer, ListMfaKeysResponse.MfaKeyMetadata> mfaKeys =
|
||||
getAccountsStubForUser(recoveredUser).listMfaKeys(ListMfaKeysRequest.getDefaultInstance()).getKeysMap();
|
||||
|
||||
assertEquals(1, mfaKeys.size());
|
||||
assertTrue(mfaKeys.containsKey(keyId));
|
||||
assertEquals(ListMfaKeysResponse.MfaKeyMetadata.MfaKeyType.MFA_KEY_TYPE_TOTP, mfaKeys.get(keyId).getType());
|
||||
assertArrayEquals(totpMetadata, mfaKeys.get(keyId).getMetadataCiphertext().toByteArray());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testRecoverWithWebAuthn() {
|
||||
final WebAuthnConfiguration webAuthnConfiguration = Operations.getWebAuthnConfiguration();
|
||||
final ClientPlatform clientPlatform = new ClientPlatform(new Origin(webAuthnConfiguration.origin()), new WebAuthnAuthenticatorAdaptor(EmulatorUtil.NONE_ATTESTATION_AUTHENTICATOR));
|
||||
final COSEAlgorithmIdentifier algorithm = COSEAlgorithmIdentifier.ES256;
|
||||
|
||||
final StartWebAuthnRegistrationResponse startWebAuthnRegistrationResponse =
|
||||
getAccountsStubForUser(user).startWebAuthnRegistration(StartWebAuthnRegistrationRequest.getDefaultInstance());
|
||||
assertEquals(StartWebAuthnRegistrationResponse.ResponseCase.PARAMS,
|
||||
startWebAuthnRegistrationResponse.getResponseCase());
|
||||
|
||||
final StartWebAuthnRegistrationResponse.WebAuthnCreateParameters webAuthnCreateParameters = startWebAuthnRegistrationResponse.getParams();
|
||||
|
||||
assertTrue(
|
||||
webAuthnCreateParameters.getAllowedAlgorithmsList().contains(algorithm.getValue()));
|
||||
|
||||
final PublicKeyCredential<AuthenticatorAttestationResponse, ?> credential =
|
||||
clientPlatform.create(new PublicKeyCredentialCreationOptions(
|
||||
new PublicKeyCredentialRpEntity(webAuthnConfiguration.relyingPartyId(), "test"),
|
||||
new PublicKeyCredentialUserEntity(webAuthnCreateParameters.getUserHandle().toByteArray(), "test", "test"),
|
||||
new DefaultChallenge(),
|
||||
List.of(new PublicKeyCredentialParameters(PublicKeyCredentialType.PUBLIC_KEY, algorithm)),
|
||||
null,
|
||||
List.of(),
|
||||
new AuthenticatorSelectionCriteria(
|
||||
null, false, ResidentKeyRequirement.DISCOURAGED, UserVerificationRequirement.DISCOURAGED),
|
||||
AttestationConveyancePreference.NONE,
|
||||
null));
|
||||
|
||||
final byte[] metadataCiphertext = Operations.randomBytes(160);
|
||||
|
||||
final FinishWebAuthnRegistrationResponse finishWebAuthnRegistrationResponse = getAccountsStubForUser(user)
|
||||
.finishWebAuthnRegistration(FinishWebAuthnRegistrationRequest.newBuilder()
|
||||
.setAttestationObject(ByteString.copyFrom(credential.getResponse().getAttestationObject()))
|
||||
.setCollectedClientDataJsonBytes(ByteString.copyFrom(credential.getResponse().getClientDataJSON()))
|
||||
.setMetadataCiphertext(ByteString.copyFrom(metadataCiphertext))
|
||||
.build());
|
||||
assertEquals(FinishWebAuthnRegistrationResponse.ResponseCase.KEY_CONFIRMED,
|
||||
finishWebAuthnRegistrationResponse.getResponseCase());
|
||||
final int keyId = finishWebAuthnRegistrationResponse.getKeyConfirmed().getKeyId();
|
||||
|
||||
final TestUser recoveredUser = Operations.recoverNumberlessUserWithWebAuthn(user, clientPlatform, credential.getRawId(),
|
||||
webAuthnConfiguration.relyingPartyId());
|
||||
|
||||
assertEquals(user.aciUuid(), recoveredUser.aciUuid());
|
||||
|
||||
// MFA key should remain set after re-registration
|
||||
final Map<Integer, ListMfaKeysResponse.MfaKeyMetadata> mfaKeys =
|
||||
getAccountsStubForUser(recoveredUser).listMfaKeys(ListMfaKeysRequest.getDefaultInstance()).getKeysMap();
|
||||
|
||||
assertEquals(1, mfaKeys.size());
|
||||
assertTrue(mfaKeys.containsKey(keyId));
|
||||
assertEquals(ListMfaKeysResponse.MfaKeyMetadata.MfaKeyType.MFA_KEY_TYPE_WEBAUTHN, mfaKeys.get(keyId).getType());
|
||||
assertArrayEquals(metadataCiphertext, mfaKeys.get(keyId).getMetadataCiphertext().toByteArray());
|
||||
}
|
||||
}
|
||||
|
||||
private static AccountsGrpc.AccountsBlockingStub getAccountsStubForUser(final TestUser user) {
|
||||
return AccountsGrpc
|
||||
.newBlockingStub(Operations.grpcChannel())
|
||||
.withInterceptors(Operations.authorizationInterceptor(user, Device.PRIMARY_ID));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testCreateAccount() {
|
||||
final TestUser user = Operations.newRegisteredUser("+19995550101");
|
||||
@@ -72,7 +265,7 @@ public class AccountTest {
|
||||
|
||||
assertEquals(user.aciUuid(), accountIdentityResponse.uuid());
|
||||
assertNotEquals(user.pniUuid(), accountIdentityResponse.pni());
|
||||
assertEquals(targetNumber, accountIdentityResponse.number());
|
||||
assertEquals(Optional.of(targetNumber), accountIdentityResponse.number());
|
||||
} finally {
|
||||
Operations.deleteUser(user);
|
||||
}
|
||||
|
||||
@@ -11,20 +11,16 @@ import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertTimeoutPreemptively;
|
||||
|
||||
import com.google.common.net.HttpHeaders;
|
||||
import jakarta.ws.rs.core.MediaType;
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.Duration;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import jakarta.ws.rs.core.MediaType;
|
||||
import org.junit.jupiter.api.AfterAll;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.Timeout;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.entities.IncomingMessage;
|
||||
import org.whispersystems.textsecuregcm.entities.IncomingMessageList;
|
||||
import org.whispersystems.textsecuregcm.entities.MessageProtos;
|
||||
@@ -65,7 +61,7 @@ public class MessagingTest {
|
||||
assertDoesNotThrow(() -> WebsocketClientSession.decode(SendMessageResponse.class, responseMessage));
|
||||
|
||||
final WebsocketClientSession websocketB = Operations.authenticatedWebsocket(userB, Device.PRIMARY_ID);
|
||||
assertTimeoutPreemptively(Duration.ofSeconds(5), websocketB::waitForQueueEmpty);
|
||||
assertTimeoutPreemptively(Duration.ofSeconds(15), websocketB::waitForQueueEmpty);
|
||||
|
||||
assertEquals(1, websocketB.getReceivedEnvelopes().size());
|
||||
final MessageProtos.Envelope envelope = websocketB.getReceivedEnvelopes().getFirst();
|
||||
|
||||
@@ -45,57 +45,60 @@
|
||||
</modules>
|
||||
|
||||
<properties>
|
||||
<aws.sdk2.version>2.42.27</aws.sdk2.version>
|
||||
<braintree.version>3.48.0</braintree.version>
|
||||
<aws.sdk2.version>2.54.7</aws.sdk2.version>
|
||||
<braintree.version>3.53.0</braintree.version>
|
||||
<commons-csv.version>1.14.1</commons-csv.version>
|
||||
<commons-io.version>2.21.0</commons-io.version>
|
||||
<dropwizard.version>5.0.1</dropwizard.version>
|
||||
<commons-io.version>2.22.0</commons-io.version>
|
||||
<dropwizard.version>5.0.2</dropwizard.version>
|
||||
<!-- Note: We use x86_64 builds without AVX instructions enabled (i.e. FoundationDB versions with even-numbered
|
||||
patch versions). Also when updating FoundationDB, make sure to update the version of FoundationDBused by GitHub
|
||||
Actions. -->
|
||||
<foundationdb.version>7.3.68</foundationdb.version>
|
||||
patch versions). -->
|
||||
<foundationdb.version>7.3.76</foundationdb.version>
|
||||
<foundationdb.api-version>730</foundationdb.api-version>
|
||||
<foundationdb.client-library-sha256>8c96a1f7ab561cd38e16e4c269c5e50ae0fd8063854e0d72c89339a7ac1b6873</foundationdb.client-library-sha256>
|
||||
<google-cloud-libraries.version>26.79.0</google-cloud-libraries.version>
|
||||
<foundationdb.client-library-sha256>af099848721d08904ff9e5d38fade0de24d92e86451ea491d9ab5ce84adcf62a</foundationdb.client-library-sha256>
|
||||
<google-cloud-libraries.version>26.87.0</google-cloud-libraries.version>
|
||||
<grpc.version>1.76.3</grpc.version> <!-- should be kept in sync with the value from Google libraries-bom -->
|
||||
<gson.version>2.13.2</gson.version>
|
||||
<guava.version>33.5.0-jre</guava.version>
|
||||
<gson.version>2.14.0</gson.version>
|
||||
<guava.version>33.7.1-jre</guava.version>
|
||||
<!-- several libraries (AWS, Google Cloud) use Apache http components transitively, and we need to align them -->
|
||||
<httpcore.version>4.4.16</httpcore.version>
|
||||
<httpclient.version>4.5.14</httpclient.version>
|
||||
<jackson.version>2.21.2</jackson.version>
|
||||
<jackson.version>2.22.2</jackson.version>
|
||||
<java-otp.version>1.0.0</java-otp.version>
|
||||
<jetty.version>12.1.9</jetty.version>
|
||||
<junit-pioneer.version>2.3.0</junit-pioneer.version>
|
||||
<jsr305.version>3.0.2</jsr305.version>
|
||||
<kotlin.version>2.3.20</kotlin.version>
|
||||
<kotlin.version>2.4.10</kotlin.version>
|
||||
<!-- dropwizard references a constant removed in 1.6. See also: dependabot.yml -->
|
||||
<logback.version>1.5.38</logback.version>
|
||||
<logback-access-common.version>2.0.12</logback-access-common.version>
|
||||
<lettuce.version>7.5.1.RELEASE</lettuce.version>
|
||||
<libphonenumber.version>9.0.21</libphonenumber.version>
|
||||
<logstash.logback.version>8.1</logstash.logback.version>
|
||||
<log4j-bom.version>2.25.4</log4j-bom.version>
|
||||
<luajava.version>3.5.0</luajava.version>
|
||||
<micrometer.version>1.16.4</micrometer.version>
|
||||
<netty.version>4.2.13.Final</netty.version>
|
||||
<!-- Must be less than or equal to the value from Google libraries-bom which controls the protobuf runtime version.
|
||||
See https://protobuf.dev/support/cross-version-runtime-guarantee/. -->
|
||||
<protoc.version>4.33.2</protoc.version>
|
||||
<pushy.version>0.15.4</pushy.version>
|
||||
<reactor-bom.version>2025.0.4</reactor-bom.version> <!-- 3.8.4, see https://github.com/reactor/reactor#bom-versioning-scheme -->
|
||||
<logback-access-common.version>2.0.15</logback-access-common.version>
|
||||
<lettuce.version>7.6.0.RELEASE</lettuce.version>
|
||||
<libphonenumber.version>9.0.38</libphonenumber.version>
|
||||
<logstash.logback.version>9.0</logstash.logback.version>
|
||||
<log4j-bom.version>2.26.1</log4j-bom.version>
|
||||
<luajava.version>4.1.0</luajava.version>
|
||||
<micrometer.version>1.17.1</micrometer.version>
|
||||
<netty.version>4.2.18.Final</netty.version>
|
||||
<!-- must be greater than or equal to the value from Google libraries-bom, see https://protobuf.dev/support/cross-version-runtime-guarantee/ -->
|
||||
<!-- the latest 4.x should be fine https://central.sonatype.com/artifact/com.google.protobuf/protobuf-java/versions -->
|
||||
<protobuf.version>4.36.0</protobuf.version>
|
||||
<pushy.version>0.15.6</pushy.version>
|
||||
<reactor-bom.version>2025.0.7</reactor-bom.version> <!-- 3.8.4, see https://github.com/reactor/reactor#bom-versioning-scheme -->
|
||||
<resilience4j.version>2.4.0</resilience4j.version>
|
||||
<semver4j.version>3.1.0</semver4j.version>
|
||||
<simple-grpc.version>0.2.0</simple-grpc.version>
|
||||
<slf4j.version>2.0.17</slf4j.version>
|
||||
<stripe.version>33.1.0</stripe.version>
|
||||
<swagger.version>2.2.46</swagger.version>
|
||||
<testcontainers.version>2.0.4</testcontainers.version>
|
||||
<simple-grpc.version>0.2.1</simple-grpc.version>
|
||||
<slf4j.version>2.0.18</slf4j.version>
|
||||
<stripe.version>33.4.0</stripe.version>
|
||||
<swagger.version>2.2.54</swagger.version>
|
||||
<testcontainers.version>2.0.5</testcontainers.version>
|
||||
<webauthn4j.version>0.31.9.RELEASE</webauthn4j.version>
|
||||
|
||||
<!-- images to use in tests via testcontainers -->
|
||||
<dynamodb.image>amazon/dynamodb-local:3.3.0@sha256:d89f8fcc6b1a39cb35976c248ed42a28c66ae00dc043099210f5571e42648ab4</dynamodb.image>
|
||||
<dynamodb.image>amazon/dynamodb-local:3.3.1@sha256:ff89bd48ff32cd8d9be5fee8873b65b8854dc408f1afe881be6eb00247bc0dab</dynamodb.image>
|
||||
<localstack.image>localstack/localstack:4.14@sha256:3ebc37595918b8accb852f8048fef2aff047d465167edd655528065b07bc364a</localstack.image>
|
||||
<redis.image>redis:7.4-alpine@sha256:6ab0b6e7381779332f97b8ca76193e45b0756f38d4c0dcda72dbb3c32061ab99</redis.image>
|
||||
<redis-cluster.image>docker.io/bitnamilegacy/redis-cluster:7.4.3@sha256:a53d023fdfaf8a8d7ddc58da040d3494e4cb45772644618ffa44c42dcd32b9af</redis-cluster.image>
|
||||
|
||||
<docker.image>eclipse-temurin:25-jre-resolute@sha256:17ddcc32b1f296155738c4b2f689208e46bf0cf4eb0b215c717717deb8b74b90</docker.image>
|
||||
<docker.image>eclipse-temurin:26-jre-resolute@sha256:c3b6e31e48772c98e8868654e5f21fb2c3670e67c055ddd76d8cf37e62113eb5</docker.image>
|
||||
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
</properties>
|
||||
@@ -105,7 +108,9 @@
|
||||
<version>JGITVER</version>
|
||||
|
||||
<dependencyManagement>
|
||||
<!-- note: order matters, and earlier declarations take precedence -->
|
||||
<dependencies>
|
||||
<!-- use a pinned version of jackson, rather than Dropwizard's BOM -->
|
||||
<dependency>
|
||||
<groupId>com.fasterxml.jackson</groupId>
|
||||
<artifactId>jackson-bom</artifactId>
|
||||
@@ -113,6 +118,50 @@
|
||||
<type>pom</type>
|
||||
<scope>import</scope>
|
||||
</dependency>
|
||||
<!-- use a pinned version of jetty, rather than Dropwizard's BOM -->
|
||||
<dependency>
|
||||
<groupId>org.eclipse.jetty</groupId>
|
||||
<artifactId>jetty-bom</artifactId>
|
||||
<version>${jetty.version}</version>
|
||||
<type>pom</type>
|
||||
<scope>import</scope>
|
||||
</dependency>
|
||||
<!-- use a pinned version of jetty, rather than Dropwizard's BOM -->
|
||||
<dependency>
|
||||
<groupId>org.eclipse.jetty.ee10</groupId>
|
||||
<artifactId>jetty-ee10-bom</artifactId>
|
||||
<version>${jetty.version}</version>
|
||||
<type>pom</type>
|
||||
<scope>import</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>io.netty</groupId>
|
||||
<artifactId>netty-bom</artifactId>
|
||||
<version>${netty.version}</version>
|
||||
<type>pom</type>
|
||||
<scope>import</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.google.protobuf</groupId>
|
||||
<artifactId>protobuf-bom</artifactId>
|
||||
<type>pom</type>
|
||||
<scope>import</scope>
|
||||
<version>${protobuf.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.google.cloud</groupId>
|
||||
<artifactId>libraries-bom</artifactId>
|
||||
<version>${google-cloud-libraries.version}</version>
|
||||
<type>pom</type>
|
||||
<scope>import</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>software.amazon.awssdk</groupId>
|
||||
<artifactId>bom</artifactId>
|
||||
<version>${aws.sdk2.version}</version>
|
||||
<type>pom</type>
|
||||
<scope>import</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>io.dropwizard</groupId>
|
||||
<artifactId>dropwizard-dependencies</artifactId>
|
||||
@@ -127,27 +176,6 @@
|
||||
<version>6.0.53</version>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>io.netty</groupId>
|
||||
<artifactId>netty-bom</artifactId>
|
||||
<version>${netty.version}</version>
|
||||
<type>pom</type>
|
||||
<scope>import</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>software.amazon.awssdk</groupId>
|
||||
<artifactId>bom</artifactId>
|
||||
<version>${aws.sdk2.version}</version>
|
||||
<type>pom</type>
|
||||
<scope>import</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.google.cloud</groupId>
|
||||
<artifactId>libraries-bom</artifactId>
|
||||
<version>${google-cloud-libraries.version}</version>
|
||||
<type>pom</type>
|
||||
<scope>import</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>io.github.resilience4j</groupId>
|
||||
<artifactId>resilience4j-bom</artifactId>
|
||||
@@ -165,14 +193,14 @@
|
||||
<dependency>
|
||||
<groupId>io.opentelemetry</groupId>
|
||||
<artifactId>opentelemetry-bom</artifactId>
|
||||
<version>1.60.1</version>
|
||||
<version>1.65.0</version>
|
||||
<type>pom</type>
|
||||
<scope>import</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>io.opentelemetry.instrumentation</groupId>
|
||||
<artifactId>opentelemetry-instrumentation-bom</artifactId>
|
||||
<version>2.26.1</version>
|
||||
<version>2.31.1</version>
|
||||
<type>pom</type>
|
||||
<scope>import</scope>
|
||||
</dependency>
|
||||
@@ -190,6 +218,11 @@
|
||||
<type>pom</type>
|
||||
<scope>import</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.eatthepath</groupId>
|
||||
<artifactId>java-otp</artifactId>
|
||||
<version>${java-otp.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.eatthepath</groupId>
|
||||
<artifactId>pushy</artifactId>
|
||||
@@ -249,7 +282,7 @@
|
||||
<dependency>
|
||||
<groupId>commons-logging</groupId>
|
||||
<artifactId>commons-logging</artifactId>
|
||||
<version>1.3.6</version>
|
||||
<version>1.4.0</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.stripe</groupId>
|
||||
@@ -285,7 +318,7 @@
|
||||
<dependency>
|
||||
<groupId>org.signal</groupId>
|
||||
<artifactId>libsignal-server</artifactId>
|
||||
<version>0.96.2</version>
|
||||
<version>0.101.2</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.signal</groupId>
|
||||
@@ -354,7 +387,7 @@
|
||||
<dependency>
|
||||
<groupId>org.wiremock</groupId>
|
||||
<artifactId>wiremock-jetty12</artifactId>
|
||||
<version>3.13.1</version>
|
||||
<version>3.13.2</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
@@ -422,32 +455,32 @@
|
||||
<plugin>
|
||||
<groupId>com.google.cloud.tools</groupId>
|
||||
<artifactId>jib-maven-plugin</artifactId>
|
||||
<version>3.4.6</version>
|
||||
<version>3.5.2</version>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-surefire-plugin</artifactId>
|
||||
<version>3.5.5</version>
|
||||
<version>3.5.6</version>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-failsafe-plugin</artifactId>
|
||||
<version>3.5.4</version>
|
||||
<version>3.5.6</version>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-jar-plugin</artifactId>
|
||||
<version>3.5.0</version>
|
||||
<version>3.5.1</version>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-shade-plugin</artifactId>
|
||||
<version>3.6.1</version>
|
||||
<version>3.6.2</version>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-assembly-plugin</artifactId>
|
||||
<version>3.7.1</version>
|
||||
<version>3.8.0</version>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.codehaus.mojo</groupId>
|
||||
@@ -457,7 +490,7 @@
|
||||
<plugin>
|
||||
<groupId>org.codehaus.mojo</groupId>
|
||||
<artifactId>properties-maven-plugin</artifactId>
|
||||
<version>1.2.1</version>
|
||||
<version>1.3.0</version>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</pluginManagement>
|
||||
@@ -469,7 +502,7 @@
|
||||
<version>0.6.1</version>
|
||||
<configuration>
|
||||
<checkStaleness>false</checkStaleness>
|
||||
<protocArtifact>com.google.protobuf:protoc:${protoc.version}:exe:${os.detected.classifier}</protocArtifact>
|
||||
<protocArtifact>com.google.protobuf:protoc:${protobuf.version}:exe:${os.detected.classifier}</protocArtifact>
|
||||
<pluginId>grpc-java</pluginId>
|
||||
<pluginArtifact>io.grpc:protoc-gen-grpc-java:${grpc.version}:exe:${os.detected.classifier}</pluginArtifact>
|
||||
|
||||
@@ -500,14 +533,14 @@
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<version>3.15.0</version>
|
||||
<configuration>
|
||||
<release>25</release>
|
||||
<release>26</release>
|
||||
</configuration>
|
||||
</plugin>
|
||||
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-jar-plugin</artifactId>
|
||||
<version>3.5.0</version>
|
||||
<version>3.5.1</version>
|
||||
<configuration>
|
||||
<archive>
|
||||
<manifest>
|
||||
@@ -520,7 +553,7 @@
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-dependency-plugin</artifactId>
|
||||
<version>3.10.0</version>
|
||||
<version>3.11.0</version>
|
||||
<executions>
|
||||
<execution>
|
||||
<!--
|
||||
@@ -540,7 +573,7 @@
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-enforcer-plugin</artifactId>
|
||||
<version>3.6.2</version>
|
||||
<version>3.6.3</version>
|
||||
<executions>
|
||||
<execution>
|
||||
<goals>
|
||||
|
||||
@@ -79,7 +79,8 @@ storageService.userAuthenticationTokenSharedSecret: AAAAAAAAAAAAAAAAAAAAAAAAAAAA
|
||||
|
||||
zkConfig-libsignal-0.42.serverSecret: ABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdef
|
||||
|
||||
callingZkConfig.serverSecret: ABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzAA==
|
||||
callingZkConfigPreV101.serverSecret: ABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzAA==
|
||||
callingZkConfigV101.serverSecret: ABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzAA==
|
||||
chatZkConfig.serverSecret: ABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzAA==
|
||||
|
||||
paymentsService.userAuthenticationTokenSharedSecret: AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA= # base64-encoded 32-byte secret shared with MobileCoin services used to generate auth tokens for Signal users
|
||||
@@ -101,3 +102,5 @@ hlrLookup.apiKey: AAAAAAAAAAA
|
||||
hlrLookup.apiSecret: AAAAAAAAAAA
|
||||
|
||||
foundationDbMessages.versionstampCipherKey.0: AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=
|
||||
|
||||
registrationWebAuthn.userHandleBlindingSecret: AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=
|
||||
@@ -74,7 +74,6 @@ appleDeviceCheck:
|
||||
|
||||
deviceCheck:
|
||||
backupRedemptionDuration: P30D
|
||||
backupRedemptionLevel: 201
|
||||
|
||||
dynamoDbClient:
|
||||
region: us-west-2 # AWS Region
|
||||
@@ -105,9 +104,8 @@ dynamoDbTables:
|
||||
expiration: P7D # Duration of time until rows expire
|
||||
issuedReceipts:
|
||||
tableName: Example_IssuedReceipts
|
||||
expiration: P30D # Duration of time until rows expire
|
||||
generator: abcdefg12345678= # random base64-encoded binary sequence
|
||||
maxIssuedReceiptsPerPaymentId:
|
||||
maxReceiptsPerSubscriptionPayment:
|
||||
STRIPE: 1
|
||||
BRAINTREE: 1
|
||||
GOOGLE_PLAY_BILLING: 1
|
||||
@@ -140,7 +138,6 @@ dynamoDbTables:
|
||||
tableName: Example_PushNotificationExperimentSamples
|
||||
redeemedReceipts:
|
||||
tableName: Example_RedeemedReceipts
|
||||
expiration: P30D # Duration of time until rows expire
|
||||
registrationRecovery:
|
||||
tableName: Example_RegistrationRecovery
|
||||
expiration: P300D # Duration of time until rows expire
|
||||
@@ -318,8 +315,11 @@ storageService:
|
||||
AAAAAAAAAAAAAAAAAAAA
|
||||
-----END CERTIFICATE-----
|
||||
|
||||
callingZkConfigPreV101:
|
||||
serverSecret: secret://callingZkConfigPreV101.serverSecret
|
||||
|
||||
callingZkConfig:
|
||||
serverSecret: secret://callingZkConfig.serverSecret
|
||||
serverSecret: secret://callingZkConfigV101.serverSecret
|
||||
|
||||
chatZkConfig:
|
||||
serverSecret: secret://chatZkConfig.serverSecret
|
||||
@@ -366,7 +366,7 @@ badges:
|
||||
- light: example-light.svg
|
||||
dark: example-dark.svg
|
||||
receiptLevels:
|
||||
'1': TEST
|
||||
ONE_TIME_DONATION: TEST
|
||||
|
||||
subscription: # configuration for Stripe subscriptions
|
||||
badgeExpiration: P30D
|
||||
@@ -385,14 +385,17 @@ subscription: # configuration for Stripe subscriptions
|
||||
STRIPE: price_example # stripe Price ID
|
||||
BRAINTREE: plan_example # braintree Plan ID
|
||||
|
||||
loginPurchase:
|
||||
playProductId: login_example
|
||||
playOptionId: login_option_example
|
||||
appStoreProductId: login_example
|
||||
|
||||
oneTimeDonations:
|
||||
sepaMaximumEuros: '10000'
|
||||
boost:
|
||||
level: 1
|
||||
expiration: P90D
|
||||
badge: EXAMPLE
|
||||
gift:
|
||||
level: 10
|
||||
expiration: P90D
|
||||
badge: EXAMPLE
|
||||
currencies:
|
||||
@@ -569,3 +572,9 @@ foundationDbMessages:
|
||||
- messages-1
|
||||
- messages-2
|
||||
- messages-3
|
||||
|
||||
registrationWebAuthn:
|
||||
relyingPartyId: example.org
|
||||
origin: https://example.org
|
||||
challengeTtl: PT2M
|
||||
userHandleBlindingSecret: secret://registrationWebAuthn.userHandleBlindingSecret
|
||||
+60
-20
@@ -11,19 +11,17 @@
|
||||
<artifactId>service</artifactId>
|
||||
|
||||
<properties>
|
||||
<apollo-api-jvm.version>3.8.5</apollo-api-jvm.version>
|
||||
<apollo-api-jvm.version>3.8.6</apollo-api-jvm.version>
|
||||
<commons-compress.version>1.28.0</commons-compress.version>
|
||||
<dynamodb-lock-client.version>1.4.0</dynamodb-lock-client.version>
|
||||
<firebase-admin.version>9.7.0</firebase-admin.version>
|
||||
<libphonenumber-geocoder.version>3.23</libphonenumber-geocoder.version>
|
||||
<dynamodb-lock-client.version>1.5.0</dynamodb-lock-client.version>
|
||||
<firebase-admin.version>9.10.0</firebase-admin.version>
|
||||
<libphonenumber-geocoder.version>3.38</libphonenumber-geocoder.version>
|
||||
<google-androidpublisher.version>v3-rev20250904-2.0.0</google-androidpublisher.version>
|
||||
<java-jwt.version>4.5.0</java-jwt.version>
|
||||
<java-jwt.version>4.6.0</java-jwt.version>
|
||||
<java-uuid-generator.version>5.2.0</java-uuid-generator.version>
|
||||
<!-- *all* opentelemetry-logback-appender versions are "alpha" despite the advanced version number -->
|
||||
<opentelemetry-logback-appender-1.0.version>2.22.0-alpha</opentelemetry-logback-appender-1.0.version>
|
||||
<storekit.version>4.0.0</storekit.version>
|
||||
<webauthn4j.version>0.30.2.RELEASE</webauthn4j.version>
|
||||
<jetty.http2-client.version>12.1.5</jetty.http2-client.version>
|
||||
<opentelemetry-logback-appender-1.0.version>2.31.1-alpha</opentelemetry-logback-appender-1.0.version>
|
||||
<storekit.version>5.2.0</storekit.version>
|
||||
</properties>
|
||||
|
||||
<dependencies>
|
||||
@@ -47,6 +45,11 @@
|
||||
<groupId>com.squareup.okio</groupId>
|
||||
<artifactId>okio-jvm</artifactId>
|
||||
</exclusion>
|
||||
<!-- conflicts with our direct dependency -->
|
||||
<exclusion>
|
||||
<groupId>com.auth0</groupId>
|
||||
<artifactId>java-jwt</artifactId>
|
||||
</exclusion>
|
||||
</exclusions>
|
||||
</dependency>
|
||||
<dependency>
|
||||
@@ -54,6 +57,11 @@
|
||||
<artifactId>webauthn4j-appattest</artifactId>
|
||||
<version>${webauthn4j.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.webauthn4j</groupId>
|
||||
<artifactId>webauthn4j-core</artifactId>
|
||||
<version>${webauthn4j.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>io.swagger.core.v3</groupId>
|
||||
<artifactId>swagger-jaxrs2-jakarta</artifactId>
|
||||
@@ -142,7 +150,6 @@
|
||||
<groupId>org.eclipse.jetty.http2</groupId>
|
||||
<artifactId>jetty-http2-client-transport</artifactId>
|
||||
<scope>test</scope>
|
||||
<version>${jetty.http2-client.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>io.dropwizard</groupId>
|
||||
@@ -173,6 +180,20 @@
|
||||
<dependency>
|
||||
<groupId>net.logstash.logback</groupId>
|
||||
<artifactId>logstash-logback-encoder</artifactId>
|
||||
<exclusions>
|
||||
<!-- conflicts with webauthn4j-appattest -->
|
||||
<exclusion>
|
||||
<groupId>tools.jackson.core</groupId>
|
||||
<artifactId>jackson-databind</artifactId>
|
||||
</exclusion>
|
||||
</exclusions>
|
||||
</dependency>
|
||||
<!-- sentinel for dependency convergence -->
|
||||
<dependency>
|
||||
<groupId>tools.jackson.core</groupId>
|
||||
<artifactId>jackson-databind</artifactId>
|
||||
<!-- update dependabot.yml when this dependency is removed -->
|
||||
<version>3.2.1</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
@@ -284,16 +305,11 @@
|
||||
<groupId>com.google.firebase</groupId>
|
||||
<artifactId>firebase-admin</artifactId>
|
||||
<version>${firebase-admin.version}</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>com.google.cloud</groupId>
|
||||
<artifactId>google-cloud-firestore</artifactId>
|
||||
<exclusions>
|
||||
<!-- incubator packages aren't included in the opentelemetry BOM, and we don't use them -->
|
||||
<exclusion>
|
||||
<groupId>io.opentelemetry.instrumentation</groupId>
|
||||
<artifactId>opentelemetry-instrumentation-api-incubator</artifactId>
|
||||
<!-- conflicts with jackson-dataformat 2.22.1 -->
|
||||
<groupId>org.codehaus.woodstox</groupId>
|
||||
<artifactId>stax2-api</artifactId>
|
||||
</exclusion>
|
||||
</exclusions>
|
||||
</dependency>
|
||||
@@ -303,6 +319,17 @@
|
||||
<artifactId>jsr305</artifactId>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<!-- manually resolve dependency conflict -->
|
||||
<groupId>org.codehaus.woodstox</groupId>
|
||||
<artifactId>stax2-api</artifactId>
|
||||
<version>4.3.0</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>io.github.resilience4j</groupId>
|
||||
<artifactId>resilience4j-bulkhead</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>io.github.resilience4j</groupId>
|
||||
<artifactId>resilience4j-circuitbreaker</artifactId>
|
||||
@@ -404,6 +431,11 @@
|
||||
<artifactId>lettuce-core</artifactId>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>com.eatthepath</groupId>
|
||||
<artifactId>java-otp</artifactId>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>com.eatthepath</groupId>
|
||||
<artifactId>pushy</artifactId>
|
||||
@@ -548,6 +580,13 @@
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>com.webauthn4j</groupId>
|
||||
<artifactId>webauthn4j-test</artifactId>
|
||||
<version>${webauthn4j.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>com.fasterxml.uuid</groupId>
|
||||
<artifactId>java-uuid-generator</artifactId>
|
||||
@@ -616,7 +655,8 @@
|
||||
<dependency>
|
||||
<groupId>com.squareup.okio</groupId>
|
||||
<artifactId>okio-jvm</artifactId>
|
||||
<version>3.16.4</version>
|
||||
<!-- update dependabot.yml when this dependency is removed -->
|
||||
<version>3.17.0</version>
|
||||
</dependency>
|
||||
|
||||
</dependencies>
|
||||
@@ -831,7 +871,7 @@
|
||||
<plugin>
|
||||
<groupId>org.codehaus.mojo</groupId>
|
||||
<artifactId>templating-maven-plugin</artifactId>
|
||||
<version>3.0.0</version>
|
||||
<version>3.1.0</version>
|
||||
<executions>
|
||||
<execution>
|
||||
<id>filter-src</id>
|
||||
|
||||
+48
@@ -20,6 +20,7 @@ import org.whispersystems.textsecuregcm.configuration.AwsCredentialsProviderFact
|
||||
import org.whispersystems.textsecuregcm.configuration.BackupConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.BadgesConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.BraintreeConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.BulkheadConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.CallQualitySurveyConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.Cdn3StorageManagerConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.CdnConfiguration;
|
||||
@@ -44,6 +45,7 @@ import org.whispersystems.textsecuregcm.configuration.HlrLookupConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.IdlePrimaryDeviceReminderConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.KeyTransparencyServiceConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.LinkDeviceSecretConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.LoginPurchaseConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.MessageByteLimitCardinalityEstimatorConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.MessageCacheConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.OneTimeDonationConfiguration;
|
||||
@@ -62,9 +64,11 @@ import org.whispersystems.textsecuregcm.configuration.SpamFilterConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.StripeConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.SubscriptionConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.TlsKeyStoreConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.TotpConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.TurnConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.UnidentifiedDeliveryConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.VirtualThreadConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.WebAuthnConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.ZkConfig;
|
||||
import org.whispersystems.websocket.configuration.WebSocketConfiguration;
|
||||
|
||||
@@ -226,6 +230,11 @@ public class WhisperServerConfiguration extends Configuration {
|
||||
@JsonProperty
|
||||
private PaymentsServiceConfiguration paymentsService;
|
||||
|
||||
@Valid
|
||||
@NotNull
|
||||
@JsonProperty
|
||||
private GenericZkConfig callingZkConfigPreV101;
|
||||
|
||||
@Valid
|
||||
@NotNull
|
||||
@JsonProperty
|
||||
@@ -266,6 +275,11 @@ public class WhisperServerConfiguration extends Configuration {
|
||||
@NotNull
|
||||
private OneTimeDonationConfiguration oneTimeDonations;
|
||||
|
||||
@Valid
|
||||
@JsonProperty
|
||||
@NotNull
|
||||
private LoginPurchaseConfiguration loginPurchase;
|
||||
|
||||
@Valid
|
||||
@JsonProperty
|
||||
@NotNull
|
||||
@@ -338,6 +352,9 @@ public class WhisperServerConfiguration extends Configuration {
|
||||
@JsonProperty
|
||||
private Map<String, @Valid RetryConfiguration> retries = Collections.emptyMap();
|
||||
|
||||
@JsonProperty
|
||||
private Map<String, @Valid BulkheadConfiguration> bulkheads = Collections.emptyMap();
|
||||
|
||||
@Valid
|
||||
@NotNull
|
||||
@JsonProperty
|
||||
@@ -373,6 +390,16 @@ public class WhisperServerConfiguration extends Configuration {
|
||||
@JsonProperty
|
||||
private FoundationDbMessagesConfiguration foundationDbMessages;
|
||||
|
||||
@Valid
|
||||
@NotNull
|
||||
@JsonProperty
|
||||
private TotpConfiguration registrationTotp = TotpConfiguration.DEFAULT;
|
||||
|
||||
@Valid
|
||||
@NotNull
|
||||
@JsonProperty
|
||||
private WebAuthnConfiguration registrationWebAuthn;
|
||||
|
||||
public TlsKeyStoreConfiguration getTlsKeyStoreConfiguration() {
|
||||
return tlsKeyStore;
|
||||
}
|
||||
@@ -502,6 +529,11 @@ public class WhisperServerConfiguration extends Configuration {
|
||||
return chatZkConfig;
|
||||
}
|
||||
|
||||
/// ZK secret shared with Calling Service
|
||||
public GenericZkConfig getCallingZkConfigPreV101() {
|
||||
return callingZkConfigPreV101;
|
||||
}
|
||||
|
||||
/// ZK secret shared with Calling Service
|
||||
public GenericZkConfig getCallingZkConfig() {
|
||||
return callingZkConfig;
|
||||
@@ -532,6 +564,10 @@ public class WhisperServerConfiguration extends Configuration {
|
||||
return oneTimeDonations;
|
||||
}
|
||||
|
||||
public LoginPurchaseConfiguration getLoginPurchase() {
|
||||
return loginPurchase;
|
||||
}
|
||||
|
||||
public PagedSingleUseKEMPreKeyStoreConfiguration getPagedSingleUseKEMPreKeyStore() {
|
||||
return pagedSingleUseKEMPreKeyStore;
|
||||
}
|
||||
@@ -596,6 +632,10 @@ public class WhisperServerConfiguration extends Configuration {
|
||||
return retries;
|
||||
}
|
||||
|
||||
public Map<String, BulkheadConfiguration> getBulkheadConfigurations() {
|
||||
return bulkheads;
|
||||
}
|
||||
|
||||
public RetryConfiguration getGeneralRedisRetryConfiguration() {
|
||||
return generalRedisRetry;
|
||||
}
|
||||
@@ -623,4 +663,12 @@ public class WhisperServerConfiguration extends Configuration {
|
||||
public FoundationDbMessagesConfiguration getFoundationDbMessagesConfiguration() {
|
||||
return foundationDbMessages;
|
||||
}
|
||||
|
||||
public TotpConfiguration getRegistrationTotpConfiguration() {
|
||||
return registrationTotp;
|
||||
}
|
||||
|
||||
public WebAuthnConfiguration getRegistrationWebAuthnConfiguration() {
|
||||
return registrationWebAuthn;
|
||||
}
|
||||
}
|
||||
@@ -97,6 +97,7 @@ import org.whispersystems.textsecuregcm.auth.ExternalServiceCredentialsGenerator
|
||||
import org.whispersystems.textsecuregcm.auth.IdlePrimaryDeviceAuthenticatedWebSocketUpgradeFilter;
|
||||
import org.whispersystems.textsecuregcm.auth.PhoneVerificationTokenManager;
|
||||
import org.whispersystems.textsecuregcm.auth.RegistrationLockVerificationManager;
|
||||
import org.whispersystems.textsecuregcm.auth.webauthn.WebAuthnCeremonyManager;
|
||||
import org.whispersystems.textsecuregcm.auth.grpc.ProhibitAuthenticationInterceptor;
|
||||
import org.whispersystems.textsecuregcm.auth.grpc.RequireAuthenticationInterceptor;
|
||||
import org.whispersystems.textsecuregcm.backup.BackupAuthManager;
|
||||
@@ -111,6 +112,7 @@ import org.whispersystems.textsecuregcm.captcha.CaptchaClient;
|
||||
import org.whispersystems.textsecuregcm.captcha.RegistrationCaptchaManager;
|
||||
import org.whispersystems.textsecuregcm.captcha.ShortCodeExpander;
|
||||
import org.whispersystems.textsecuregcm.configuration.BadgeConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.FoundationDbExternalClientConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.secrets.SecretStore;
|
||||
import org.whispersystems.textsecuregcm.configuration.secrets.SecretsModule;
|
||||
@@ -130,6 +132,7 @@ import org.whispersystems.textsecuregcm.controllers.DonationController;
|
||||
import org.whispersystems.textsecuregcm.controllers.KeepAliveController;
|
||||
import org.whispersystems.textsecuregcm.controllers.KeyTransparencyController;
|
||||
import org.whispersystems.textsecuregcm.controllers.KeysController;
|
||||
import org.whispersystems.textsecuregcm.controllers.LoginPurchaseController;
|
||||
import org.whispersystems.textsecuregcm.controllers.MessageController;
|
||||
import org.whispersystems.textsecuregcm.controllers.OneTimeDonationController;
|
||||
import org.whispersystems.textsecuregcm.controllers.PaymentsController;
|
||||
@@ -171,8 +174,10 @@ import org.whispersystems.textsecuregcm.grpc.ErrorMappingInterceptor;
|
||||
import org.whispersystems.textsecuregcm.grpc.ExternalServiceDefinitions;
|
||||
import org.whispersystems.textsecuregcm.grpc.GroupSendTokenUtil;
|
||||
import org.whispersystems.textsecuregcm.grpc.GrpcAllowListInterceptor;
|
||||
import org.whispersystems.textsecuregcm.grpc.KeyTransparencyGrpcService;
|
||||
import org.whispersystems.textsecuregcm.grpc.KeysAnonymousGrpcService;
|
||||
import org.whispersystems.textsecuregcm.grpc.KeysGrpcService;
|
||||
import org.whispersystems.textsecuregcm.grpc.LoginPurchaseGrpcService;
|
||||
import org.whispersystems.textsecuregcm.grpc.MessageDispatcher;
|
||||
import org.whispersystems.textsecuregcm.grpc.MessagesAnonymousGrpcService;
|
||||
import org.whispersystems.textsecuregcm.grpc.MessagesGrpcService;
|
||||
@@ -204,12 +209,12 @@ import org.whispersystems.textsecuregcm.limits.RedisMessageDeliveryLoopMonitor;
|
||||
import org.whispersystems.textsecuregcm.mappers.BackupExceptionMapper;
|
||||
import org.whispersystems.textsecuregcm.mappers.CompletionExceptionMapper;
|
||||
import org.whispersystems.textsecuregcm.mappers.DeviceLimitExceededExceptionMapper;
|
||||
import org.whispersystems.textsecuregcm.mappers.GrpcStatusRuntimeExceptionMapper;
|
||||
import org.whispersystems.textsecuregcm.mappers.IOExceptionMapper;
|
||||
import org.whispersystems.textsecuregcm.mappers.IllegalStateExceptionMapper;
|
||||
import org.whispersystems.textsecuregcm.mappers.ImpossiblePhoneNumberExceptionMapper;
|
||||
import org.whispersystems.textsecuregcm.mappers.InvalidWebsocketAddressExceptionMapper;
|
||||
import org.whispersystems.textsecuregcm.mappers.JsonMappingExceptionMapper;
|
||||
import org.whispersystems.textsecuregcm.mappers.MfaFailureExceptionMapper;
|
||||
import org.whispersystems.textsecuregcm.mappers.NonNormalizedPhoneNumberExceptionMapper;
|
||||
import org.whispersystems.textsecuregcm.mappers.ObsoletePhoneNumberFormatExceptionMapper;
|
||||
import org.whispersystems.textsecuregcm.mappers.RateLimitExceededExceptionMapper;
|
||||
@@ -270,14 +275,14 @@ import org.whispersystems.textsecuregcm.storage.OneTimeDonationsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.PagedSingleUseKEMPreKeyStore;
|
||||
import org.whispersystems.textsecuregcm.storage.PersistentTimer;
|
||||
import org.whispersystems.textsecuregcm.storage.PhoneNumberIdentifiers;
|
||||
import org.whispersystems.textsecuregcm.storage.PhoneNumberRecoveryPasswords;
|
||||
import org.whispersystems.textsecuregcm.storage.PhoneNumberRecoveryPasswordsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.ProfileAvatars;
|
||||
import org.whispersystems.textsecuregcm.storage.Profiles;
|
||||
import org.whispersystems.textsecuregcm.storage.ProfilesManager;
|
||||
import org.whispersystems.textsecuregcm.storage.ProfilesV2;
|
||||
import org.whispersystems.textsecuregcm.storage.PushChallengeDynamoDb;
|
||||
import org.whispersystems.textsecuregcm.storage.RedeemedReceiptsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.RegistrationRecoveryPasswords;
|
||||
import org.whispersystems.textsecuregcm.storage.RegistrationRecoveryPasswordsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.RemoteConfigs;
|
||||
import org.whispersystems.textsecuregcm.storage.RemoteConfigsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.RepeatedUseECSignedPreKeyStore;
|
||||
@@ -292,14 +297,18 @@ import org.whispersystems.textsecuregcm.storage.VerificationSessions;
|
||||
import org.whispersystems.textsecuregcm.storage.devicecheck.AppleDeviceCheckManager;
|
||||
import org.whispersystems.textsecuregcm.storage.devicecheck.AppleDeviceCheckTrustAnchor;
|
||||
import org.whispersystems.textsecuregcm.storage.devicecheck.AppleDeviceChecks;
|
||||
import org.whispersystems.textsecuregcm.storage.foundationdb.FaultTolerantDatabase;
|
||||
import org.whispersystems.textsecuregcm.storage.foundationdb.FoundationDbMessageStore;
|
||||
import org.whispersystems.textsecuregcm.storage.foundationdb.FoundationDBWarmup;
|
||||
import org.whispersystems.textsecuregcm.storage.foundationdb.VersionstampUUIDCipher;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.AppleAppStoreClient;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.AppleAppStoreManager;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.BankMandateTranslator;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.BraintreeManager;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.GooglePlayBillingManager;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.LoginPurchaseManager;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.PayPalDonationsTranslator;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.PaymentProvider;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.StripeManager;
|
||||
import org.whispersystems.textsecuregcm.telephony.CarrierDataProvider;
|
||||
import org.whispersystems.textsecuregcm.telephony.hlrlookup.HlrLookupCarrierDataProvider;
|
||||
@@ -323,6 +332,7 @@ import org.whispersystems.textsecuregcm.workers.CertificateCommand;
|
||||
import org.whispersystems.textsecuregcm.workers.CheckDynamicConfigurationCommand;
|
||||
import org.whispersystems.textsecuregcm.workers.ClearExpiredFoundationDbMessagesCommand;
|
||||
import org.whispersystems.textsecuregcm.workers.ClearIssuedReceiptRedemptionsCommand;
|
||||
import org.whispersystems.textsecuregcm.workers.ClearOrphanedFoundationDbQueuesCommand;
|
||||
import org.whispersystems.textsecuregcm.workers.CopyToS3Command;
|
||||
import org.whispersystems.textsecuregcm.workers.DeleteUserCommand;
|
||||
import org.whispersystems.textsecuregcm.workers.IdleDeviceNotificationSchedulerFactory;
|
||||
@@ -400,6 +410,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
bootstrap.addCommand(new CopyToS3Command());
|
||||
bootstrap.addCommand(new ClearExpiredFoundationDbMessagesCommand(Clock.systemUTC()));
|
||||
bootstrap.addCommand(new TrimOversizedFoundationDbMessageQueuesCommand());
|
||||
bootstrap.addCommand(new ClearOrphanedFoundationDbQueuesCommand());
|
||||
|
||||
bootstrap.addCommand(new ProcessScheduledJobsServiceCommand("process-idle-device-notification-jobs",
|
||||
"Processes scheduled jobs to send notifications to idle devices",
|
||||
@@ -433,6 +444,9 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
config.getRetryConfigurations().forEach((name, configuration) ->
|
||||
ResilienceUtil.getRetryRegistry().addConfiguration(name, configuration.toRetryConfigBuilder().build()));
|
||||
|
||||
config.getBulkheadConfigurations().forEach((name, configuration) ->
|
||||
ResilienceUtil.getBulkheadRegistry().addConfiguration(name, configuration.toBulkheadConfig().build()));
|
||||
|
||||
ResilienceUtil.setGeneralRedisRetryConfiguration(config.getGeneralRedisRetryConfiguration());
|
||||
|
||||
ScheduledExecutorService dynamicConfigurationExecutor = ScheduledExecutorServiceBuilder.of(environment, "dynamicConfiguration")
|
||||
@@ -492,9 +506,20 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
// we'd like, but is the least bad option given current constraints.
|
||||
fdb.disableShutdownHook();
|
||||
|
||||
final Map<Integer, List<Database>> messageDatabasesByEpoch;
|
||||
final FoundationDbExternalClientConfiguration externalClientConfiguration = config.getFoundationDbMessagesConfiguration()
|
||||
.externalClientConfiguration();
|
||||
if (externalClientConfiguration != null) {
|
||||
// If threadsPerClient is not specified, we default to the cluster size so that there is 1:1 correspondence between
|
||||
// Database objects and threads.
|
||||
final int clientThreadsPerVersion = externalClientConfiguration.threadsPerClient()
|
||||
.orElseGet(() -> config.getFoundationDbMessagesConfiguration().clusters().size());
|
||||
externalClientConfiguration.clientLibraryPaths().forEach(path -> fdb.options().setExternalClientLibrary(path));
|
||||
fdb.options().setClientThreadsPerVersion(clientThreadsPerVersion);
|
||||
}
|
||||
|
||||
final Map<Integer, List<FaultTolerantDatabase>> messageDatabasesByEpoch;
|
||||
{
|
||||
final Map<String, Database> databasesByName =
|
||||
final Map<String, FaultTolerantDatabase> faultTolerantDatabasesByName =
|
||||
config.getFoundationDbMessagesConfiguration().clusters().entrySet().stream()
|
||||
.collect(Collectors.toUnmodifiableMap(Map.Entry::getKey,
|
||||
entry -> {
|
||||
@@ -506,7 +531,9 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
database.options().setTransactionRetryLimit(
|
||||
config.getFoundationDbMessagesConfiguration().transactionRetryLimit());
|
||||
|
||||
return database;
|
||||
return new FaultTolerantDatabase(database, entry.getKey(),
|
||||
config.getFoundationDbMessagesConfiguration().circuitBreakerConfigurationName(),
|
||||
config.getFoundationDbMessagesConfiguration().bulkheadConfigurationName());
|
||||
} catch (final IOException e) {
|
||||
throw new UncheckedIOException(e);
|
||||
}
|
||||
@@ -515,8 +542,10 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
messageDatabasesByEpoch = config.getFoundationDbMessagesConfiguration().epochs().entrySet().stream()
|
||||
.collect(Collectors.toUnmodifiableMap(Map.Entry::getKey,
|
||||
entry -> entry.getValue().stream()
|
||||
.map(databasesByName::get)
|
||||
.map(faultTolerantDatabasesByName::get)
|
||||
.toList()));
|
||||
|
||||
environment.lifecycle().manage(new FoundationDBWarmup(faultTolerantDatabasesByName));
|
||||
}
|
||||
|
||||
final AwsCredentialsProvider cdnCredentialsProvider = config.getCdnConfiguration().credentials().build();
|
||||
@@ -535,10 +564,15 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
.allowCoreThreadTimeOut(true)
|
||||
.workQueue(messageDeletionQueue).build();
|
||||
|
||||
RedeemedReceiptsManager redeemedReceiptsManager = new RedeemedReceiptsManager(clock,
|
||||
config.getDynamoDbTables().getRedeemedReceipts().getTableName(),
|
||||
dynamoDbClient);
|
||||
|
||||
Accounts accounts = new Accounts(
|
||||
clock,
|
||||
dynamoDbClient,
|
||||
dynamoDbAsyncClient,
|
||||
redeemedReceiptsManager,
|
||||
config.getDynamoDbTables().getAccounts().getTableName(),
|
||||
config.getDynamoDbTables().getAccounts().getPhoneNumberTableName(),
|
||||
config.getDynamoDbTables().getAccounts().getPhoneNumberIdentifierTableName(),
|
||||
@@ -580,7 +614,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
ReportMessageDynamoDb reportMessageDynamoDb = new ReportMessageDynamoDb(dynamoDbClient, dynamoDbAsyncClient,
|
||||
config.getDynamoDbTables().getReportMessage().getTableName(),
|
||||
config.getReportMessageConfiguration().getReportTtl());
|
||||
RegistrationRecoveryPasswords registrationRecoveryPasswords = new RegistrationRecoveryPasswords(
|
||||
PhoneNumberRecoveryPasswords phoneNumberRecoveryPasswords = new PhoneNumberRecoveryPasswords(
|
||||
config.getDynamoDbTables().getRegistrationRecovery().getTableName(),
|
||||
config.getDynamoDbTables().getRegistrationRecovery().getExpiration(),
|
||||
dynamoDbClient,
|
||||
@@ -654,10 +688,6 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
.workQueue(receiptSenderQueue)
|
||||
.rejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy())
|
||||
.build();
|
||||
ExecutorService accountLockExecutor = ExecutorServiceBuilder.of(environment, "accountLock")
|
||||
.minThreads(8)
|
||||
.maxThreads(8)
|
||||
.build();
|
||||
// unbounded executor (same as cachedThreadPool)
|
||||
ExecutorService remoteStorageHttpExecutor = ExecutorServiceBuilder.of(environment, "remoteStorage")
|
||||
.minThreads(0)
|
||||
@@ -722,8 +752,8 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
AsnInfoProvider.EMPTY,
|
||||
"AsnManager");
|
||||
|
||||
RegistrationRecoveryPasswordsManager registrationRecoveryPasswordsManager =
|
||||
new RegistrationRecoveryPasswordsManager(registrationRecoveryPasswords);
|
||||
PhoneNumberRecoveryPasswordsManager phoneNumberRecoveryPasswordsManager =
|
||||
new PhoneNumberRecoveryPasswordsManager(phoneNumberRecoveryPasswords);
|
||||
UsernameHashZkProofVerifier usernameHashZkProofVerifier = new UsernameHashZkProofVerifier();
|
||||
|
||||
final CarrierDataProvider carrierDataProvider =
|
||||
@@ -787,11 +817,19 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
changeNumberWaitingPeriods, config.getChangeNumber().postRegistrationWaitingPeriod(), clock);
|
||||
AccountLockManager accountLockManager = new AccountLockManager(dynamoDbClient,
|
||||
config.getDynamoDbTables().getDeletedAccountsLock().getTableName());
|
||||
AccountsManager accountsManager = new AccountsManager(accounts, phoneNumberIdentifiers, cacheCluster,
|
||||
final WebAuthnCeremonyManager webAuthnCeremonyManager = new WebAuthnCeremonyManager(
|
||||
config.getRegistrationWebAuthnConfiguration().relyingPartyId(),
|
||||
config.getRegistrationWebAuthnConfiguration().origin(),
|
||||
config.getRegistrationWebAuthnConfiguration().challengeTtl(),
|
||||
config.getRegistrationWebAuthnConfiguration().userHandleBlindingSecret().value(),
|
||||
rateLimitersCluster);
|
||||
final AccountsManager accountsManager = new AccountsManager(accounts, phoneNumberIdentifiers, cacheCluster,
|
||||
pubsubClient, accountLockManager, keysManager, messagesManager, profilesManager,
|
||||
changeNumberWaitingPeriodManager, secureStorageClient, secureValueRecovery2Client, disconnectionRequestManager,
|
||||
registrationRecoveryPasswordsManager, accountLockExecutor, messagePollExecutor,
|
||||
retryExecutor, clock, config.getLinkDeviceSecretConfiguration().secret().value());
|
||||
phoneNumberRecoveryPasswordsManager, messagePollExecutor,
|
||||
retryExecutor, clock, config.getLinkDeviceSecretConfiguration().secret().value(),
|
||||
config.getRegistrationTotpConfiguration().maxValidationDelay(),
|
||||
webAuthnCeremonyManager);
|
||||
RemoteConfigsManager remoteConfigsManager = new RemoteConfigsManager(remoteConfigs, config.getRemoteConfigConfiguration().globalConfig());
|
||||
APNSender apnSender = new APNSender(apnSenderExecutor, Clock.systemUTC(), config.getApnConfiguration());
|
||||
FcmSender fcmSender = new FcmSender(fcmSenderExecutor, config.getFcmConfiguration().credentials().value());
|
||||
@@ -803,18 +841,13 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
ProvisioningManager provisioningManager = new ProvisioningManager(pubsubClient);
|
||||
IssuedReceiptsManager issuedReceiptsManager = new IssuedReceiptsManager(
|
||||
config.getDynamoDbTables().getIssuedReceipts().getTableName(),
|
||||
config.getDynamoDbTables().getIssuedReceipts().getExpiration(),
|
||||
dynamoDbClient,
|
||||
config.getDynamoDbTables().getIssuedReceipts().getGenerator(),
|
||||
config.getDynamoDbTables().getIssuedReceipts().getmaxIssuedReceiptsPerPaymentId());
|
||||
config.getDynamoDbTables().getIssuedReceipts().getMaxReceiptsPerSubscriptionPayment());
|
||||
OneTimeDonationsManager oneTimeDonationsManager = new OneTimeDonationsManager(
|
||||
config.getDynamoDbTables().getOnetimeDonations().getTableName(), config.getDynamoDbTables().getOnetimeDonations().getExpiration(), dynamoDbClient);
|
||||
DonationPermits donationPermits = new DonationPermits(
|
||||
config.getDynamoDbTables().getDonationPermits().getTableName(), config.getDynamoDbTables().getDonationPermits().getExpiration(), dynamoDbClient);
|
||||
RedeemedReceiptsManager redeemedReceiptsManager = new RedeemedReceiptsManager(clock,
|
||||
config.getDynamoDbTables().getRedeemedReceipts().getTableName(),
|
||||
dynamoDbClient,
|
||||
config.getDynamoDbTables().getRedeemedReceipts().getExpiration());
|
||||
Subscriptions subscriptions = new Subscriptions(
|
||||
config.getDynamoDbTables().getSubscriptions().getTableName(), dynamoDbClient);
|
||||
MessageDeliveryLoopMonitor messageDeliveryLoopMonitor =
|
||||
@@ -825,7 +858,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
callQualitySurveyPubSubExecutor);
|
||||
|
||||
final RegistrationLockVerificationManager registrationLockVerificationManager = new RegistrationLockVerificationManager(
|
||||
accountsManager, disconnectionRequestManager, svr2CredentialsGenerator, registrationRecoveryPasswordsManager,
|
||||
accountsManager, disconnectionRequestManager, svr2CredentialsGenerator, phoneNumberRecoveryPasswordsManager,
|
||||
pushNotificationManager, rateLimiters);
|
||||
|
||||
final ReportedMessageMetricsListener reportedMessageMetricsListener = new ReportedMessageMetricsListener(
|
||||
@@ -930,6 +963,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
config.getCdnConfiguration().credentials().secretAccessKey().value());
|
||||
|
||||
ServerSecretParams groupZkSecretParams = new ServerSecretParams(config.getGroupsZkConfig().serverSecret().value());
|
||||
GenericServerSecretParams callingPreV101GenericZkSecretParams = new GenericServerSecretParams(config.getCallingZkConfigPreV101().serverSecret().value());
|
||||
GenericServerSecretParams callingGenericZkSecretParams = new GenericServerSecretParams(config.getCallingZkConfig().serverSecret().value());
|
||||
GenericServerSecretParams chatGenericZkSecretParams = new GenericServerSecretParams(config.getChatZkConfig().serverSecret().value());
|
||||
ServerZkProfileOperations zkProfileOperations = new ServerZkProfileOperations(groupZkSecretParams);
|
||||
@@ -983,6 +1017,13 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
List.of(stripeManager, braintreeManager, googlePlayBillingManager, appleAppStoreManager),
|
||||
zkReceiptOperations, issuedReceiptsManager);
|
||||
|
||||
final LoginPurchaseManager loginPurchaseManager = new LoginPurchaseManager(
|
||||
Map.of(
|
||||
PaymentProvider.APPLE_APP_STORE, appleAppStoreManager,
|
||||
PaymentProvider.GOOGLE_PLAY_BILLING, googlePlayBillingManager),
|
||||
issuedReceiptsManager,
|
||||
zkReceiptOperations);
|
||||
|
||||
final List<SpamFilter> spamFilters = ServiceLoader.load(SpamFilter.class)
|
||||
.stream()
|
||||
.map(ServiceLoader.Provider::get)
|
||||
@@ -1040,7 +1081,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
final HttpClient shortCodeRetrieverHttpClient = HttpClient.newBuilder().version(HttpClient.Version.HTTP_2)
|
||||
.connectTimeout(Duration.ofSeconds(10)).build();
|
||||
final ShortCodeExpander shortCodeRetriever = new ShortCodeExpander(shortCodeRetrieverHttpClient, config.getShortCodeRetrieverConfiguration().baseUrl());
|
||||
final CaptchaChecker captchaChecker = new CaptchaChecker(shortCodeRetriever, captchaClientSupplier);
|
||||
final CaptchaChecker captchaChecker = new CaptchaChecker(shortCodeRetriever, captchaClientSupplier, dynamicConfigurationManager);
|
||||
|
||||
final RegistrationCaptchaManager registrationCaptchaManager = new RegistrationCaptchaManager(captchaChecker);
|
||||
|
||||
@@ -1082,19 +1123,20 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
config.getDeliveryCertificate().embedSigner());
|
||||
|
||||
final PhoneVerificationTokenManager phoneVerificationTokenManager = new PhoneVerificationTokenManager(
|
||||
phoneNumberIdentifiers, registrationServiceClient, registrationRecoveryPasswordsManager, registrationRecoveryChecker);
|
||||
phoneNumberIdentifiers, registrationServiceClient, phoneNumberRecoveryPasswordsManager, registrationRecoveryChecker);
|
||||
|
||||
final ChangeNumberManager changeNumberManager = new ChangeNumberManager(messageSender, accountsManager,
|
||||
phoneVerificationTokenManager, registrationLockVerificationManager, rateLimiters,
|
||||
changeNumberWaitingPeriodManager, Clock.systemUTC());
|
||||
|
||||
final List<ServerServiceDefinition> authenticatedServices = Stream.of(
|
||||
new AccountsGrpcService(accountsManager, rateLimiters, usernameHashZkProofVerifier, registrationRecoveryPasswordsManager, Clock.systemUTC(), changeNumberManager),
|
||||
new AccountsGrpcService(accountsManager, rateLimiters, usernameHashZkProofVerifier,
|
||||
phoneNumberRecoveryPasswordsManager, Clock.systemUTC(), changeNumberManager),
|
||||
new CallingGrpcService(cloudflareTurnCredentialsManager, rateLimiters),
|
||||
new CredentialsGrpcService(accountsManager, certificateGenerator, zkAuthOperations, callingGenericZkSecretParams, rateLimiters, Clock.systemUTC(), ExternalServiceDefinitions.createExternalServiceList(config, Clock.systemUTC())),
|
||||
new KeysGrpcService(accountsManager, keysManager, rateLimiters),
|
||||
new ProfileGrpcService(clock, accountsManager, profilesManager, dynamicConfigurationManager, config.getBadges(), profileCdnPolicyGenerator, chatGenericZkSecretParams, profileBadgeConverter, rateLimiters),
|
||||
new MessagesGrpcService(accountsManager, rateLimiters, messageSender, messageByteLimitCardinalityEstimator, spamChecker, messageDispatcher, Clock.systemUTC()),
|
||||
new ProfileGrpcService(clock, accountsManager, profilesManager, asnInfoProviderSupplier, dynamicConfigurationManager, config.getBadges(), profileCdnPolicyGenerator, chatGenericZkSecretParams, profileBadgeConverter, rateLimiters),
|
||||
new MessagesGrpcService(accountsManager, reportMessageManager, phoneNumberIdentifiers, rateLimiters, messageSender, messageByteLimitCardinalityEstimator, spamChecker, messageDispatcher, Clock.systemUTC()),
|
||||
new BackupsGrpcService(accountsManager, backupAuthManager, backupMetrics),
|
||||
new DevicesGrpcService(accountsManager),
|
||||
new AttachmentsGrpcService(experimentEnrollmentManager, rateLimiters, gcsAttachmentGenerator,
|
||||
@@ -1104,7 +1146,8 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
new ChallengeGrpcService(accountsManager, rateLimitChallengeManager, challengeConstraintChecker),
|
||||
new DonationsGrpcService(clock, zkReceiptOperations, redeemedReceiptsManager, accountsManager, config.getBadges(), ReceiptCredentialPresentation::new, donationPermitsManager, rateLimiters),
|
||||
new ProductConfigurationGrpcService(config.getSubscription(), config.getOneTimeDonations(),
|
||||
List.of(stripeManager, braintreeManager), config.getBackupConfiguration().maxTotalMediaSize()),
|
||||
config.getLoginPurchase(), List.of(stripeManager, braintreeManager),
|
||||
config.getBackupConfiguration().maxTotalMediaSize()),
|
||||
new RemoteConfigurationGrpcService(remoteConfigsManager, profileBadgeConverter,
|
||||
config.getBadges().getBadges().stream()
|
||||
.map(BadgeConfiguration::getId)
|
||||
@@ -1125,6 +1168,8 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
new AccountsAnonymousGrpcService(accountsManager, rateLimiters, groupSendTokenUtil),
|
||||
new CallQualitySurveyGrpcService(callQualitySurveyManager, rateLimiters),
|
||||
new KeysAnonymousGrpcService(accountsManager, keysManager, groupZkSecretParams, Clock.systemUTC()),
|
||||
new KeyTransparencyGrpcService(rateLimiters, keyTransparencyServiceClient),
|
||||
new LoginPurchaseGrpcService(loginPurchaseManager, dynamicConfigurationManager),
|
||||
new ProfileAnonymousGrpcService(accountsManager, profilesManager, profileBadgeConverter, profileCdnPolicyGenerator, chatGenericZkSecretParams, groupZkSecretParams, rateLimiters, clock),
|
||||
new MessagesAnonymousGrpcService(accountsManager, rateLimiters, messageSender, groupSendTokenUtil, messageByteLimitCardinalityEstimator, spamChecker, Clock.systemUTC()),
|
||||
new BackupsAnonymousGrpcService(backupManager, backupMetrics, config.getAttachments().maxAttachmentUploadSizeInBytes(), config.getAttachments().maxMessageBackupUploadSizeInBytes()),
|
||||
@@ -1160,11 +1205,14 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
unauthenticatedServices.forEach(serverBuilder::addService);
|
||||
final ManagedGrpcServer localGrpcServer = new ManagedGrpcServer(serverBuilder.build());
|
||||
|
||||
final String websocketServletPath = "/v1/websocket/";
|
||||
final String provisioningWebsocketServletPath = "/v1/websocket/provisioning/";
|
||||
|
||||
final SocketAddress websocketAddress =
|
||||
new InetSocketAddress(config.getGrpc().websocketAddress(), config.getGrpc().websocketPort());
|
||||
final OmnibusRouter omnibusRouter = new OmnibusRouter(List.of(
|
||||
new OmnibusRouter.OmnibusRoute("/v1/websocket", websocketAddress),
|
||||
new OmnibusRouter.OmnibusRoute("/v1/provisioning", websocketAddress)),
|
||||
final OmnibusRouter omnibusRouter = new OmnibusRouter(Map.of(
|
||||
websocketServletPath, websocketAddress,
|
||||
provisioningWebsocketServletPath, websocketAddress),
|
||||
grpcLocalAddress);
|
||||
@Nullable final Mapping<String, SslContext> sniMapping = config.getGrpc().h2c()
|
||||
? null
|
||||
@@ -1195,9 +1243,6 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
.setAuthenticator(accountAuthenticator)
|
||||
.buildAuthFilter();
|
||||
|
||||
final String websocketServletPath = "/v1/websocket/";
|
||||
final String provisioningWebsocketServletPath = "/v1/websocket/provisioning/";
|
||||
|
||||
MetricsHttpEventHandler.configure(environment, Metrics.globalRegistry, clientReleaseManager, Set.of(websocketServletPath, provisioningWebsocketServletPath, "/health-check"));
|
||||
|
||||
// BufferingInterceptor is needed on the base environment but not the WebSocketEnvironment,
|
||||
@@ -1240,20 +1285,19 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
final PersistentTimer persistentTimer = new PersistentTimer(rateLimitersCluster, clock);
|
||||
|
||||
final List<Object> commonControllers = Lists.newArrayList(
|
||||
new AccountController(accountsManager, rateLimiters, registrationRecoveryPasswordsManager,
|
||||
new AccountController(accountsManager, rateLimiters, phoneNumberRecoveryPasswordsManager,
|
||||
usernameHashZkProofVerifier),
|
||||
new AccountControllerV2(accountsManager, changeNumberManager),
|
||||
new AttachmentControllerV4(rateLimiters, gcsAttachmentGenerator, tusAttachmentGenerator,
|
||||
experimentEnrollmentManager, config.getAttachments().maxAttachmentUploadSizeInBytes()),
|
||||
new ArchiveController(accountsManager, backupAuthManager, backupManager, backupMetrics, config.getAttachments().maxAttachmentUploadSizeInBytes(), config.getAttachments().maxMessageBackupUploadSizeInBytes()),
|
||||
new CallRoutingControllerV2(rateLimiters, cloudflareTurnCredentialsManager),
|
||||
new CallLinkController(rateLimiters, callingGenericZkSecretParams),
|
||||
new CallLinkController(rateLimiters, callingGenericZkSecretParams, callingPreV101GenericZkSecretParams),
|
||||
new CallQualitySurveyController(callQualitySurveyManager),
|
||||
new CertificateController(accountsManager, certificateGenerator, zkAuthOperations, callingGenericZkSecretParams, clock),
|
||||
new CertificateController(accountsManager, certificateGenerator, zkAuthOperations, callingGenericZkSecretParams, callingPreV101GenericZkSecretParams, clock),
|
||||
new ChallengeController(accountsManager, rateLimitChallengeManager, challengeConstraintChecker),
|
||||
new DeviceController(accountsManager, rateLimiters, persistentTimer),
|
||||
new DeviceCheckController(clock, accountsManager, backupAuthManager, appleDeviceCheckManager, rateLimiters,
|
||||
config.getDeviceCheck().backupRedemptionLevel(),
|
||||
config.getDeviceCheck().backupRedemptionDuration()),
|
||||
new DirectoryV2Controller(directoryV2CredentialsGenerator),
|
||||
new DonationController(clock, zkReceiptOperations, redeemedReceiptsManager, accountsManager, config.getBadges(),
|
||||
@@ -1263,27 +1307,29 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
new MessageController(rateLimiters, messageByteLimitCardinalityEstimator, messageSender, accountsManager,
|
||||
phoneNumberIdentifiers, reportMessageManager, groupZkSecretParams, spamChecker, Clock.systemUTC()),
|
||||
new PaymentsController(currencyManager, paymentsCredentialsGenerator),
|
||||
new ProfileController(clock, rateLimiters, accountsManager, profilesManager, dynamicConfigurationManager,
|
||||
profileBadgeConverter, config.getBadges(), profileCdnPolicyGenerator,
|
||||
new ProfileController(clock, rateLimiters, accountsManager, profilesManager, asnInfoProviderSupplier,
|
||||
dynamicConfigurationManager, profileBadgeConverter, config.getBadges(), profileCdnPolicyGenerator,
|
||||
groupZkSecretParams, zkProfileOperations, batchIdentityCheckExecutor),
|
||||
new ProvisioningController(rateLimiters, provisioningManager),
|
||||
new RegistrationController(accountsManager, phoneVerificationTokenManager, registrationLockVerificationManager,
|
||||
rateLimiters, registrationFraudChecker),
|
||||
rateLimiters, registrationFraudChecker, ReceiptCredentialPresentation::new, zkReceiptOperations, clock, dynamicConfigurationManager),
|
||||
new RemoteConfigController(remoteConfigsManager),
|
||||
new SecureStorageController(storageCredentialsGenerator),
|
||||
new SecureValueRecovery2Controller(svr2CredentialsGenerator, accountsManager),
|
||||
new StickerController(rateLimiters, stickerPolicyGenerator, Clock.systemUTC()),
|
||||
new VerificationController(registrationServiceClient, new VerificationSessionManager(verificationSessions),
|
||||
pushNotificationManager, registrationCaptchaManager, registrationRecoveryPasswordsManager,
|
||||
pushNotificationManager, registrationCaptchaManager, phoneNumberRecoveryPasswordsManager,
|
||||
phoneNumberIdentifiers, rateLimiters, accountsManager, carrierDataProvider, registrationFraudChecker,
|
||||
dynamicConfigurationManager, experimentEnrollmentManager, clock),
|
||||
dynamicConfigurationManager, clock),
|
||||
new SubscriptionController(clock, config.getSubscription(), config.getOneTimeDonations(),
|
||||
subscriptionManager, stripeManager, braintreeManager, googlePlayBillingManager, appleAppStoreManager,
|
||||
config.getLoginPurchase(), subscriptionManager, stripeManager, braintreeManager, googlePlayBillingManager,
|
||||
appleAppStoreManager,
|
||||
profileBadgeConverter, bankMandateTranslator, donationPermitsManager,
|
||||
config.getBackupConfiguration().maxTotalMediaSize()),
|
||||
new OneTimeDonationController(clock, config.getOneTimeDonations(), stripeManager, braintreeManager,
|
||||
payPalDonationsTranslator, zkReceiptOperations, issuedReceiptsManager, oneTimeDonationsManager,
|
||||
donationPermitsManager)
|
||||
donationPermitsManager),
|
||||
new LoginPurchaseController(loginPurchaseManager, dynamicConfigurationManager)
|
||||
);
|
||||
|
||||
for (Object controller : commonControllers) {
|
||||
@@ -1343,7 +1389,6 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
List.of(
|
||||
new LoggingUnhandledExceptionMapper(),
|
||||
new CompletionExceptionMapper(),
|
||||
new GrpcStatusRuntimeExceptionMapper(),
|
||||
new IOExceptionMapper(),
|
||||
new RateLimitExceededExceptionMapper(),
|
||||
new InvalidWebsocketAddressExceptionMapper(),
|
||||
@@ -1357,7 +1402,8 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
new SubscriptionExceptionMapper(),
|
||||
new BackupExceptionMapper(),
|
||||
new JsonMappingExceptionMapper(),
|
||||
new RegistrationLockFailureExceptionMapper()
|
||||
new RegistrationLockFailureExceptionMapper(),
|
||||
new MfaFailureExceptionMapper()
|
||||
).forEach(exceptionMapper -> {
|
||||
environment.jersey().register(exceptionMapper);
|
||||
webSocketEnvironment.jersey().register(exceptionMapper);
|
||||
|
||||
+2
-3
@@ -19,7 +19,6 @@ import java.time.temporal.ChronoUnit;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.whispersystems.textsecuregcm.identity.IdentityType;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.Device;
|
||||
@@ -101,7 +100,7 @@ public class AccountAuthenticator implements Authenticator<BasicCredentials, Aut
|
||||
if (deviceSaltedTokenHash.verify(basicCredentials.getPassword())) {
|
||||
succeeded = true;
|
||||
final Account authenticatedAccount = updateLastSeen(account.get(), device.get());
|
||||
return Optional.of(new AuthenticatedDevice(authenticatedAccount.getIdentifier(IdentityType.ACI),
|
||||
return Optional.of(new AuthenticatedDevice(authenticatedAccount.getAccountIdentifier(),
|
||||
device.get().getId(),
|
||||
Instant.ofEpochMilli(authenticatedAccount.getPrimaryDevice().getLastSeen())));
|
||||
} else {
|
||||
@@ -142,7 +141,7 @@ public class AccountAuthenticator implements Authenticator<BasicCredentials, Aut
|
||||
Metrics.summary(DAYS_SINCE_LAST_SEEN_DISTRIBUTION_NAME, IS_PRIMARY_DEVICE_TAG, String.valueOf(device.isPrimary()))
|
||||
.record(Duration.ofMillis(todayInMillisWithOffset - device.getLastSeen()).toDays());
|
||||
|
||||
return accountsManager.updateDeviceLastSeen(account.getIdentifier(IdentityType.ACI), device, Util.todayInMillis(clock));
|
||||
return accountsManager.updateDeviceLastSeen(account.getAccountIdentifier(), device, Util.todayInMillis(clock));
|
||||
}
|
||||
|
||||
return account;
|
||||
|
||||
+6
-3
@@ -11,7 +11,6 @@ import java.util.concurrent.TimeUnit;
|
||||
import org.signal.libsignal.protocol.ecc.ECPrivateKey;
|
||||
import org.whispersystems.textsecuregcm.entities.MessageProtos.SenderCertificate;
|
||||
import org.whispersystems.textsecuregcm.entities.MessageProtos.ServerCertificate;
|
||||
import org.whispersystems.textsecuregcm.identity.IdentityType;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.util.UUIDUtil;
|
||||
|
||||
@@ -35,14 +34,18 @@ public class CertificateGenerator {
|
||||
}
|
||||
|
||||
public byte[] createFor(final Account account, final byte deviceId, boolean includeE164) {
|
||||
if (includeE164 && account.getNumber().isEmpty()) {
|
||||
throw new IllegalArgumentException();
|
||||
}
|
||||
|
||||
SenderCertificate.Certificate.Builder builder = SenderCertificate.Certificate.newBuilder()
|
||||
.setSenderDevice(Math.toIntExact(deviceId))
|
||||
.setExpires(System.currentTimeMillis() + TimeUnit.DAYS.toMillis(expiresDays))
|
||||
.setIdentityKey(ByteString.copyFrom(account.getIdentityKey(IdentityType.ACI).serialize()))
|
||||
.setIdentityKey(ByteString.copyFrom(account.getAccountIdentityKey().serialize()))
|
||||
.setSenderUuid(UUIDUtil.toByteString(account.getAccountIdentifier()));
|
||||
|
||||
if (includeE164) {
|
||||
builder.setSenderE164(account.getNumber());
|
||||
builder.setSenderE164(account.getNumber().get());
|
||||
}
|
||||
|
||||
if (embedSigner) {
|
||||
|
||||
+1
-1
@@ -164,7 +164,7 @@ public class DisconnectionRequestManager extends RedisPubSubAdapter<byte[], byte
|
||||
* @return a future that completes when the request has been broadcast
|
||||
*/
|
||||
public CompletionStage<Void> requestDisconnection(final Account account) {
|
||||
return requestDisconnection(account.getIdentifier(IdentityType.ACI),
|
||||
return requestDisconnection(account.getAccountIdentifier(),
|
||||
account.getDevices().stream().map(Device::getId).toList());
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
/*
|
||||
* Copyright 2026 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.auth;
|
||||
|
||||
import javax.annotation.Nullable;
|
||||
import org.whispersystems.textsecuregcm.auth.webauthn.AuthenticationCeremonyParameters;
|
||||
import org.whispersystems.textsecuregcm.util.NoStackTraceException;
|
||||
|
||||
public class MfaFailureException extends NoStackTraceException {
|
||||
|
||||
private final @Nullable AuthenticationCeremonyParameters webAuthnParameters;
|
||||
private final boolean hasTotp;
|
||||
|
||||
public MfaFailureException(@Nullable AuthenticationCeremonyParameters webAuthnParameters, boolean hasTotpKey) {
|
||||
this.webAuthnParameters = webAuthnParameters;
|
||||
this.hasTotp = hasTotpKey;
|
||||
}
|
||||
|
||||
public @Nullable AuthenticationCeremonyParameters getWebAuthnParameters() {
|
||||
return webAuthnParameters;
|
||||
}
|
||||
|
||||
public boolean hasTotpKey() {
|
||||
return hasTotp;
|
||||
}
|
||||
}
|
||||
+5
-5
@@ -22,7 +22,7 @@ import org.whispersystems.textsecuregcm.entities.RegistrationServiceSession;
|
||||
import org.whispersystems.textsecuregcm.registration.RegistrationServiceClient;
|
||||
import org.whispersystems.textsecuregcm.spam.RegistrationRecoveryChecker;
|
||||
import org.whispersystems.textsecuregcm.storage.PhoneNumberIdentifiers;
|
||||
import org.whispersystems.textsecuregcm.storage.RegistrationRecoveryPasswordsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.PhoneNumberRecoveryPasswordsManager;
|
||||
|
||||
public class PhoneVerificationTokenManager {
|
||||
|
||||
@@ -33,16 +33,16 @@ public class PhoneVerificationTokenManager {
|
||||
private final PhoneNumberIdentifiers phoneNumberIdentifiers;
|
||||
|
||||
private final RegistrationServiceClient registrationServiceClient;
|
||||
private final RegistrationRecoveryPasswordsManager registrationRecoveryPasswordsManager;
|
||||
private final PhoneNumberRecoveryPasswordsManager phoneNumberRecoveryPasswordsManager;
|
||||
private final RegistrationRecoveryChecker registrationRecoveryChecker;
|
||||
|
||||
public PhoneVerificationTokenManager(final PhoneNumberIdentifiers phoneNumberIdentifiers,
|
||||
final RegistrationServiceClient registrationServiceClient,
|
||||
final RegistrationRecoveryPasswordsManager registrationRecoveryPasswordsManager,
|
||||
final PhoneNumberRecoveryPasswordsManager phoneNumberRecoveryPasswordsManager,
|
||||
final RegistrationRecoveryChecker registrationRecoveryChecker) {
|
||||
this.phoneNumberIdentifiers = phoneNumberIdentifiers;
|
||||
this.registrationServiceClient = registrationServiceClient;
|
||||
this.registrationRecoveryPasswordsManager = registrationRecoveryPasswordsManager;
|
||||
this.phoneNumberRecoveryPasswordsManager = phoneNumberRecoveryPasswordsManager;
|
||||
this.registrationRecoveryChecker = registrationRecoveryChecker;
|
||||
}
|
||||
|
||||
@@ -127,7 +127,7 @@ public class PhoneVerificationTokenManager {
|
||||
final UUID phoneNumberIdentifier = phoneNumberIdentifiers.getPhoneNumberIdentifier(number)
|
||||
.get(VERIFICATION_TIMEOUT_SECONDS, TimeUnit.SECONDS);
|
||||
|
||||
final boolean verified = registrationRecoveryPasswordsManager.verify(phoneNumberIdentifier, recoveryPassword);
|
||||
final boolean verified = phoneNumberRecoveryPasswordsManager.verify(phoneNumberIdentifier, recoveryPassword);
|
||||
|
||||
if (!verified) {
|
||||
throw new RecoveryPasswordVerificationFailedException();
|
||||
|
||||
+24
-14
@@ -14,13 +14,13 @@ import io.micrometer.core.instrument.Tag;
|
||||
import io.micrometer.core.instrument.Tags;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import javax.annotation.Nullable;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
|
||||
import org.whispersystems.textsecuregcm.entities.PhoneVerificationRequest;
|
||||
import org.whispersystems.textsecuregcm.entities.RegistrationLockFailure;
|
||||
import org.whispersystems.textsecuregcm.identity.IdentityType;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimiters;
|
||||
import org.whispersystems.textsecuregcm.metrics.UserAgentTagUtil;
|
||||
import org.whispersystems.textsecuregcm.push.NotPushRegisteredException;
|
||||
@@ -28,7 +28,8 @@ import org.whispersystems.textsecuregcm.push.PushNotificationManager;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.Device;
|
||||
import org.whispersystems.textsecuregcm.storage.RegistrationRecoveryPasswordsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.PhoneNumberRecoveryPasswordsManager;
|
||||
import software.amazon.awssdk.services.dynamodb.model.TransactWriteItem;
|
||||
|
||||
public class RegistrationLockVerificationManager {
|
||||
public enum Flow {
|
||||
@@ -54,20 +55,20 @@ public class RegistrationLockVerificationManager {
|
||||
private final DisconnectionRequestManager disconnectionRequestManager;
|
||||
private final ExternalServiceCredentialsGenerator svr2CredentialGenerator;
|
||||
private final RateLimiters rateLimiters;
|
||||
private final RegistrationRecoveryPasswordsManager registrationRecoveryPasswordsManager;
|
||||
private final PhoneNumberRecoveryPasswordsManager phoneNumberRecoveryPasswordsManager;
|
||||
private final PushNotificationManager pushNotificationManager;
|
||||
|
||||
public RegistrationLockVerificationManager(
|
||||
final AccountsManager accounts,
|
||||
final DisconnectionRequestManager disconnectionRequestManager,
|
||||
final ExternalServiceCredentialsGenerator svr2CredentialGenerator,
|
||||
final RegistrationRecoveryPasswordsManager registrationRecoveryPasswordsManager,
|
||||
final PhoneNumberRecoveryPasswordsManager phoneNumberRecoveryPasswordsManager,
|
||||
final PushNotificationManager pushNotificationManager,
|
||||
final RateLimiters rateLimiters) {
|
||||
this.accounts = accounts;
|
||||
this.disconnectionRequestManager = disconnectionRequestManager;
|
||||
this.svr2CredentialGenerator = svr2CredentialGenerator;
|
||||
this.registrationRecoveryPasswordsManager = registrationRecoveryPasswordsManager;
|
||||
this.phoneNumberRecoveryPasswordsManager = phoneNumberRecoveryPasswordsManager;
|
||||
this.pushNotificationManager = pushNotificationManager;
|
||||
this.rateLimiters = rateLimiters;
|
||||
}
|
||||
@@ -86,6 +87,9 @@ public class RegistrationLockVerificationManager {
|
||||
final PhoneVerificationRequest.VerificationType phoneVerificationType
|
||||
) throws RateLimitExceededException, RegistrationLockFailureException {
|
||||
|
||||
final String phoneNumber = account.getNumber()
|
||||
.orElseThrow(() -> new IllegalArgumentException("account does not have a phone number"));
|
||||
|
||||
final Tags expiredTags = Tags.of(UserAgentTagUtil.getPlatformTag(userAgent),
|
||||
Tag.of(REGISTRATION_LOCK_VERIFICATION_FLOW_TAG_NAME, flow.name()),
|
||||
Tag.of(PHONE_VERIFICATION_TYPE_TAG_NAME, phoneVerificationType.name())
|
||||
@@ -106,10 +110,9 @@ public class RegistrationLockVerificationManager {
|
||||
}
|
||||
|
||||
if (StringUtils.isNotEmpty(clientRegistrationLock)) {
|
||||
rateLimiters.getPinLimiter().validate(account.getNumber());
|
||||
rateLimiters.getPinLimiter().validate(phoneNumber);
|
||||
}
|
||||
|
||||
final String phoneNumber = account.getNumber();
|
||||
final boolean registrationLockMatches = existingRegistrationLock.verify(clientRegistrationLock);
|
||||
final boolean alreadyLocked = account.hasLockedCredentials();
|
||||
|
||||
@@ -136,12 +139,8 @@ public class RegistrationLockVerificationManager {
|
||||
// Freezing the existing account credentials will definitively start the reglock timeout.
|
||||
// Until the timeout, the current reglock can still be supplied,
|
||||
// along with phone number verification, to restore access.
|
||||
final Account updatedAccount;
|
||||
if (!alreadyLocked) {
|
||||
updatedAccount = accounts.update(account, Account::lockAuthTokenHash);
|
||||
} else {
|
||||
updatedAccount = account;
|
||||
}
|
||||
|
||||
final List<TransactWriteItem> additionalWriteItems;
|
||||
|
||||
// The client often sends an empty registration lock token on the first request
|
||||
// and sends an actual token if the server returns a 423 indicating that one is required.
|
||||
@@ -150,9 +149,20 @@ public class RegistrationLockVerificationManager {
|
||||
// This allows users to re-register via registration recovery password
|
||||
// instead of always being forced to fall back to SMS verification.
|
||||
if (!phoneVerificationType.equals(PhoneVerificationRequest.VerificationType.RECOVERY_PASSWORD) || clientRegistrationLock != null) {
|
||||
registrationRecoveryPasswordsManager.remove(updatedAccount.getIdentifier(IdentityType.PNI));
|
||||
additionalWriteItems = List.of(phoneNumberRecoveryPasswordsManager.buildTransactWriteItemForRemovePassword(account.getPhoneNumberIdentifier()
|
||||
.orElseThrow(() -> new AssertionError("Account with a phone number did not have a phone number identifier"))));
|
||||
} else {
|
||||
additionalWriteItems = Collections.emptyList();
|
||||
}
|
||||
|
||||
final Account updatedAccount = accounts.update(account.getAccountIdentifier(), a -> {
|
||||
if (!a.hasLockedCredentials()) {
|
||||
a.lockAuthTokenHash();
|
||||
}
|
||||
|
||||
a.clearAccountRecoveryPassword();
|
||||
}, additionalWriteItems);
|
||||
|
||||
final List<Byte> deviceIds = updatedAccount.getDevices().stream().map(Device::getId).toList();
|
||||
disconnectionRequestManager.requestDisconnection(updatedAccount.getAccountIdentifier(), deviceIds);
|
||||
|
||||
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
/*
|
||||
* Copyright 2026 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.auth.webauthn;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.util.List;
|
||||
|
||||
/// Server-generated parameters for a freshly-initiated authentication ceremony.
|
||||
public record AuthenticationCeremonyParameters(
|
||||
byte[] challenge,
|
||||
Duration timeout,
|
||||
List<byte[]> allowedCredentialIds) {
|
||||
}
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
/*
|
||||
* Copyright 2026 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.auth.webauthn;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/// Server-generated parameters for a freshly-initiated registration ceremony.
|
||||
public record RegistrationCeremonyParameters(
|
||||
byte[] userHandle,
|
||||
List<Long> allowedAlgorithms,
|
||||
List<byte[]> excludedCredentialIds) {
|
||||
}
|
||||
+17
@@ -0,0 +1,17 @@
|
||||
/*
|
||||
* Copyright 2026 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.auth.webauthn;
|
||||
|
||||
import com.webauthn4j.data.attestation.authenticator.AttestedCredentialData;
|
||||
import com.webauthn4j.data.client.CollectedClientData;
|
||||
|
||||
/// Results of a registration ceremony for persisting.
|
||||
public record RegistrationCeremonyResult(
|
||||
AttestedCredentialData attestedCredentialData,
|
||||
CollectedClientData collectedClientData,
|
||||
long signCount
|
||||
) {
|
||||
}
|
||||
+27
@@ -0,0 +1,27 @@
|
||||
/*
|
||||
* Copyright 2026 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.auth.webauthn;
|
||||
|
||||
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
|
||||
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import org.whispersystems.textsecuregcm.util.ByteArrayAdapter;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public record WebAuthnAuthenticationParameters(
|
||||
@Schema(description = "The authentication ceremony challenge.")
|
||||
@JsonDeserialize(using = ByteArrayAdapter.Deserializing.class)
|
||||
@JsonSerialize(using = ByteArrayAdapter.Serializing.class)
|
||||
byte[] challenge,
|
||||
|
||||
@Schema(description = "The number of seconds the challenge will be valid.")
|
||||
long timeoutSeconds,
|
||||
|
||||
@Schema(description = "A list of authenticators previously registered to the account.")
|
||||
@JsonDeserialize(contentUsing = ByteArrayAdapter.Deserializing.class)
|
||||
@JsonSerialize(contentUsing = ByteArrayAdapter.Serializing.class)
|
||||
List<byte[]> allowedCredentialIds) {}
|
||||
+231
@@ -0,0 +1,231 @@
|
||||
/*
|
||||
* Copyright 2026 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
package org.whispersystems.textsecuregcm.auth.webauthn;
|
||||
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import com.webauthn4j.WebAuthnManager;
|
||||
import com.webauthn4j.credential.CredentialRecord;
|
||||
import com.webauthn4j.data.AuthenticationData;
|
||||
import com.webauthn4j.data.AuthenticationParameters;
|
||||
import com.webauthn4j.data.PublicKeyCredentialParameters;
|
||||
import com.webauthn4j.data.PublicKeyCredentialType;
|
||||
import com.webauthn4j.data.RegistrationData;
|
||||
import com.webauthn4j.data.RegistrationParameters;
|
||||
import com.webauthn4j.data.RegistrationRequest;
|
||||
import com.webauthn4j.data.attestation.statement.COSEAlgorithmIdentifier;
|
||||
import com.webauthn4j.data.client.Origin;
|
||||
import com.webauthn4j.server.ServerProperty;
|
||||
import com.webauthn4j.util.exception.WebAuthnException;
|
||||
import com.webauthn4j.verifier.exception.BadChallengeException;
|
||||
import com.webauthn4j.verifier.exception.VerificationException;
|
||||
import io.lettuce.core.SetArgs;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.SecureRandom;
|
||||
import java.time.Duration;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
import javax.annotation.Nullable;
|
||||
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisClusterClient;
|
||||
import org.whispersystems.textsecuregcm.util.HmacUtils;
|
||||
import org.whispersystems.textsecuregcm.util.ResilienceUtil;
|
||||
import org.whispersystems.textsecuregcm.util.UUIDUtil;
|
||||
import tools.jackson.core.JacksonException;
|
||||
|
||||
/// Handles WebAuthn registration and authentication operations.
|
||||
public class WebAuthnCeremonyManager {
|
||||
/// [relying party ID - WebAuthn TR](https://www.w3.org/TR/webauthn/#relying-party-identifier)
|
||||
private final String rpId;
|
||||
/// [origin - WebAuthn TR](https://www.w3.org/TR/webauthn/#dom-collectedclientdata-origin)
|
||||
private final Origin origin;
|
||||
private final byte[] blindingSecret;
|
||||
private final Duration challengeTtl;
|
||||
|
||||
private final FaultTolerantRedisClusterClient challengeStorageCluster;
|
||||
private final WebAuthnManager webAuthnManager;
|
||||
|
||||
private static final String RETRY_NAME = ResilienceUtil.name(WebAuthnCeremonyManager.class);
|
||||
|
||||
/// Ed25519 support is fairly limited, while ES256 is broadly supported
|
||||
private static final List<PublicKeyCredentialParameters> ALLOWED_WEBAUTHN_CREDENTIAL_ALGORITHMS = List.of(
|
||||
new PublicKeyCredentialParameters(PublicKeyCredentialType.PUBLIC_KEY, COSEAlgorithmIdentifier.Ed25519),
|
||||
new PublicKeyCredentialParameters(PublicKeyCredentialType.PUBLIC_KEY, COSEAlgorithmIdentifier.ES256)
|
||||
);
|
||||
|
||||
private static final SecureRandom SECURE_RANDOM = new SecureRandom();
|
||||
|
||||
public WebAuthnCeremonyManager(final String rpId, final String origin, final Duration challengeTtl, final byte[] blindingSecret,
|
||||
final FaultTolerantRedisClusterClient challengeStorageCluster) {
|
||||
this.rpId = rpId;
|
||||
this.origin = new Origin(origin);
|
||||
this.challengeTtl = challengeTtl;
|
||||
this.blindingSecret = blindingSecret;
|
||||
this.challengeStorageCluster = challengeStorageCluster;
|
||||
this.webAuthnManager = WebAuthnManager.createNonStrictWebAuthnManager();
|
||||
}
|
||||
|
||||
/// Initiates a WebAuthn registration ceremony
|
||||
///
|
||||
/// @param identifier The account identifier
|
||||
///
|
||||
/// @param existingCredentials a list of already-stored credential records for the user; their IDs
|
||||
/// will be provided to the client to help prevent registering a duplicate ID on the same
|
||||
/// authenticator
|
||||
///
|
||||
/// @return parameters the client must use for its step in the registration ceremony. `identifier` will be blinded, so
|
||||
/// that it is a [non-identifiable user handle](https://www.w3.org/TR/webauthn/#sctn-user-handle-privacy)
|
||||
public RegistrationCeremonyParameters startRegistration(final UUID identifier, final List<? extends CredentialRecord> existingCredentials) {
|
||||
return new RegistrationCeremonyParameters(
|
||||
blindIdentifier(identifier),
|
||||
ALLOWED_WEBAUTHN_CREDENTIAL_ALGORITHMS.stream().map(pkcp -> pkcp.getAlg().getValue()).toList(),
|
||||
existingCredentials.stream().map(credentialRecord -> credentialRecord.getAttestedCredentialData().getCredentialId()).toList()
|
||||
);
|
||||
}
|
||||
|
||||
/// Verifies that the supplied authenticator response components form a
|
||||
/// valid WebAuthn registration ceremony with acceptable parameters.
|
||||
///
|
||||
/// @param serializedAttestationObject the "attestation object" from the authenticator response,
|
||||
/// serialized in the format specified by the WebAuthn TR. Its attestation format must be `none`
|
||||
/// and any attestation statement must have been cleared to mitigate privacy risks.
|
||||
///
|
||||
/// @param collectedClientDataJson the "collected client data" from the authenticator response,
|
||||
/// serialized in the [format specified by the WebAuthn TR](https://www.w3.org/TR/webauthn/#sctn-generating-an-attestation-object)
|
||||
///
|
||||
/// @return a record that can be stored for future authentication.
|
||||
///
|
||||
/// @throws WebAuthnException if the supplied authenticator response is
|
||||
/// invalid for any reason (structurally or due to selecting unacceptable
|
||||
/// parameters, for example an unsupported signature algorithm)
|
||||
public RegistrationCeremonyResult verifyRegistration(
|
||||
final byte[] serializedAttestationObject, final String collectedClientDataJson) throws WebAuthnException {
|
||||
|
||||
final RegistrationData registrationData;
|
||||
try {
|
||||
registrationData = webAuthnManager.parse(
|
||||
new RegistrationRequest(serializedAttestationObject, collectedClientDataJson.getBytes(StandardCharsets.UTF_8)));
|
||||
} catch (final JacksonException e) {
|
||||
throw new WebAuthnException(e);
|
||||
}
|
||||
|
||||
// These shouldn't ever be null, because the upstream RPC inputs are not nullable. However, the fields are annotated as
|
||||
// nullable.
|
||||
if (registrationData.getAttestationObject() == null) {
|
||||
throw new WebAuthnException("Attestation object must not be null");
|
||||
}
|
||||
if (registrationData.getCollectedClientData() == null) {
|
||||
throw new WebAuthnException("Collected client data must not be null");
|
||||
}
|
||||
|
||||
if (!"none".equals(registrationData.getAttestationObject().getAttestationStatement().getFormat())) {
|
||||
// Refuse any attestations; clients must clear them to prevent sharing information we don't want to store
|
||||
throw new WebAuthnException("attestation format must be 'none'");
|
||||
}
|
||||
|
||||
final ServerProperty serverProperties = ServerProperty.builder()
|
||||
// we aren't verifying any signatures for registration, so we don't need to bother saving a
|
||||
// challenge; accept whatever is supplied
|
||||
.challenge(registrationData.getCollectedClientData().getChallenge())
|
||||
.origin(origin)
|
||||
.rpId(rpId)
|
||||
.build();
|
||||
|
||||
webAuthnManager.verify(registrationData,
|
||||
new RegistrationParameters(serverProperties, ALLOWED_WEBAUTHN_CREDENTIAL_ALGORITHMS, false, true));
|
||||
|
||||
return new RegistrationCeremonyResult(
|
||||
registrationData.getAttestationObject().getAuthenticatorData().getAttestedCredentialData(),
|
||||
registrationData.getCollectedClientData(),
|
||||
registrationData.getAttestationObject().getAuthenticatorData().getSignCount());
|
||||
}
|
||||
|
||||
/// Initiates a WebAuthn authentication ceremony.
|
||||
///
|
||||
/// Each call generates, and replaces any existing, [challenge](https://www.w3.org/TR/webauthn/#sctn-cryptographic-challenges).
|
||||
///
|
||||
/// @param identifier the identifier of the account to be authenticated
|
||||
/// @param existingCredentials a list of stored credential records for the user being authenticated
|
||||
///
|
||||
/// @return a [AuthenticationCeremonyParameters] record with the details
|
||||
/// needed by a client in possession of a matching authenticator to complete
|
||||
/// the ceremony
|
||||
public AuthenticationCeremonyParameters startAuthentication(final UUID identifier, List<? extends CredentialRecord> existingCredentials) {
|
||||
final byte[] challengeKey = challengeKey(identifier);
|
||||
final byte[] challenge = new byte[16];
|
||||
SECURE_RANDOM.nextBytes(challenge);
|
||||
|
||||
ResilienceUtil.getGeneralRedisRetry(RETRY_NAME)
|
||||
.executeRunnable(
|
||||
() -> challengeStorageCluster.withBinaryCluster(cluster -> cluster.sync().set(challengeKey, challenge, SetArgs.Builder.ex(challengeTtl.toSeconds()))));
|
||||
|
||||
return new AuthenticationCeremonyParameters(
|
||||
challenge,
|
||||
challengeTtl,
|
||||
existingCredentials.stream().map(cr -> cr.getAttestedCredentialData().getCredentialId()).toList());
|
||||
}
|
||||
|
||||
/// Parses an authenticator response JSON blob, whose format is specified in the WebAuthn Technical Report
|
||||
public AuthenticationData parseAuthenticationResponse(final String authenticationResponseJson) throws WebAuthnException {
|
||||
try {
|
||||
return webAuthnManager.parseAuthenticationResponseJSON(authenticationResponseJson);
|
||||
} catch (final NullPointerException | JacksonException e) {
|
||||
throw new WebAuthnException(e);
|
||||
}
|
||||
}
|
||||
|
||||
/// Verifies an authenticator response to a WebAuthn authentication ceremony, consuming any existing stored challenge.
|
||||
///
|
||||
/// If verification succeeds, the `CredentialRecord` is [updated in-place](https://www.w3.org/TR/webauthn-3/#authn-ceremony-update-credential-record).
|
||||
///
|
||||
/// @param identifier the identifier of the account to be authenticated
|
||||
/// @param matchingCredential the stored credential record for the account to be authenticated with an ID matching the one from the authenticator response
|
||||
/// @param authenticationData the parsed authenticator response
|
||||
///
|
||||
///
|
||||
/// @throws VerificationException if the response could not be verified for any reason (incorrect signature, incorrect or expired challenge)
|
||||
public void verifyAuthentication(
|
||||
final UUID identifier,
|
||||
final CredentialRecord matchingCredential,
|
||||
final AuthenticationData authenticationData) throws VerificationException {
|
||||
|
||||
final byte[] challengeKey = challengeKey(identifier);
|
||||
@Nullable final byte[] challenge = ResilienceUtil.getGeneralRedisRetry(RETRY_NAME)
|
||||
.executeSupplier(() -> challengeStorageCluster.withBinaryCluster(cluster -> cluster.sync().getdel(challengeKey)));
|
||||
|
||||
//noinspection ConstantValue
|
||||
if (challenge == null) {
|
||||
throw new BadChallengeException("no challenge stored");
|
||||
}
|
||||
|
||||
final byte[] credentialId = matchingCredential.getAttestedCredentialData().getCredentialId();
|
||||
final AuthenticationParameters authenticationParameters = new AuthenticationParameters(
|
||||
ServerProperty.builder()
|
||||
.origin(origin)
|
||||
.rpId(rpId)
|
||||
.challenge(() -> challenge)
|
||||
.build(),
|
||||
matchingCredential,
|
||||
List.of(credentialId),
|
||||
false,
|
||||
true);
|
||||
|
||||
webAuthnManager.verify(authenticationData, authenticationParameters);
|
||||
}
|
||||
|
||||
/// @return `true` if [CredentialRecord]s represent the same actual credential ID. Note that this is more specific than
|
||||
/// whether they came from the same authenticator device, which cannot be determined in general.
|
||||
public static boolean isSameCredential(final CredentialRecord a, final CredentialRecord b) {
|
||||
return Arrays.equals(a.getAttestedCredentialData().getCredentialId(), b.getAttestedCredentialData().getCredentialId());
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
static byte[] challengeKey(final UUID identifier) {
|
||||
return String.format("webauthn_challenge::{%s}", identifier).getBytes(StandardCharsets.UTF_8);
|
||||
}
|
||||
|
||||
private byte[] blindIdentifier(final UUID identifier) {
|
||||
return HmacUtils.hmac256Truncated(blindingSecret, UUIDUtil.toBytes(identifier), 32);
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -266,7 +266,7 @@ public class BackupAuthManager {
|
||||
}
|
||||
|
||||
boolean receiptAllowed = redeemedReceiptsManager
|
||||
.put(receiptSerial, receiptExpiration.getEpochSecond(), receiptLevel, account.getAccountIdentifier());
|
||||
.put(receiptSerial, receiptExpiration, receiptLevel, account.getAccountIdentifier());
|
||||
if (!receiptAllowed) {
|
||||
throw new BackupBadReceiptException("receipt serial is already redeemed");
|
||||
}
|
||||
|
||||
@@ -59,6 +59,8 @@ public class BackupManager {
|
||||
|
||||
static final String MESSAGE_BACKUP_NAME = "messageBackup";
|
||||
|
||||
private static final int DEFAULT_LIST_MEDIA_LIMIT = 1000;
|
||||
|
||||
private static final String ZK_AUTHN_COUNTER_NAME = MetricsUtil.name(BackupManager.class, "authentication");
|
||||
private static final String ZK_AUTHZ_FAILURE_COUNTER_NAME = MetricsUtil.name(BackupManager.class,
|
||||
"authorizationFailure");
|
||||
@@ -458,17 +460,19 @@ public class BackupManager {
|
||||
*
|
||||
* @param backupUser An already ZK authenticated backup user
|
||||
* @param cursor A cursor returned by a previous call that can be used to resume listing
|
||||
* @param limit The maximum number of list results to return
|
||||
* @param limit The maximum number of list results to return, or empty to use
|
||||
* {@link #DEFAULT_LIST_MEDIA_LIMIT}
|
||||
* @return A {@link ListMediaResult}
|
||||
* @throws BackupPermissionException if the credential does not have the correct level
|
||||
*/
|
||||
public ListMediaResult list(
|
||||
final AuthenticatedBackupUser backupUser,
|
||||
final Optional<String> cursor,
|
||||
final int limit) throws BackupPermissionException {
|
||||
final Optional<Integer> limit) throws BackupPermissionException {
|
||||
checkBackupLevel(backupUser, BackupLevel.FREE);
|
||||
final RemoteStorageManager.ListResult result =
|
||||
remoteStorageManager.list(cdnMediaDirectory(backupUser), cursor, limit).toCompletableFuture().join();
|
||||
final RemoteStorageManager.ListResult result = remoteStorageManager
|
||||
.list(cdnMediaDirectory(backupUser), cursor, limit.orElse(DEFAULT_LIST_MEDIA_LIMIT))
|
||||
.toCompletableFuture().join();
|
||||
return new ListMediaResult(result
|
||||
.objects()
|
||||
.stream()
|
||||
|
||||
@@ -9,7 +9,6 @@ import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
|
||||
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import jakarta.ws.rs.BadRequestException;
|
||||
import java.io.IOException;
|
||||
import java.util.Locale;
|
||||
import java.util.Optional;
|
||||
@@ -19,6 +18,8 @@ import java.util.function.Function;
|
||||
import javax.annotation.Nullable;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
|
||||
import org.whispersystems.textsecuregcm.storage.DynamicConfigurationManager;
|
||||
|
||||
public class CaptchaChecker {
|
||||
private static final Logger logger = LoggerFactory.getLogger(CaptchaChecker.class);
|
||||
@@ -33,12 +34,15 @@ public class CaptchaChecker {
|
||||
|
||||
private final ShortCodeExpander shortCodeExpander;
|
||||
private final Function<String, CaptchaClient> captchaClientSupplier;
|
||||
private final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager;
|
||||
|
||||
public CaptchaChecker(
|
||||
final ShortCodeExpander shortCodeRetriever,
|
||||
final Function<String, CaptchaClient> captchaClientSupplier) {
|
||||
final Function<String, CaptchaClient> captchaClientSupplier,
|
||||
final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager) {
|
||||
this.shortCodeExpander = shortCodeRetriever;
|
||||
this.captchaClientSupplier = captchaClientSupplier;
|
||||
this.dynamicConfigurationManager = dynamicConfigurationManager;
|
||||
}
|
||||
|
||||
|
||||
@@ -105,12 +109,21 @@ public class CaptchaChecker {
|
||||
throw new InvalidCaptchaArgumentException("invalid captcha site-key");
|
||||
}
|
||||
|
||||
final AssessmentResult result = client.verify(maybeAci, siteKey, parsedAction, token, ip, userAgent);
|
||||
Metrics.counter(ASSESSMENTS_COUNTER_NAME,
|
||||
"action", action,
|
||||
"score", result.getScoreString(),
|
||||
"provider", provider)
|
||||
.increment();
|
||||
return result;
|
||||
try {
|
||||
final AssessmentResult result = client.verify(maybeAci, siteKey, parsedAction, token, ip, userAgent);
|
||||
Metrics.counter(ASSESSMENTS_COUNTER_NAME,
|
||||
"action", action,
|
||||
"score", result.getScoreString(),
|
||||
"provider", provider)
|
||||
.increment();
|
||||
return result;
|
||||
} catch (final IOException | RuntimeException e) {
|
||||
if (dynamicConfigurationManager.getConfiguration().getCaptchaConfiguration().isFailOpen()) {
|
||||
logger.warn("Failed to verify captcha; failing open", e);
|
||||
return AssessmentResult.alwaysValid();
|
||||
}
|
||||
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
}
|
||||
+2
-1
@@ -12,6 +12,7 @@ import jakarta.validation.constraints.NotNull;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import org.whispersystems.textsecuregcm.configuration.secrets.SecretString;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.ReceiptLevel;
|
||||
import javax.annotation.Nullable;
|
||||
|
||||
/**
|
||||
@@ -38,7 +39,7 @@ public record AppleAppStoreConfiguration(
|
||||
@NotBlank String keyId,
|
||||
@NotNull SecretString encodedKey,
|
||||
@NotBlank String subscriptionGroupId,
|
||||
@NotNull Map<String, Long> productIdToLevel,
|
||||
@NotNull Map<String, ReceiptLevel> productIdToLevel,
|
||||
@NotNull List<@NotBlank String> appleRootCerts,
|
||||
@Nullable String retryConfigurationName) {
|
||||
}
|
||||
+4
-3
@@ -13,6 +13,7 @@ import com.fasterxml.jackson.annotation.Nulls;
|
||||
import io.dropwizard.validation.ValidationMethod;
|
||||
import jakarta.validation.Valid;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.ReceiptLevel;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
@@ -21,12 +22,12 @@ import java.util.stream.Collectors;
|
||||
|
||||
public class BadgesConfiguration {
|
||||
private final List<BadgeConfiguration> badges;
|
||||
private final Map<Long, String> receiptLevels;
|
||||
private final Map<ReceiptLevel, String> receiptLevels;
|
||||
|
||||
@JsonCreator
|
||||
public BadgesConfiguration(
|
||||
@JsonProperty("badges") @JsonSetter(nulls = Nulls.AS_EMPTY) final List<BadgeConfiguration> badges,
|
||||
@JsonProperty("receiptLevels") @JsonSetter(nulls = Nulls.AS_EMPTY) final Map<Long, String> receiptLevels) {
|
||||
@JsonProperty("receiptLevels") @JsonSetter(nulls = Nulls.AS_EMPTY) final Map<ReceiptLevel, String> receiptLevels) {
|
||||
this.badges = Objects.requireNonNull(badges);
|
||||
this.receiptLevels = Objects.requireNonNull(receiptLevels);
|
||||
}
|
||||
@@ -39,7 +40,7 @@ public class BadgesConfiguration {
|
||||
|
||||
@Valid
|
||||
@NotNull
|
||||
public Map<Long, String> getReceiptLevels() {
|
||||
public Map<ReceiptLevel, String> getReceiptLevels() {
|
||||
return receiptLevels;
|
||||
}
|
||||
|
||||
|
||||
+45
@@ -0,0 +1,45 @@
|
||||
/*
|
||||
* Copyright 2026 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.configuration;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import io.github.resilience4j.bulkhead.BulkheadConfig;
|
||||
import jakarta.validation.constraints.Min;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
import java.time.Duration;
|
||||
|
||||
public class BulkheadConfiguration {
|
||||
|
||||
@JsonProperty
|
||||
@Min(1)
|
||||
private int maxConcurrentCalls = BulkheadConfig.DEFAULT_MAX_CONCURRENT_CALLS;
|
||||
|
||||
@JsonProperty
|
||||
@NotNull
|
||||
private Duration maxWaitDuration = BulkheadConfig.DEFAULT_MAX_WAIT_DURATION;
|
||||
|
||||
public int getMaxConcurrentCalls() {
|
||||
return maxConcurrentCalls;
|
||||
}
|
||||
|
||||
public void setMaxConcurrentCalls(final int maxConcurrentCalls) {
|
||||
this.maxConcurrentCalls = maxConcurrentCalls;
|
||||
}
|
||||
|
||||
public Duration getMaxWaitDuration() {
|
||||
return maxWaitDuration;
|
||||
}
|
||||
|
||||
public void setMaxWaitDuration(final Duration maxWaitDuration) {
|
||||
this.maxWaitDuration = maxWaitDuration;
|
||||
}
|
||||
|
||||
public BulkheadConfig.Builder toBulkheadConfig() {
|
||||
return BulkheadConfig.custom()
|
||||
.maxConcurrentCalls(maxConcurrentCalls)
|
||||
.maxWaitDuration(maxWaitDuration);
|
||||
}
|
||||
}
|
||||
+1
-2
@@ -10,6 +10,5 @@ import java.time.Duration;
|
||||
* Configuration for Device Check operations
|
||||
*
|
||||
* @param backupRedemptionDuration How long to grant backup access for redemptions via device check
|
||||
* @param backupRedemptionLevel What backup level to grant redemptions via device check
|
||||
*/
|
||||
public record DeviceCheckConfiguration(Duration backupRedemptionDuration, long backupRedemptionLevel) {}
|
||||
public record DeviceCheckConfiguration(Duration backupRedemptionDuration) {}
|
||||
+3
-3
@@ -69,7 +69,7 @@ public class DynamoDbTables {
|
||||
private final Table profilesV2;
|
||||
private final Table pushChallenge;
|
||||
private final Table pushNotificationExperimentSamples;
|
||||
private final TableWithExpiration redeemedReceipts;
|
||||
private final Table redeemedReceipts;
|
||||
private final TableWithExpiration registrationRecovery;
|
||||
private final Table remoteConfig;
|
||||
private final Table reportMessage;
|
||||
@@ -100,7 +100,7 @@ public class DynamoDbTables {
|
||||
@JsonProperty("profilesV2") final Table profilesV2,
|
||||
@JsonProperty("pushChallenge") final Table pushChallenge,
|
||||
@JsonProperty("pushNotificationExperimentSamples") final Table pushNotificationExperimentSamples,
|
||||
@JsonProperty("redeemedReceipts") final TableWithExpiration redeemedReceipts,
|
||||
@JsonProperty("redeemedReceipts") final Table redeemedReceipts,
|
||||
@JsonProperty("registrationRecovery") final TableWithExpiration registrationRecovery,
|
||||
@JsonProperty("remoteConfig") final Table remoteConfig,
|
||||
@JsonProperty("reportMessage") final Table reportMessage,
|
||||
@@ -273,7 +273,7 @@ public class DynamoDbTables {
|
||||
|
||||
@NotNull
|
||||
@Valid
|
||||
public TableWithExpiration getRedeemedReceipts() {
|
||||
public Table getRedeemedReceipts() {
|
||||
return redeemedReceipts;
|
||||
}
|
||||
|
||||
|
||||
+22
@@ -0,0 +1,22 @@
|
||||
/*
|
||||
* Copyright 2026 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
package org.whispersystems.textsecuregcm.configuration;
|
||||
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import jakarta.validation.constraints.NotEmpty;
|
||||
import jakarta.validation.constraints.PositiveOrZero;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
/// Configuration for FoundationDB external clients. Primarily exists because an external client must be specified to
|
||||
/// make use of the multi-threaded client feature.
|
||||
///
|
||||
/// @param clientLibraryPaths a list of paths to external client libraries (generally .so files on Linux). This allows
|
||||
/// us to run multiple FDB client versions concurrently if needed; however, during normal operation, we expect the list
|
||||
/// to be a single path pointing to the current FDB client library
|
||||
/// @param threadsPerClient the number of networking threads spawned per client
|
||||
public record FoundationDbExternalClientConfiguration(@NotEmpty List<@NotBlank String> clientLibraryPaths,
|
||||
Optional<@PositiveOrZero Integer> threadsPerClient) {}
|
||||
+6
-2
@@ -5,6 +5,7 @@
|
||||
|
||||
package org.whispersystems.textsecuregcm.configuration;
|
||||
|
||||
import jakarta.annotation.Nullable;
|
||||
import jakarta.validation.Valid;
|
||||
import jakarta.validation.constraints.AssertTrue;
|
||||
import jakarta.validation.constraints.Max;
|
||||
@@ -25,7 +26,7 @@ import org.whispersystems.textsecuregcm.storage.foundationdb.FoundationDbMessage
|
||||
/// @param batchPriorityTransactionTimeout the maximum time for a batch priority transaction. Should be greater than or equal to {@link transactionTimeout}
|
||||
/// @param batchPriorityTransactionRetryLimit the maximum number of retries permitted _within_ a batch priority transaction
|
||||
public record FoundationDbMessagesConfiguration(@NotEmpty Map<String, @Valid FoundationDbDatabaseFactory> clusters,
|
||||
@NotEmpty Map<@PositiveOrZero @Max(FoundationDbMessageStore.MAX_EPOCHS - 1) Integer, @Size(min = 1, max = FoundationDbMessageStore.MAX_SHARDS - 1) List<String>> epochs,
|
||||
@NotEmpty Map<@PositiveOrZero @Max(FoundationDbMessageStore.MAX_EPOCHS - 1) Integer, @Size(min = 1, max = FoundationDbMessageStore.MAX_SHARDS) List<String>> epochs,
|
||||
@PositiveOrZero @Max(FoundationDbMessageStore.MAX_EPOCHS - 1) int activeEpoch,
|
||||
@NotEmpty Map<@PositiveOrZero @Max(63) Integer, SecretBytes> versionstampCipherKeys,
|
||||
@PositiveOrZero @Max(63) int currentVersionstampCipherKey,
|
||||
@@ -33,7 +34,10 @@ public record FoundationDbMessagesConfiguration(@NotEmpty Map<String, @Valid Fou
|
||||
@NotNull Duration transactionTimeout,
|
||||
@PositiveOrZero long transactionRetryLimit,
|
||||
@NotNull Duration batchPriorityTransactionTimeout,
|
||||
@PositiveOrZero long batchPriorityTransactionRetryLimit) {
|
||||
@PositiveOrZero long batchPriorityTransactionRetryLimit,
|
||||
@Nullable String circuitBreakerConfigurationName,
|
||||
@Nullable String bulkheadConfigurationName,
|
||||
@Nullable @Valid FoundationDbExternalClientConfiguration externalClientConfiguration) {
|
||||
|
||||
public static final long DEFAULT_MAX_WATCHES_PER_CLIENT = 10_000;
|
||||
public static final Duration DEFAULT_TRANSACTION_TIMEOUT = Duration.ofSeconds(1);
|
||||
|
||||
+2
-1
@@ -9,6 +9,7 @@ import jakarta.validation.constraints.NotBlank;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
import java.util.Map;
|
||||
import org.whispersystems.textsecuregcm.configuration.secrets.SecretString;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.ReceiptLevel;
|
||||
|
||||
/**
|
||||
* @param credentialsJson Service account credentials for Play Billing API
|
||||
@@ -21,4 +22,4 @@ public record GooglePlayBillingConfiguration(
|
||||
@NotBlank String credentialsJson,
|
||||
@NotNull String packageName,
|
||||
@NotBlank String applicationName,
|
||||
@NotNull Map<String, Long> productIdToLevel) {}
|
||||
@NotNull Map<String, ReceiptLevel> productIdToLevel) {}
|
||||
+10
-14
@@ -7,29 +7,25 @@ package org.whispersystems.textsecuregcm.configuration;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import jakarta.validation.constraints.NotEmpty;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.PaymentProvider;
|
||||
import org.whispersystems.textsecuregcm.util.EnumMapUtil;
|
||||
import java.time.Duration;
|
||||
import java.util.EnumMap;
|
||||
import java.util.Map;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.PaymentProvider;
|
||||
import org.whispersystems.textsecuregcm.util.EnumMapUtil;
|
||||
|
||||
public class IssuedReceiptsTableConfiguration extends DynamoDbTables.TableWithExpiration {
|
||||
public class IssuedReceiptsTableConfiguration extends DynamoDbTables.Table {
|
||||
|
||||
private final byte[] generator;
|
||||
|
||||
/**
|
||||
* The maximum number of issued receipts the issued receipt manager should issue for a particular itemId
|
||||
*/
|
||||
private final EnumMap<PaymentProvider, Integer> maxIssuedReceiptsPerPaymentId;
|
||||
/// The maximum number of receipts that may be issued for a single subscription payment.
|
||||
private final EnumMap<PaymentProvider, Integer> maxReceiptsPerSubscriptionPayment;
|
||||
|
||||
public IssuedReceiptsTableConfiguration(
|
||||
@JsonProperty("tableName") final String tableName,
|
||||
@JsonProperty("expiration") final Duration expiration,
|
||||
@JsonProperty("generator") final byte[] generator,
|
||||
@JsonProperty("maxIssuedReceiptsPerPaymentId") final Map<PaymentProvider, Integer> maxIssuedReceiptsPerPaymentId) {
|
||||
super(tableName, expiration);
|
||||
@JsonProperty("maxReceiptsPerSubscriptionPayment") final Map<PaymentProvider, Integer> maxReceiptsPerSubscriptionPayment) {
|
||||
super(tableName);
|
||||
this.generator = generator;
|
||||
this.maxIssuedReceiptsPerPaymentId = EnumMapUtil.toCompleteEnumMap(PaymentProvider.class, maxIssuedReceiptsPerPaymentId);
|
||||
this.maxReceiptsPerSubscriptionPayment = EnumMapUtil.toCompleteEnumMap(PaymentProvider.class, maxReceiptsPerSubscriptionPayment);
|
||||
}
|
||||
|
||||
@NotEmpty
|
||||
@@ -37,7 +33,7 @@ public class IssuedReceiptsTableConfiguration extends DynamoDbTables.TableWithEx
|
||||
return generator;
|
||||
}
|
||||
|
||||
public EnumMap<PaymentProvider, Integer> getmaxIssuedReceiptsPerPaymentId() {
|
||||
return maxIssuedReceiptsPerPaymentId;
|
||||
public EnumMap<PaymentProvider, Integer> getMaxReceiptsPerSubscriptionPayment() {
|
||||
return maxReceiptsPerSubscriptionPayment;
|
||||
}
|
||||
}
|
||||
+20
@@ -0,0 +1,20 @@
|
||||
/*
|
||||
* Copyright 2026 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
package org.whispersystems.textsecuregcm.configuration;
|
||||
|
||||
import jakarta.validation.constraints.NotEmpty;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
import jakarta.validation.constraints.Positive;
|
||||
import java.time.Duration;
|
||||
|
||||
/// Configuration for one-time Signal Login purchases
|
||||
///
|
||||
/// @param playProductId the Google Play Billing productId clients should purchase to obtain a Signal Login
|
||||
/// @param playOptionId the Google Play Billing optionId clients should purchase to obtain a Signal Login
|
||||
/// @param appStoreProductId the App Store productId clients should purchase to obtain a Signal Login
|
||||
public record LoginPurchaseConfiguration(
|
||||
@NotEmpty String playProductId,
|
||||
@NotEmpty String playOptionId,
|
||||
@NotEmpty String appStoreProductId) {}
|
||||
+1
-2
@@ -24,10 +24,9 @@ public record OneTimeDonationConfiguration(@Valid ExpiringLevelConfiguration boo
|
||||
|
||||
/**
|
||||
* @param badge the numeric donation level ID
|
||||
* @param level the badge ID associated with the level
|
||||
* @param expiration the duration after which the level expires
|
||||
*/
|
||||
public record ExpiringLevelConfiguration(@NotEmpty String badge, @Positive long level, Duration expiration) {
|
||||
public record ExpiringLevelConfiguration(@NotEmpty String badge, Duration expiration) {
|
||||
|
||||
}
|
||||
}
|
||||
+1
@@ -18,6 +18,7 @@ public record OpenTelemetryConfiguration(
|
||||
@JsonProperty Duration shutdownWaitDuration,
|
||||
@JsonProperty int maxBucketCount,
|
||||
@JsonProperty Map<String, Integer> maxBucketsPerMeter,
|
||||
@JsonProperty boolean publishMaxGaugeForHistograms,
|
||||
@JsonAnyGetter @JsonAnySetter Map<String, String> otlpConfig
|
||||
) implements OtlpConfig {
|
||||
|
||||
|
||||
+20
@@ -0,0 +1,20 @@
|
||||
/*
|
||||
* Copyright 2026 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.configuration;
|
||||
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
import java.time.Duration;
|
||||
|
||||
public record TotpConfiguration(@NotNull Duration maxValidationDelay) {
|
||||
|
||||
public static TotpConfiguration DEFAULT = new TotpConfiguration(Duration.ofSeconds(15));
|
||||
|
||||
public TotpConfiguration {
|
||||
if (maxValidationDelay == null) {
|
||||
maxValidationDelay = DEFAULT.maxValidationDelay();
|
||||
}
|
||||
}
|
||||
}
|
||||
+19
@@ -0,0 +1,19 @@
|
||||
/*
|
||||
* Copyright 2026 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.configuration;
|
||||
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
import java.time.Duration;
|
||||
import org.whispersystems.textsecuregcm.configuration.secrets.SecretBytes;
|
||||
import org.whispersystems.textsecuregcm.util.ExactlySize;
|
||||
|
||||
public record WebAuthnConfiguration(
|
||||
@NotBlank String relyingPartyId,
|
||||
@NotBlank String origin,
|
||||
@NotNull Duration challengeTtl,
|
||||
@NotNull @ExactlySize(32) SecretBytes userHandleBlindingSecret) {
|
||||
}
|
||||
+10
@@ -35,6 +35,9 @@ public class DynamicCaptchaConfiguration {
|
||||
@NotNull
|
||||
private Map<Action, BigDecimal> scoreFloorByAction = Collections.emptyMap();
|
||||
|
||||
@JsonProperty
|
||||
private boolean failOpen = false;
|
||||
|
||||
public BigDecimal getScoreFloor() {
|
||||
return scoreFloor;
|
||||
}
|
||||
@@ -66,4 +69,11 @@ public class DynamicCaptchaConfiguration {
|
||||
this.hCaptchaSiteKeys = hCaptchaSiteKeys;
|
||||
}
|
||||
|
||||
public boolean isFailOpen() {
|
||||
return failOpen;
|
||||
}
|
||||
|
||||
public void setFailOpen(final boolean failOpen) {
|
||||
this.failOpen = failOpen;
|
||||
}
|
||||
}
|
||||
+9
-1
@@ -35,7 +35,7 @@ public class DynamicConfiguration {
|
||||
|
||||
@JsonProperty
|
||||
@Valid
|
||||
private DynamicPaymentsConfiguration payments = new DynamicPaymentsConfiguration();
|
||||
private DynamicPaymentsConfiguration payments = DynamicPaymentsConfiguration.DEFAULT;
|
||||
|
||||
@JsonProperty
|
||||
@Valid
|
||||
@@ -85,6 +85,10 @@ public class DynamicConfiguration {
|
||||
@Valid
|
||||
private DynamicTurnConfiguration turn = new DynamicTurnConfiguration();
|
||||
|
||||
@JsonProperty
|
||||
@Valid
|
||||
private DynamicLoginPurchaseConfiguration loginPurchase = new DynamicLoginPurchaseConfiguration(false);
|
||||
|
||||
public Optional<DynamicExperimentEnrollmentConfiguration> getExperimentEnrollmentConfiguration(
|
||||
final String experimentName) {
|
||||
return Optional.ofNullable(experiments.get(experimentName));
|
||||
@@ -154,4 +158,8 @@ public class DynamicConfiguration {
|
||||
public DynamicTurnConfiguration getTurnConfiguration() {
|
||||
return turn;
|
||||
}
|
||||
|
||||
public DynamicLoginPurchaseConfiguration getLoginPurchaseConfiguration() {
|
||||
return loginPurchase;
|
||||
}
|
||||
}
|
||||
+8
@@ -0,0 +1,8 @@
|
||||
/*
|
||||
* Copyright 2026 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
package org.whispersystems.textsecuregcm.configuration.dynamic;
|
||||
|
||||
/// @param enabled whether clients may exchange a one-time purchase for a Signal Login receipt credential
|
||||
public record DynamicLoginPurchaseConfiguration(boolean enabled) {}
|
||||
+13
-5
@@ -6,15 +6,23 @@
|
||||
package org.whispersystems.textsecuregcm.configuration.dynamic;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
|
||||
public class DynamicPaymentsConfiguration {
|
||||
public record DynamicPaymentsConfiguration(@JsonProperty @NotNull List<String> disallowedPrefixes,
|
||||
@JsonProperty @NotNull List<String> disallowedAsnRegions) {
|
||||
|
||||
@JsonProperty
|
||||
private List<String> disallowedPrefixes = Collections.emptyList();
|
||||
public static DynamicPaymentsConfiguration DEFAULT =
|
||||
new DynamicPaymentsConfiguration(Collections.emptyList(), Collections.emptyList());
|
||||
|
||||
public List<String> getDisallowedPrefixes() {
|
||||
return disallowedPrefixes;
|
||||
public DynamicPaymentsConfiguration {
|
||||
if (disallowedPrefixes == null) {
|
||||
disallowedPrefixes = DEFAULT.disallowedPrefixes();
|
||||
}
|
||||
|
||||
if (disallowedAsnRegions == null) {
|
||||
disallowedAsnRegions = DEFAULT.disallowedAsnRegions();
|
||||
}
|
||||
}
|
||||
}
|
||||
+38
-33
@@ -4,12 +4,7 @@
|
||||
*/
|
||||
package org.whispersystems.textsecuregcm.controllers;
|
||||
|
||||
import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
|
||||
|
||||
import io.dropwizard.auth.Auth;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import io.micrometer.core.instrument.Tag;
|
||||
import io.micrometer.core.instrument.Tags;
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
import io.swagger.v3.oas.annotations.Parameter;
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
@@ -30,11 +25,13 @@ import jakarta.ws.rs.PathParam;
|
||||
import jakarta.ws.rs.Produces;
|
||||
import jakarta.ws.rs.QueryParam;
|
||||
import jakarta.ws.rs.WebApplicationException;
|
||||
import jakarta.ws.rs.core.HttpHeaders;
|
||||
import jakarta.ws.rs.core.MediaType;
|
||||
import jakarta.ws.rs.core.Response;
|
||||
import jakarta.ws.rs.core.Response.Status;
|
||||
import java.util.Base64;
|
||||
import java.util.Collection;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
@@ -58,20 +55,19 @@ import org.whispersystems.textsecuregcm.entities.ReserveUsernameHashResponse;
|
||||
import org.whispersystems.textsecuregcm.entities.UsernameHashResponse;
|
||||
import org.whispersystems.textsecuregcm.entities.UsernameLinkHandle;
|
||||
import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.identity.IdentityType;
|
||||
import org.whispersystems.textsecuregcm.identity.ServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimitedByIp;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimiters;
|
||||
import org.whispersystems.textsecuregcm.metrics.UserAgentTagUtil;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.Device;
|
||||
import org.whispersystems.textsecuregcm.storage.RegistrationRecoveryPasswordsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.PhoneNumberRecoveryPasswordsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.UsernameHashNotAvailableException;
|
||||
import org.whispersystems.textsecuregcm.storage.UsernameReservationNotFoundException;
|
||||
import org.whispersystems.textsecuregcm.util.HeaderUtils;
|
||||
import org.whispersystems.textsecuregcm.util.UsernameHashZkProofVerifier;
|
||||
import org.whispersystems.textsecuregcm.util.Util;
|
||||
import software.amazon.awssdk.services.dynamodb.model.TransactWriteItem;
|
||||
|
||||
@SuppressWarnings("OptionalUsedAsFieldOrParameterType")
|
||||
@Path("/v1/accounts")
|
||||
@@ -81,23 +77,19 @@ public class AccountController {
|
||||
public static final int USERNAME_HASH_LENGTH = 32;
|
||||
public static final int MAXIMUM_USERNAME_CIPHERTEXT_LENGTH = 128;
|
||||
|
||||
private static final String RECOVERY_PASSWORD_SET_COUNTER_NAME =
|
||||
name(AccountController.class, "recoveryPasswordSet");
|
||||
|
||||
|
||||
private final AccountsManager accounts;
|
||||
private final RateLimiters rateLimiters;
|
||||
private final RegistrationRecoveryPasswordsManager registrationRecoveryPasswordsManager;
|
||||
private final PhoneNumberRecoveryPasswordsManager phoneNumberRecoveryPasswordsManager;
|
||||
private final UsernameHashZkProofVerifier usernameHashZkProofVerifier;
|
||||
|
||||
public AccountController(
|
||||
AccountsManager accounts,
|
||||
RateLimiters rateLimiters,
|
||||
RegistrationRecoveryPasswordsManager registrationRecoveryPasswordsManager,
|
||||
PhoneNumberRecoveryPasswordsManager phoneNumberRecoveryPasswordsManager,
|
||||
UsernameHashZkProofVerifier usernameHashZkProofVerifier) {
|
||||
this.accounts = accounts;
|
||||
this.rateLimiters = rateLimiters;
|
||||
this.registrationRecoveryPasswordsManager = registrationRecoveryPasswordsManager;
|
||||
this.phoneNumberRecoveryPasswordsManager = phoneNumberRecoveryPasswordsManager;
|
||||
this.usernameHashZkProofVerifier = usernameHashZkProofVerifier;
|
||||
}
|
||||
|
||||
@@ -166,8 +158,12 @@ public class AccountController {
|
||||
public void setRegistrationLock(@Auth AuthenticatedDevice auth, @NotNull @Valid RegistrationLock accountLock) {
|
||||
final SaltedTokenHash credentials = SaltedTokenHash.generateFor(accountLock.registrationLock());
|
||||
|
||||
accounts.update(auth.accountIdentifier(),
|
||||
a -> a.setRegistrationLock(credentials.hash(), credentials.salt()));
|
||||
try {
|
||||
accounts.update(auth.accountIdentifier(),
|
||||
a -> a.setRegistrationLock(credentials.hash(), credentials.salt()));
|
||||
} catch (IllegalArgumentException _) {
|
||||
throw new BadRequestException();
|
||||
}
|
||||
}
|
||||
|
||||
@DELETE
|
||||
@@ -211,7 +207,7 @@ public class AccountController {
|
||||
throw new ForbiddenException();
|
||||
}
|
||||
|
||||
accounts.updateDevice(account.getIdentifier(IdentityType.ACI), targetDeviceId, d -> d.setName(deviceName.deviceName()));
|
||||
accounts.updateDevice(account.getAccountIdentifier(), targetDeviceId, d -> d.setName(deviceName.deviceName()));
|
||||
}
|
||||
|
||||
@PUT
|
||||
@@ -220,11 +216,19 @@ public class AccountController {
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
public void setAccountAttributes(
|
||||
@Auth AuthenticatedDevice auth,
|
||||
@HeaderParam(HttpHeaders.USER_AGENT) String userAgent,
|
||||
@HeaderParam(HeaderUtils.X_SIGNAL_AGENT) String signalAgent,
|
||||
@NotNull @Valid AccountAttributes attributes) {
|
||||
|
||||
final Account updatedAccount = accounts.update(auth.accountIdentifier(), a -> {
|
||||
final Account account = accounts.getByAccountIdentifier(auth.accountIdentifier())
|
||||
.orElseThrow(() -> new WebApplicationException(Status.UNAUTHORIZED));
|
||||
|
||||
final Collection<TransactWriteItem> additionalWriteItems =
|
||||
account.getPhoneNumberIdentifier()
|
||||
.flatMap(phoneNumberIdentifier -> attributes.recoveryPassword().map(recoveryPassword ->
|
||||
List.of(phoneNumberRecoveryPasswordsManager.buildTransactWriteItemForStorePassword(phoneNumberIdentifier, recoveryPassword))))
|
||||
.orElseGet(Collections::emptyList);
|
||||
|
||||
accounts.update(auth.accountIdentifier(), a -> {
|
||||
a.getDevice(auth.deviceId()).ifPresent(d -> {
|
||||
d.setFetchesMessages(attributes.getFetchesMessages());
|
||||
d.setName(attributes.getName());
|
||||
@@ -235,21 +239,22 @@ public class AccountController {
|
||||
}
|
||||
});
|
||||
|
||||
if (StringUtils.isNotEmpty(attributes.getRegistrationLock()) && a.getNumber().isEmpty()) {
|
||||
throw new BadRequestException("account does not have a phone number");
|
||||
}
|
||||
|
||||
a.setRegistrationLockFromAttributes(attributes);
|
||||
a.setUnidentifiedAccessKey(attributes.getUnidentifiedAccessKey());
|
||||
a.setUnrestrictedUnidentifiedAccess(attributes.isUnrestrictedUnidentifiedAccess());
|
||||
a.setDiscoverableByPhoneNumber(attributes.isDiscoverableByPhoneNumber());
|
||||
});
|
||||
|
||||
// if registration recovery password was sent to us, store it (or refresh its expiration)
|
||||
attributes.recoveryPassword().ifPresent(registrationRecoveryPassword -> {
|
||||
final boolean rrpCreated = registrationRecoveryPasswordsManager
|
||||
.store(updatedAccount.getIdentifier(IdentityType.PNI), registrationRecoveryPassword);
|
||||
Metrics.counter(RECOVERY_PASSWORD_SET_COUNTER_NAME, Tags.of(
|
||||
UserAgentTagUtil.getPlatformTag(userAgent),
|
||||
Tag.of("outcome", rrpCreated ? "created" : "updated")))
|
||||
.increment();
|
||||
});
|
||||
if (attributes.isDiscoverableByPhoneNumber() && a.getNumber().isEmpty()) {
|
||||
throw new BadRequestException("account does not have a phone number");
|
||||
}
|
||||
|
||||
a.setDiscoverableByPhoneNumber(attributes.isDiscoverableByPhoneNumber());
|
||||
|
||||
attributes.recoveryPassword().ifPresent(a::setAccountRecoveryPassword);
|
||||
}, additionalWriteItems);
|
||||
}
|
||||
|
||||
@GET
|
||||
@@ -433,7 +438,7 @@ public class AccountController {
|
||||
} else {
|
||||
usernameLinkHandle = UUID.randomUUID();
|
||||
}
|
||||
updateUsernameLink(account.getIdentifier(IdentityType.ACI), usernameLinkHandle, encryptedUsername.usernameLinkEncryptedValue());
|
||||
updateUsernameLink(account.getAccountIdentifier(), usernameLinkHandle, encryptedUsername.usernameLinkEncryptedValue());
|
||||
return new UsernameLinkHandle(usernameLinkHandle);
|
||||
}
|
||||
|
||||
|
||||
+7
-2
@@ -155,8 +155,13 @@ public class AccountControllerV2 {
|
||||
@Auth AuthenticatedDevice auth,
|
||||
@NotNull @Valid PhoneNumberDiscoverabilityRequest phoneNumberDiscoverability) {
|
||||
|
||||
accountsManager.update(auth.accountIdentifier(), a -> a.setDiscoverableByPhoneNumber(
|
||||
phoneNumberDiscoverability.discoverableByPhoneNumber()));
|
||||
accountsManager.update(auth.accountIdentifier(), account -> {
|
||||
if (account.getNumber().isEmpty()) {
|
||||
throw new BadRequestException();
|
||||
}
|
||||
|
||||
account.setDiscoverableByPhoneNumber(phoneNumberDiscoverability.discoverableByPhoneNumber());
|
||||
});
|
||||
}
|
||||
|
||||
@GET
|
||||
|
||||
+5
-4
@@ -18,18 +18,18 @@ public class AccountIdentityResponseBuilder {
|
||||
private boolean storageCapable;
|
||||
private Clock clock;
|
||||
|
||||
public AccountIdentityResponseBuilder(Account account) {
|
||||
public AccountIdentityResponseBuilder(final Account account) {
|
||||
this.account = account;
|
||||
this.storageCapable = account.hasCapability(DeviceCapability.STORAGE);
|
||||
this.clock = Clock.systemUTC();
|
||||
}
|
||||
|
||||
public AccountIdentityResponseBuilder storageCapable(boolean storageCapable) {
|
||||
public AccountIdentityResponseBuilder storageCapable(final boolean storageCapable) {
|
||||
this.storageCapable = storageCapable;
|
||||
return this;
|
||||
}
|
||||
|
||||
public AccountIdentityResponseBuilder clock(Clock clock) {
|
||||
public AccountIdentityResponseBuilder clock(final Clock clock) {
|
||||
this.clock = clock;
|
||||
return this;
|
||||
}
|
||||
@@ -53,7 +53,8 @@ public class AccountIdentityResponseBuilder {
|
||||
account.getUsernameHash().filter(h -> h.length > 0).orElse(null),
|
||||
account.getUsernameLinkHandle(),
|
||||
storageCapable,
|
||||
new Entitlements(badges, backupEntitlement));
|
||||
new Entitlements(badges, backupEntitlement),
|
||||
account.getAuthCredentialSalt().orElse(null));
|
||||
}
|
||||
|
||||
public static AccountIdentityResponse fromAccount(final Account account) {
|
||||
|
||||
+1
-1
@@ -975,7 +975,7 @@ public class ArchiveController {
|
||||
final AuthenticatedBackupUser backupUser =
|
||||
backupManager.authenticateBackupUser(presentation.presentation, signature.signature, userAgent);
|
||||
final BackupManager.ListMediaResult listResult =
|
||||
backupManager.list(backupUser, cursor, limit.orElse(1000));
|
||||
backupManager.list(backupUser, cursor, limit);
|
||||
return new ListResponse(listResult.media()
|
||||
.stream().map(entry -> new StoredMediaObject(entry.cdn(), entry.key(), entry.length()))
|
||||
.toList(),
|
||||
|
||||
+10
-3
@@ -2,6 +2,7 @@ package org.whispersystems.textsecuregcm.controllers;
|
||||
|
||||
import io.dropwizard.auth.Auth;
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
import io.swagger.v3.oas.annotations.Parameter;
|
||||
import io.swagger.v3.oas.annotations.responses.ApiResponse;
|
||||
import jakarta.validation.Valid;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
@@ -9,6 +10,7 @@ import jakarta.ws.rs.BadRequestException;
|
||||
import jakarta.ws.rs.POST;
|
||||
import jakarta.ws.rs.Path;
|
||||
import jakarta.ws.rs.Produces;
|
||||
import jakarta.ws.rs.QueryParam;
|
||||
import jakarta.ws.rs.core.MediaType;
|
||||
import java.time.Instant;
|
||||
import java.time.temporal.ChronoUnit;
|
||||
@@ -26,13 +28,16 @@ import org.whispersystems.textsecuregcm.limits.RateLimiters;
|
||||
public class CallLinkController {
|
||||
private final RateLimiters rateLimiters;
|
||||
private final GenericServerSecretParams genericServerSecretParams;
|
||||
private final GenericServerSecretParams genericServerSecretParamsPreV101;
|
||||
|
||||
public CallLinkController(
|
||||
final RateLimiters rateLimiters,
|
||||
final GenericServerSecretParams genericServerSecretParams
|
||||
final GenericServerSecretParams genericServerSecretParams,
|
||||
final GenericServerSecretParams genericServerSecretParamsPreV101
|
||||
) {
|
||||
this.rateLimiters = rateLimiters;
|
||||
this.genericServerSecretParams = genericServerSecretParams;
|
||||
this.genericServerSecretParamsPreV101 = genericServerSecretParamsPreV101;
|
||||
}
|
||||
|
||||
@POST
|
||||
@@ -52,7 +57,9 @@ public class CallLinkController {
|
||||
@ApiResponse(responseCode = "429", description = "Ratelimited.")
|
||||
public CreateCallLinkCredential getCreateAuth(
|
||||
final @Auth AuthenticatedDevice auth,
|
||||
final @NotNull @Valid GetCreateCallLinkCredentialsRequest request
|
||||
final @NotNull @Valid GetCreateCallLinkCredentialsRequest request,
|
||||
@Parameter(description = "Whether to use libsignal v0.101.0+ secret params")
|
||||
final @QueryParam("v101") boolean v101
|
||||
) throws RateLimitExceededException {
|
||||
|
||||
rateLimiters.getCreateCallLinkLimiter().validate(auth.accountIdentifier());
|
||||
@@ -67,7 +74,7 @@ public class CallLinkController {
|
||||
}
|
||||
|
||||
return new CreateCallLinkCredential(
|
||||
createCallLinkCredentialRequest.issueCredential(new ServiceId.Aci(auth.accountIdentifier()), truncatedDayTimestamp, genericServerSecretParams).serialize(),
|
||||
createCallLinkCredentialRequest.issueCredential(new ServiceId.Aci(auth.accountIdentifier()), truncatedDayTimestamp, v101 ? genericServerSecretParams : genericServerSecretParamsPreV101).serialize(),
|
||||
truncatedDayTimestamp.getEpochSecond()
|
||||
);
|
||||
}
|
||||
|
||||
+23
-9
@@ -10,6 +10,7 @@ import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import io.dropwizard.auth.Auth;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import io.swagger.v3.oas.annotations.Parameter;
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
import jakarta.ws.rs.BadRequestException;
|
||||
import jakarta.ws.rs.DefaultValue;
|
||||
@@ -26,6 +27,7 @@ import java.time.Instant;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
import java.util.Optional;
|
||||
import javax.annotation.Nonnull;
|
||||
import org.signal.libsignal.protocol.ServiceId;
|
||||
import org.signal.libsignal.zkgroup.GenericServerSecretParams;
|
||||
@@ -37,7 +39,6 @@ import org.whispersystems.textsecuregcm.auth.CertificateGenerator;
|
||||
import org.whispersystems.textsecuregcm.auth.RedemptionRange;
|
||||
import org.whispersystems.textsecuregcm.entities.DeliveryCertificate;
|
||||
import org.whispersystems.textsecuregcm.entities.GroupCredentials;
|
||||
import org.whispersystems.textsecuregcm.identity.IdentityType;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountsManager;
|
||||
|
||||
@@ -49,6 +50,7 @@ public class CertificateController {
|
||||
private final CertificateGenerator certificateGenerator;
|
||||
private final ServerZkAuthOperations serverZkAuthOperations;
|
||||
private final GenericServerSecretParams genericServerSecretParams;
|
||||
private final GenericServerSecretParams genericServerSecretParamsPreV101;
|
||||
private final Clock clock;
|
||||
|
||||
@VisibleForTesting
|
||||
@@ -61,12 +63,14 @@ public class CertificateController {
|
||||
@Nonnull CertificateGenerator certificateGenerator,
|
||||
@Nonnull ServerZkAuthOperations serverZkAuthOperations,
|
||||
@Nonnull GenericServerSecretParams genericServerSecretParams,
|
||||
@Nonnull GenericServerSecretParams genericServerSecretParamsPreV101,
|
||||
@Nonnull Clock clock) {
|
||||
|
||||
this.accountsManager = accountsManager;
|
||||
this.certificateGenerator = Objects.requireNonNull(certificateGenerator);
|
||||
this.serverZkAuthOperations = Objects.requireNonNull(serverZkAuthOperations);
|
||||
this.genericServerSecretParams = genericServerSecretParams;
|
||||
this.genericServerSecretParamsPreV101 = genericServerSecretParamsPreV101;
|
||||
this.clock = Objects.requireNonNull(clock);
|
||||
}
|
||||
|
||||
@@ -82,8 +86,11 @@ public class CertificateController {
|
||||
final Account account = accountsManager.getByAccountIdentifier(auth.accountIdentifier())
|
||||
.orElseThrow(() -> new WebApplicationException(Response.Status.UNAUTHORIZED));
|
||||
|
||||
return new DeliveryCertificate(
|
||||
certificateGenerator.createFor(account, auth.deviceId(), includeE164));
|
||||
try {
|
||||
return new DeliveryCertificate(certificateGenerator.createFor(account, auth.deviceId(), includeE164));
|
||||
} catch (final IllegalArgumentException _) {
|
||||
throw new BadRequestException();
|
||||
}
|
||||
}
|
||||
|
||||
@GET
|
||||
@@ -92,7 +99,9 @@ public class CertificateController {
|
||||
public GroupCredentials getGroupAuthenticationCredentials(
|
||||
@Auth AuthenticatedDevice auth,
|
||||
@QueryParam("redemptionStartSeconds") long startSeconds,
|
||||
@QueryParam("redemptionEndSeconds") long endSeconds) {
|
||||
@QueryParam("redemptionEndSeconds") long endSeconds,
|
||||
@Parameter(description = "Whether to use libsignal v0.101.0+ secret params")
|
||||
@QueryParam("v101") boolean v101) {
|
||||
|
||||
final RedemptionRange redemptionRange;
|
||||
try {
|
||||
@@ -109,20 +118,25 @@ public class CertificateController {
|
||||
final List<GroupCredentials.GroupCredential> credentials = new ArrayList<>();
|
||||
final List<GroupCredentials.CallLinkAuthCredential> callLinkAuthCredentials = new ArrayList<>();
|
||||
|
||||
final ServiceId.Aci aci = new ServiceId.Aci(account.getIdentifier(IdentityType.ACI));
|
||||
final ServiceId.Pni pni = new ServiceId.Pni(account.getIdentifier(IdentityType.PNI));
|
||||
final ServiceId.Aci aci = new ServiceId.Aci(account.getAccountIdentifier());
|
||||
final Optional<ServiceId.Pni> maybePni = account.getPhoneNumberIdentifier().map(ServiceId.Pni::new);
|
||||
|
||||
for (Instant redemption : redemptionRange) {
|
||||
AuthCredentialWithPniResponse authCredentialWithPni = serverZkAuthOperations.issueAuthCredentialWithPniZkc(aci, pni, redemption);
|
||||
final AuthCredentialWithPniResponse authCredentialWithPni =
|
||||
maybePni.map(pni -> serverZkAuthOperations.issueAuthCredentialWithPniZkc(aci, pni, redemption))
|
||||
.orElseGet(() -> serverZkAuthOperations.issueAuthCredentialZkcWithoutPni(aci,
|
||||
account.getAuthCredentialSalt()
|
||||
.orElseThrow(() -> new IllegalStateException("account without PNI must have auth credential salt")),
|
||||
redemption));
|
||||
credentials.add(new GroupCredentials.GroupCredential(
|
||||
authCredentialWithPni.serialize(),
|
||||
(int) redemption.getEpochSecond()));
|
||||
|
||||
callLinkAuthCredentials.add(new GroupCredentials.CallLinkAuthCredential(
|
||||
CallLinkAuthCredentialResponse.issueCredential(aci, redemption, genericServerSecretParams).serialize(),
|
||||
CallLinkAuthCredentialResponse.issueCredential(aci, redemption, v101 ? genericServerSecretParams : genericServerSecretParamsPreV101).serialize(),
|
||||
redemption.getEpochSecond()));
|
||||
}
|
||||
|
||||
return new GroupCredentials(credentials, callLinkAuthCredentials, pni.getRawUUID());
|
||||
return new GroupCredentials(credentials, callLinkAuthCredentials, maybePni.map(ServiceId.Pni::getRawUUID).orElse(null));
|
||||
}
|
||||
}
|
||||
+8
-4
@@ -14,6 +14,7 @@ import io.swagger.v3.oas.annotations.responses.ApiResponse;
|
||||
import jakarta.validation.Valid;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
import jakarta.ws.rs.Consumes;
|
||||
import jakarta.ws.rs.ForbiddenException;
|
||||
import jakarta.ws.rs.GET;
|
||||
import jakarta.ws.rs.POST;
|
||||
import jakarta.ws.rs.PUT;
|
||||
@@ -29,11 +30,13 @@ import java.time.Duration;
|
||||
import java.util.Base64;
|
||||
import java.util.Locale;
|
||||
import org.glassfish.jersey.server.ManagedAsync;
|
||||
import org.signal.libsignal.zkgroup.backups.BackupLevel;
|
||||
import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
|
||||
import org.whispersystems.textsecuregcm.backup.BackupAuthManager;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimiters;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.Device;
|
||||
import org.whispersystems.textsecuregcm.storage.devicecheck.AppleDeviceCheckManager;
|
||||
import org.whispersystems.textsecuregcm.storage.devicecheck.ChallengeNotFoundException;
|
||||
import org.whispersystems.textsecuregcm.storage.devicecheck.DeviceCheckKeyIdNotFoundException;
|
||||
@@ -59,7 +62,6 @@ public class DeviceCheckController {
|
||||
private final BackupAuthManager backupAuthManager;
|
||||
private final AppleDeviceCheckManager deviceCheckManager;
|
||||
private final RateLimiters rateLimiters;
|
||||
private final long backupRedemptionLevel;
|
||||
private final Duration backupRedemptionDuration;
|
||||
|
||||
public DeviceCheckController(
|
||||
@@ -68,13 +70,11 @@ public class DeviceCheckController {
|
||||
final BackupAuthManager backupAuthManager,
|
||||
final AppleDeviceCheckManager deviceCheckManager,
|
||||
final RateLimiters rateLimiters,
|
||||
final long backupRedemptionLevel,
|
||||
final Duration backupRedemptionDuration) {
|
||||
this.clock = clock;
|
||||
this.accountsManager = accountsManager;
|
||||
this.backupAuthManager = backupAuthManager;
|
||||
this.deviceCheckManager = deviceCheckManager;
|
||||
this.backupRedemptionLevel = backupRedemptionLevel;
|
||||
this.backupRedemptionDuration = backupRedemptionDuration;
|
||||
this.rateLimiters = rateLimiters;
|
||||
}
|
||||
@@ -141,6 +141,10 @@ public class DeviceCheckController {
|
||||
@RequestBody(description = "The attestation data, created by [attestKey](https://developer.apple.com/documentation/devicecheck/dcappattestservice/attestkey(_:clientdatahash:completionhandler:))")
|
||||
@NotNull final byte[] attestation) {
|
||||
|
||||
if (authenticatedDevice.deviceId() != Device.PRIMARY_ID) {
|
||||
throw new ForbiddenException("Only primary devices may register attestations");
|
||||
}
|
||||
|
||||
final Account account = accountsManager.getByAccountIdentifier(authenticatedDevice.accountIdentifier())
|
||||
.orElseThrow(() -> new WebApplicationException(Response.Status.UNAUTHORIZED));
|
||||
|
||||
@@ -252,7 +256,7 @@ public class DeviceCheckController {
|
||||
switch (request.assertionRequest().action()) {
|
||||
case BACKUP -> backupAuthManager.extendBackupVoucher(
|
||||
account,
|
||||
new Account.BackupVoucher(backupRedemptionLevel, clock.instant().plus(backupRedemptionDuration)));
|
||||
new Account.BackupVoucher(BackupLevel.PAID.getValue(), clock.instant().plus(backupRedemptionDuration)));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+39
-21
@@ -62,7 +62,6 @@ import org.whispersystems.textsecuregcm.entities.RemoteAttachment;
|
||||
import org.whispersystems.textsecuregcm.entities.RemoteAttachmentError;
|
||||
import org.whispersystems.textsecuregcm.entities.RestoreAccountRequest;
|
||||
import org.whispersystems.textsecuregcm.entities.TransferArchiveUploadedRequest;
|
||||
import org.whispersystems.textsecuregcm.identity.IdentityType;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimitedByIp;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimiters;
|
||||
import org.whispersystems.textsecuregcm.metrics.DevicePlatformUtil;
|
||||
@@ -72,6 +71,7 @@ import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.Device;
|
||||
import org.whispersystems.textsecuregcm.storage.DeviceCapability;
|
||||
import org.whispersystems.textsecuregcm.storage.DeviceIdentityInfo;
|
||||
import org.whispersystems.textsecuregcm.storage.DeviceSpec;
|
||||
import org.whispersystems.textsecuregcm.storage.LinkDeviceTokenAlreadyUsedException;
|
||||
import org.whispersystems.textsecuregcm.storage.PersistentTimer;
|
||||
@@ -222,7 +222,7 @@ public class DeviceController {
|
||||
""")
|
||||
@ApiResponse(responseCode = "200", description = "The new device was linked to the calling account", useReturnTypeSchema = true)
|
||||
@ApiResponse(responseCode = "403", description = "The given account was not found or the given verification code was incorrect")
|
||||
@ApiResponse(responseCode = "409", description = "The new device is missing a capability supported by all other devices on the account")
|
||||
@ApiResponse(responseCode = "409", description = "The new device is missing a capability required for the account")
|
||||
@ApiResponse(responseCode = "411", description = "The given account already has its maximum number of linked devices")
|
||||
@ApiResponse(responseCode = "422", description = "The request did not pass validation")
|
||||
@ApiResponse(responseCode = "429", description = "Too many attempts", headers = @Header(
|
||||
@@ -232,7 +232,6 @@ public class DeviceController {
|
||||
@HeaderParam(HttpHeaders.USER_AGENT) @Nullable String userAgent,
|
||||
@NotNull @Valid LinkDeviceRequest linkDeviceRequest)
|
||||
throws RateLimitExceededException, DeviceLimitExceededException {
|
||||
|
||||
final Account account = accounts.checkDeviceLinkingToken(linkDeviceRequest.verificationCode())
|
||||
.flatMap(accounts::getByAccountIdentifier)
|
||||
.orElseThrow(ForbiddenException::new);
|
||||
@@ -242,15 +241,31 @@ public class DeviceController {
|
||||
|
||||
rateLimiters.getVerifyDeviceLimiter().validate(account.getAccountIdentifier());
|
||||
|
||||
// Check the optional-phone-number capability before checking PNI keys, so we can give a better error code (since an
|
||||
// older device will improperly supply PNI keys for a PNI-less account)
|
||||
if (account.getPhoneNumberIdentifier().isEmpty() &&
|
||||
!linkDeviceRequest.deviceAttributes().capabilities().contains(DeviceCapability.OPTIONAL_PHONE_NUMBER)) {
|
||||
throw new WebApplicationException("Missing required device capability", 409);
|
||||
}
|
||||
|
||||
final boolean allKeysValid =
|
||||
PreKeySignatureValidator.validatePreKeySignatures(account.getIdentityKey(IdentityType.ACI),
|
||||
List.of(deviceActivationRequest.aciSignedPreKey(), deviceActivationRequest.aciPqLastResortPreKey()),
|
||||
userAgent,
|
||||
"link-device")
|
||||
&& PreKeySignatureValidator.validatePreKeySignatures(account.getIdentityKey(IdentityType.PNI),
|
||||
List.of(deviceActivationRequest.pniSignedPreKey(), deviceActivationRequest.pniPqLastResortPreKey()),
|
||||
userAgent,
|
||||
"link-device");
|
||||
PreKeySignatureValidator
|
||||
.validatePreKeySignatures(account.getAccountIdentityKey(),
|
||||
List.of(deviceActivationRequest.aciSignedPreKey(), deviceActivationRequest.aciPqLastResortPreKey()),
|
||||
userAgent,
|
||||
"link-device")
|
||||
&& account.getPhoneNumberIdentityKey()
|
||||
.map(pniIdentityKey ->
|
||||
deviceActivationRequest.pniSignedPreKey().isPresent()
|
||||
&& deviceActivationRequest.pniPqLastResortPreKey().isPresent()
|
||||
&& PreKeySignatureValidator.validatePreKeySignatures(
|
||||
pniIdentityKey,
|
||||
List.of(deviceActivationRequest.pniSignedPreKey().get(), deviceActivationRequest.pniPqLastResortPreKey().get()),
|
||||
userAgent,
|
||||
"link-device"))
|
||||
.orElse(
|
||||
deviceActivationRequest.pniSignedPreKey().isEmpty()
|
||||
&& deviceActivationRequest.pniPqLastResortPreKey().isEmpty());
|
||||
|
||||
if (!allKeysValid) {
|
||||
throw new WebApplicationException(Response.status(422).build());
|
||||
@@ -279,25 +294,28 @@ public class DeviceController {
|
||||
}
|
||||
|
||||
try {
|
||||
final Pair<Account, Device> accountAndDevice = accounts.addDevice(account.getIdentifier(IdentityType.ACI),
|
||||
final Pair<Account, Device> accountAndDevice = accounts.addDevice(account.getAccountIdentifier(),
|
||||
new DeviceSpec(deviceAttributes.name(),
|
||||
authorizationHeader.getPassword(),
|
||||
signalAgent,
|
||||
capabilities,
|
||||
deviceAttributes.registrationId(),
|
||||
deviceAttributes.phoneNumberIdentityRegistrationId(),
|
||||
new DeviceIdentityInfo(
|
||||
deviceAttributes.registrationId(),
|
||||
deviceActivationRequest.aciSignedPreKey(),
|
||||
deviceActivationRequest.aciPqLastResortPreKey()),
|
||||
account.getPhoneNumberIdentityKey().map(_ ->
|
||||
new DeviceIdentityInfo(
|
||||
deviceAttributes.phoneNumberIdentityRegistrationId(),
|
||||
deviceActivationRequest.pniSignedPreKey().get(),
|
||||
deviceActivationRequest.pniPqLastResortPreKey().get())),
|
||||
deviceAttributes.fetchesMessages(),
|
||||
deviceActivationRequest.apnToken(),
|
||||
deviceActivationRequest.gcmToken(),
|
||||
deviceActivationRequest.aciSignedPreKey(),
|
||||
deviceActivationRequest.pniSignedPreKey(),
|
||||
deviceActivationRequest.aciPqLastResortPreKey(),
|
||||
deviceActivationRequest.pniPqLastResortPreKey()),
|
||||
deviceActivationRequest.gcmToken()),
|
||||
linkDeviceRequest.verificationCode());
|
||||
|
||||
return new LinkDeviceResponse(
|
||||
accountAndDevice.first().getIdentifier(IdentityType.ACI),
|
||||
accountAndDevice.first().getIdentifier(IdentityType.PNI),
|
||||
accountAndDevice.first().getAccountIdentifier(),
|
||||
accountAndDevice.first().getPhoneNumberIdentifier(),
|
||||
accountAndDevice.second().getId());
|
||||
} catch (final LinkDeviceTokenAlreadyUsedException e) {
|
||||
throw new ForbiddenException();
|
||||
|
||||
+6
-2
@@ -41,6 +41,7 @@ import org.whispersystems.textsecuregcm.storage.AccountsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.DonationPermitsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.RedeemedReceiptsManager;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.ReceiptCredentialPresentationFactory;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.ReceiptLevel;
|
||||
|
||||
@Path("/v1/donation")
|
||||
@Tag(name = "Donations")
|
||||
@@ -117,7 +118,10 @@ public class DonationController {
|
||||
final ReceiptSerial receiptSerial = receiptCredentialPresentation.getReceiptSerial();
|
||||
final Instant receiptExpiration = Instant.ofEpochSecond(receiptCredentialPresentation.getReceiptExpirationTime());
|
||||
final long receiptLevel = receiptCredentialPresentation.getReceiptLevel();
|
||||
final String badgeId = badgesConfiguration.getReceiptLevels().get(receiptLevel);
|
||||
final String badgeId = ReceiptLevel
|
||||
.lookupLevel(receiptLevel)
|
||||
.map(badgesConfiguration.getReceiptLevels()::get)
|
||||
.orElse(null);
|
||||
if (badgeId == null) {
|
||||
return Response.serverError()
|
||||
.entity("server does not recognize the requested receipt level")
|
||||
@@ -126,7 +130,7 @@ public class DonationController {
|
||||
}
|
||||
|
||||
final boolean receiptMatched = redeemedReceiptsManager.put(
|
||||
receiptSerial, receiptExpiration.getEpochSecond(), receiptLevel, auth.accountIdentifier());
|
||||
receiptSerial, receiptExpiration, receiptLevel, auth.accountIdentifier());
|
||||
if (!receiptMatched) {
|
||||
return Response.status(Status.BAD_REQUEST)
|
||||
.entity("receipt serial is already redeemed")
|
||||
|
||||
+42
-9
@@ -108,6 +108,7 @@ public class KeysController {
|
||||
@Operation(summary = "Get prekey count",
|
||||
description = "Gets the number of one-time prekeys uploaded for this device and still available")
|
||||
@ApiResponse(responseCode = "200", description = "Body contains the number of available one-time prekeys for the device.", useReturnTypeSchema = true)
|
||||
@ApiResponse(responseCode = "400", description = "The request was malformed or the account does not support the requested identityType")
|
||||
@ApiResponse(responseCode = "401", description = "Account authentication check failed.")
|
||||
public CompletableFuture<PreKeyCount> getStatus(@Auth final AuthenticatedDevice auth,
|
||||
@QueryParam("identity") @DefaultValue("aci") final IdentityType identityType) {
|
||||
@@ -115,12 +116,13 @@ public class KeysController {
|
||||
return accounts.getByAccountIdentifierAsync(auth.accountIdentifier())
|
||||
.thenCompose(maybeAccount -> {
|
||||
final Account account = maybeAccount.orElseThrow(() -> new WebApplicationException(Response.Status.UNAUTHORIZED));
|
||||
final UUID identifier = getIdentifier(account, identityType);
|
||||
|
||||
final CompletableFuture<Integer> ecCountFuture =
|
||||
keysManager.getEcCount(account.getIdentifier(identityType), auth.deviceId());
|
||||
keysManager.getEcCount(identifier, auth.deviceId());
|
||||
|
||||
final CompletableFuture<Integer> pqCountFuture =
|
||||
keysManager.getPqCount(account.getIdentifier(identityType), auth.deviceId());
|
||||
keysManager.getPqCount(identifier, auth.deviceId());
|
||||
|
||||
return ecCountFuture.thenCombine(pqCountFuture, PreKeyCount::new);
|
||||
});
|
||||
@@ -131,6 +133,7 @@ public class KeysController {
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@Operation(summary = "Upload new prekeys", description = "Upload new pre-keys for this device.")
|
||||
@ApiResponse(responseCode = "200", description = "Indicates that new keys were successfully stored.")
|
||||
@ApiResponse(responseCode = "400", description = "The request was malformed or the account does not support the requested identityType")
|
||||
@ApiResponse(responseCode = "401", description = "Account authentication check failed.")
|
||||
@ApiResponse(responseCode = "403", description = "Attempt to change identity key from a non-primary device.")
|
||||
@ApiResponse(responseCode = "422", description = "Invalid request format.")
|
||||
@@ -154,9 +157,9 @@ public class KeysController {
|
||||
final Device device = account.getDevice(auth.deviceId())
|
||||
.orElseThrow(() -> new WebApplicationException(Response.Status.UNAUTHORIZED));
|
||||
|
||||
final UUID identifier = account.getIdentifier(identityType);
|
||||
final UUID identifier = getIdentifier(account, identityType);
|
||||
|
||||
checkSignedPreKeySignatures(setKeysRequest, account.getIdentityKey(identityType), userAgent);
|
||||
checkSignedPreKeySignatures(setKeysRequest, getIdentityKey(account, identityType), userAgent);
|
||||
|
||||
final Tag platformTag = UserAgentTagUtil.getPlatformTag(userAgent);
|
||||
final Tag primaryDeviceTag = Tag.of(PRIMARY_DEVICE_TAG_NAME, String.valueOf(auth.deviceId() == Device.PRIMARY_ID));
|
||||
@@ -244,6 +247,7 @@ public class KeysController {
|
||||
version byte followed by 1568 bytes of key material for a total of 1569 bytes)
|
||||
""")
|
||||
@ApiResponse(responseCode = "200", description = "Indicates that client and server have consistent views of repeated-use keys")
|
||||
@ApiResponse(responseCode = "400", description = "The request was malformed or the account does not support the requested identityType")
|
||||
@ApiResponse(responseCode = "401", description = "Account authentication check failed")
|
||||
@ApiResponse(responseCode = "409", description = """
|
||||
Indicates that client and server have inconsistent views of repeated-use keys or one or more repeated-use keys could
|
||||
@@ -258,7 +262,7 @@ public class KeysController {
|
||||
.thenCompose(maybeAccount -> {
|
||||
final Account account = maybeAccount.orElseThrow(() -> new WebApplicationException(Response.Status.UNAUTHORIZED));
|
||||
|
||||
final UUID identifier = account.getIdentifier(checkKeysRequest.identityType());
|
||||
final UUID identifier = getIdentifier(account, checkKeysRequest.identityType());
|
||||
final byte deviceId = auth.deviceId();
|
||||
|
||||
final CompletableFuture<Optional<ECSignedPreKey>> ecSignedPreKeyFuture =
|
||||
@@ -275,7 +279,7 @@ public class KeysController {
|
||||
final boolean digestsMatch;
|
||||
|
||||
if (maybeSignedPreKey.isPresent() && maybeLastResortKey.isPresent()) {
|
||||
final IdentityKey identityKey = account.getIdentityKey(checkKeysRequest.identityType());
|
||||
final IdentityKey identityKey = getIdentityKey(account, checkKeysRequest.identityType());
|
||||
final ECSignedPreKey ecSignedPreKey = maybeSignedPreKey.get();
|
||||
final KEMSignedPreKey lastResortKey = maybeLastResortKey.get();
|
||||
|
||||
@@ -380,7 +384,12 @@ public class KeysController {
|
||||
.fromCompletionStage(keysManager.takeDevicePreKeys(device.getId(), targetIdentifier, userAgent))
|
||||
.flatMap(Mono::justOrEmpty)
|
||||
.map(devicePreKeys -> new PreKeyResponseItem(
|
||||
device.getId(), device.getRegistrationId(targetIdentifier.identityType()),
|
||||
device.getId(),
|
||||
switch (targetIdentifier.identityType()) {
|
||||
case ACI -> device.getAccountRegistrationId();
|
||||
case PNI -> device.getPhoneNumberIdentityRegistrationId()
|
||||
.orElseThrow(() -> new IllegalStateException("Device on account retrieved by PNI does not have a PNI registration ID"));
|
||||
},
|
||||
devicePreKeys.ecSignedPreKey(),
|
||||
devicePreKeys.ecPreKey().orElse(null),
|
||||
devicePreKeys.kemSignedPreKey())))
|
||||
@@ -388,7 +397,11 @@ public class KeysController {
|
||||
.blockOptional()
|
||||
.orElseGet(Collections::emptyList);
|
||||
|
||||
final IdentityKey identityKey = target.getIdentityKey(targetIdentifier.identityType());
|
||||
final IdentityKey identityKey = switch (targetIdentifier.identityType()) {
|
||||
case ACI -> target.getAccountIdentityKey();
|
||||
case PNI -> target.getPhoneNumberIdentityKey()
|
||||
.orElseThrow(() -> new IllegalStateException("Account retrieved by PNI does not have a PNI identity key"));
|
||||
};
|
||||
|
||||
if (responseItems.isEmpty()) {
|
||||
throw new WebApplicationException(Response.Status.NOT_FOUND);
|
||||
@@ -424,7 +437,10 @@ public class KeysController {
|
||||
final Optional<Byte> parsedTargetDeviceId = parseDeviceId(targetDeviceId);
|
||||
final Optional<Integer> targetRegistrationId = parsedTargetDeviceId
|
||||
.flatMap(targetAccount::getDevice)
|
||||
.map(device -> device.getRegistrationId(targetIdentifier.identityType()));
|
||||
.flatMap(device -> switch (targetIdentifier.identityType()) {
|
||||
case ACI -> Optional.of(device.getAccountRegistrationId());
|
||||
case PNI -> device.getPhoneNumberIdentityRegistrationId();
|
||||
});
|
||||
return RateLimitKeys.preKeyLimiterKey(
|
||||
account.getAccountIdentifier(),
|
||||
authenticatedDevice.deviceId(),
|
||||
@@ -432,4 +448,21 @@ public class KeysController {
|
||||
parsedTargetDeviceId, targetRegistrationId);
|
||||
}
|
||||
|
||||
/// Get the identity of the requested `idenityType`, or throw a [BadRequestException] if `account` does not contain
|
||||
/// that type.
|
||||
private static UUID getIdentifier(final Account account, final IdentityType identityType) {
|
||||
return switch (identityType) {
|
||||
case ACI -> account.getAccountIdentifier();
|
||||
case PNI -> account.getPhoneNumberIdentifier()
|
||||
.orElseThrow(() -> new BadRequestException("Cannot set PNI identity keys on an account without a number"));
|
||||
};
|
||||
}
|
||||
|
||||
private static IdentityKey getIdentityKey(final Account account, final IdentityType identityType) {
|
||||
return switch (identityType) {
|
||||
case ACI -> account.getAccountIdentityKey();
|
||||
case PNI -> account.getPhoneNumberIdentityKey()
|
||||
.orElseThrow(() -> new BadRequestException("Account does not have a phone number"));
|
||||
};
|
||||
}
|
||||
}
|
||||
+134
@@ -0,0 +1,134 @@
|
||||
/*
|
||||
* Copyright 2026 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
package org.whispersystems.textsecuregcm.controllers;
|
||||
|
||||
import io.dropwizard.auth.Auth;
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
import io.swagger.v3.oas.annotations.headers.Header;
|
||||
import io.swagger.v3.oas.annotations.media.Content;
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import io.swagger.v3.oas.annotations.responses.ApiResponse;
|
||||
import jakarta.validation.Valid;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
import jakarta.ws.rs.BadRequestException;
|
||||
import jakarta.ws.rs.Consumes;
|
||||
import jakarta.ws.rs.ForbiddenException;
|
||||
import jakarta.ws.rs.POST;
|
||||
import jakarta.ws.rs.Path;
|
||||
import jakarta.ws.rs.Produces;
|
||||
import jakarta.ws.rs.core.MediaType;
|
||||
import jakarta.ws.rs.core.Response;
|
||||
import java.io.IOException;
|
||||
import java.util.Optional;
|
||||
import org.glassfish.jersey.server.ManagedAsync;
|
||||
import org.signal.libsignal.zkgroup.InvalidInputException;
|
||||
import org.signal.libsignal.zkgroup.VerificationFailedException;
|
||||
import org.signal.libsignal.zkgroup.receipts.ReceiptCredentialRequest;
|
||||
import org.signal.libsignal.zkgroup.receipts.ReceiptCredentialResponse;
|
||||
import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
|
||||
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
|
||||
import org.whispersystems.textsecuregcm.mappers.SubscriptionExceptionMapper;
|
||||
import org.whispersystems.textsecuregcm.storage.DynamicConfigurationManager;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.LoginPurchaseManager;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.PaymentProvider;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionInvalidArgumentsException;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionNotFoundException;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionPaymentRequiredException;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionReceiptAlreadyRedeemedException;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionReceiptRequestedForOpenPaymentException;
|
||||
|
||||
@Path("/v1/login-purchase")
|
||||
@io.swagger.v3.oas.annotations.tags.Tag(name = "LoginPurchase")
|
||||
public class LoginPurchaseController {
|
||||
|
||||
private final LoginPurchaseManager loginPurchaseManager;
|
||||
private final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager;
|
||||
|
||||
public LoginPurchaseController(
|
||||
final LoginPurchaseManager loginPurchaseManager,
|
||||
final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager) {
|
||||
this.loginPurchaseManager = loginPurchaseManager;
|
||||
this.dynamicConfigurationManager = dynamicConfigurationManager;
|
||||
}
|
||||
|
||||
public record CreateLoginReceiptCredentialRequest(
|
||||
@NotNull String purchaseIdentifier,
|
||||
@NotNull byte[] receiptCredentialRequest,
|
||||
@NotNull PaymentProvider paymentProvider) {
|
||||
}
|
||||
|
||||
public record CreateLoginReceiptCredentialResponse(byte[] receiptCredentialResponse) {
|
||||
}
|
||||
|
||||
@POST
|
||||
@Path("/receipt_credentials")
|
||||
@Consumes(MediaType.APPLICATION_JSON)
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@Operation(summary = "Create a receipt credential for a completed one-time login purchase",
|
||||
description = """
|
||||
Verify a completed one-time purchase with the payment provider and issue a receipt credential that can be
|
||||
redeemed for a login.
|
||||
|
||||
This endpoint must be called on an unauthenticated connection. Retries for the same purchaseIdentifier MUST
|
||||
use the same receiptCredentialRequest.
|
||||
|
||||
Callers must validate that the generated receipt credential has the
|
||||
following properties:
|
||||
|
||||
- Level == 300 (The login level)
|
||||
- ExpirationTime % 86400 == 0
|
||||
- ExpirationTime == PurchaseTime + (5 * 366 * 86400) +/- (7 * 86400)
|
||||
""")
|
||||
@ApiResponse(responseCode = "200", description = "Successfully created receipt",
|
||||
content = @Content(schema = @Schema(implementation = CreateLoginReceiptCredentialResponse.class)))
|
||||
@ApiResponse(responseCode = "204", description = "The purchase is still pending with the payment provider. The client may retry later.")
|
||||
@ApiResponse(responseCode = "400", description = """
|
||||
Invalid request: malformed request, failed zkgroup verification, unsupported paymentProvider, the provided
|
||||
purchase identifier not for a Signal Login, or login purchases are not currently enabled.
|
||||
""")
|
||||
@ApiResponse(responseCode = "402", description = "The purchase did not complete successfully. The body may include ChargeFailure details.",
|
||||
content = @Content(schema = @Schema(
|
||||
nullable = true,
|
||||
implementation = SubscriptionExceptionMapper.ChargeFailureResponse.class)))
|
||||
@ApiResponse(responseCode = "403", description = "The request was made on an authenticated channel")
|
||||
@ApiResponse(responseCode = "404", description = "The payment provider has no purchase with the provided purchaseIdentifier")
|
||||
@ApiResponse(responseCode = "409", description = "The purchase was already redeemed for a receipt credential, but with a different receipt credential request")
|
||||
@ApiResponse(responseCode = "429", description = "Too many attempts", headers = @Header(
|
||||
name = "Retry-After",
|
||||
description = "If present, a positive integer indicating the number of seconds before a subsequent attempt could succeed"))
|
||||
@ManagedAsync
|
||||
public Response createLoginReceiptCredential(
|
||||
@Auth final Optional<AuthenticatedDevice> authenticatedAccount,
|
||||
@NotNull @Valid final CreateLoginReceiptCredentialRequest request)
|
||||
throws IOException, SubscriptionPaymentRequiredException, SubscriptionInvalidArgumentsException, SubscriptionNotFoundException, RateLimitExceededException, SubscriptionReceiptAlreadyRedeemedException {
|
||||
|
||||
if (!dynamicConfigurationManager.getConfiguration().getLoginPurchaseConfiguration().enabled()) {
|
||||
throw new BadRequestException("login purchases are not enabled");
|
||||
}
|
||||
|
||||
if (authenticatedAccount.isPresent()) {
|
||||
throw new ForbiddenException("must not use authenticated connection for login purchase operations");
|
||||
}
|
||||
|
||||
final ReceiptCredentialRequest receiptCredentialRequest;
|
||||
try {
|
||||
receiptCredentialRequest = new ReceiptCredentialRequest(request.receiptCredentialRequest);
|
||||
} catch (final InvalidInputException e) {
|
||||
throw new BadRequestException("invalid receipt credential request", e);
|
||||
}
|
||||
|
||||
try {
|
||||
final ReceiptCredentialResponse receiptCredentialResponse = loginPurchaseManager.generateReceipt(
|
||||
request.paymentProvider, request.purchaseIdentifier, receiptCredentialRequest);
|
||||
return Response.ok(
|
||||
new CreateLoginReceiptCredentialResponse(receiptCredentialResponse.serialize()))
|
||||
.build();
|
||||
} catch (SubscriptionReceiptRequestedForOpenPaymentException e) {
|
||||
return Response.noContent().build();
|
||||
} catch (VerificationFailedException e) {
|
||||
throw new BadRequestException("receipt credential request failed verification", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
+12
-37
@@ -91,9 +91,9 @@ import org.whispersystems.textsecuregcm.spam.SpamChecker;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.PhoneNumberIdentifiers;
|
||||
import org.whispersystems.textsecuregcm.storage.ReportMessageHelper;
|
||||
import org.whispersystems.textsecuregcm.storage.ReportMessageManager;
|
||||
import org.whispersystems.textsecuregcm.util.HeaderUtils;
|
||||
import org.whispersystems.textsecuregcm.util.Util;
|
||||
|
||||
@SuppressWarnings("OptionalUsedAsFieldOrParameterType")
|
||||
@Path("/v1/messages")
|
||||
@@ -605,7 +605,7 @@ public class MessageController {
|
||||
|
||||
CompletableFuture.allOf(resolvedRecipients.values()
|
||||
.stream()
|
||||
.map(account -> account.getIdentifier(IdentityType.ACI))
|
||||
.map(Account::getAccountIdentifier)
|
||||
.map(accountIdentifier ->
|
||||
rateLimiters.getStoriesLimiter().validateAsync(accountIdentifier).toCompletableFuture())
|
||||
.toList()
|
||||
@@ -731,42 +731,10 @@ public class MessageController {
|
||||
@Path("/report/{source}/{messageGuid}")
|
||||
public Response reportSpamMessage(
|
||||
@Auth AuthenticatedDevice auth,
|
||||
@PathParam("source") String source,
|
||||
@PathParam("source") UUID source,
|
||||
@PathParam("messageGuid") UUID messageGuid,
|
||||
@Nullable SpamReport spamReport,
|
||||
@HeaderParam(HttpHeaders.USER_AGENT) String userAgent
|
||||
) {
|
||||
final Optional<String> sourceNumber;
|
||||
final Optional<UUID> sourceAci;
|
||||
final Optional<UUID> sourcePni;
|
||||
|
||||
if (source.startsWith("+")) {
|
||||
sourceNumber = Optional.of(source);
|
||||
final Optional<Account> maybeAccount = accountsManager.getByE164(source);
|
||||
if (maybeAccount.isPresent()) {
|
||||
sourceAci = maybeAccount.map(Account::getAccountIdentifier);
|
||||
sourcePni = maybeAccount.map(Account::getPhoneNumberIdentifier);
|
||||
} else {
|
||||
sourcePni = Optional.ofNullable(phoneNumberIdentifiers.getPhoneNumberIdentifier(source).join());
|
||||
sourceAci = sourcePni.flatMap(accountsManager::findRecentlyDeletedAccountIdentifier);
|
||||
}
|
||||
} else {
|
||||
sourceAci = Optional.of(UUID.fromString(source));
|
||||
|
||||
final Optional<Account> sourceAccount = accountsManager.getByAccountIdentifier(sourceAci.get());
|
||||
|
||||
if (sourceAccount.isEmpty()) {
|
||||
logger.warn("Could not find source: {}", sourceAci.get());
|
||||
sourcePni = accountsManager.findRecentlyDeletedPhoneNumberIdentifier(sourceAci.get());
|
||||
sourceNumber = sourcePni.flatMap(pni ->
|
||||
Util.getCanonicalNumber(phoneNumberIdentifiers.getPhoneNumber(pni).join()));
|
||||
} else {
|
||||
sourceNumber = sourceAccount.map(Account::getNumber);
|
||||
sourcePni = sourceAccount.map(Account::getPhoneNumberIdentifier);
|
||||
}
|
||||
}
|
||||
|
||||
UUID spamReporterUuid = auth.accountIdentifier();
|
||||
@HeaderParam(HttpHeaders.USER_AGENT) String userAgent) {
|
||||
|
||||
// spam report token is optional, but if provided ensure it is non-empty.
|
||||
final Optional<byte[]> maybeSpamReportToken =
|
||||
@@ -774,7 +742,14 @@ public class MessageController {
|
||||
.flatMap(r -> Optional.ofNullable(r.token()))
|
||||
.filter(t -> t.length > 0);
|
||||
|
||||
reportMessageManager.report(sourceNumber, sourceAci, sourcePni, messageGuid, spamReporterUuid, maybeSpamReportToken, userAgent);
|
||||
ReportMessageHelper.reportMessage(new AciServiceIdentifier(source),
|
||||
new AciServiceIdentifier(auth.accountIdentifier()),
|
||||
messageGuid,
|
||||
maybeSpamReportToken.orElse(null),
|
||||
userAgent,
|
||||
accountsManager,
|
||||
phoneNumberIdentifiers,
|
||||
reportMessageManager);
|
||||
|
||||
return Response.status(Status.ACCEPTED)
|
||||
.build();
|
||||
|
||||
+16
-18
@@ -199,7 +199,7 @@ public class OneTimeDonationController {
|
||||
throw new WebApplicationException(Response.Status.UNAUTHORIZED);
|
||||
}
|
||||
|
||||
validateRequestCurrencyAmount(request, BigDecimal.valueOf(request.amount), stripeManager);
|
||||
validateRequestCurrencyAmount(request, request.amount, stripeManager);
|
||||
final PaymentIntent paymentIntent = stripeManager.createPaymentIntent(request.currency, request.amount,
|
||||
request.level,
|
||||
getClientPlatform(userAgent));
|
||||
@@ -212,7 +212,7 @@ public class OneTimeDonationController {
|
||||
*
|
||||
* @throws BadRequestException indicates validation failed. Inspect {@code response.error} for details
|
||||
*/
|
||||
private void validateRequestCurrencyAmount(final CreateBoostRequest request, final BigDecimal amount,
|
||||
private void validateRequestCurrencyAmount(final CreateBoostRequest request, final long amount,
|
||||
final CustomerAwareSubscriptionPaymentProcessor manager) {
|
||||
|
||||
final Map<String, String> errorBody = switch (OneTimeDonationUtil.validateOneTimeDonationRequest(request.currency,
|
||||
@@ -222,11 +222,9 @@ public class OneTimeDonationController {
|
||||
case OneTimeDonationUtil.OneTimeDonationRequestValidationResult.UnsupportedCurrency _ ->
|
||||
Map.of("error", "unsupported_currency");
|
||||
case OneTimeDonationUtil.OneTimeDonationRequestValidationResult.AmountBelowMinimum(final BigDecimal min) ->
|
||||
Map.of("error", "amount_below_currency_minimum",
|
||||
"minimum", min.toString());
|
||||
Map.of("error", "amount_below_currency_minimum", "minimum", min.toString());
|
||||
case OneTimeDonationUtil.OneTimeDonationRequestValidationResult.AmountAboveSepaLimit(final BigDecimal max) ->
|
||||
Map.of("error", "amount_above_sepa_limit",
|
||||
"maximum", max.toString());
|
||||
Map.of("error", "amount_above_sepa_limit", "maximum", max.toString());
|
||||
case OneTimeDonationUtil.OneTimeDonationRequestValidationResult.Success _ -> Collections.emptyMap();
|
||||
};
|
||||
|
||||
@@ -265,7 +263,7 @@ public class OneTimeDonationController {
|
||||
throw new ForbiddenException("must not use authenticated connection for one-time donation operations");
|
||||
}
|
||||
|
||||
validateRequestCurrencyAmount(request, BigDecimal.valueOf(request.amount), braintreeManager);
|
||||
validateRequestCurrencyAmount(request, request.amount, braintreeManager);
|
||||
final List<Locale> acceptableLanguages =
|
||||
HeaderUtils.getAcceptableLanguagesForRequest(containerRequestContext);
|
||||
final OneTimeDonationUtil.LocalizedPayPalDonationLineItem localizedLineItem = OneTimeDonationUtil.localizePayPalDonationLineItem(
|
||||
@@ -307,7 +305,7 @@ public class OneTimeDonationController {
|
||||
throw new ForbiddenException("must not use authenticated connection for one-time donation operations");
|
||||
}
|
||||
|
||||
validateRequestCurrencyAmount(request, BigDecimal.valueOf(request.amount), braintreeManager);
|
||||
validateRequestCurrencyAmount(request, request.amount, braintreeManager);
|
||||
final BraintreeManager.PayPalChargeSuccessDetails chargeSuccessDetails = braintreeManager.captureOneTimePayment(
|
||||
request.payerId, request.paymentId,
|
||||
request.paymentToken, request.currency, request.amount, request.level, getClientPlatform(userAgent));
|
||||
@@ -350,8 +348,8 @@ public class OneTimeDonationController {
|
||||
}
|
||||
|
||||
final Optional<PaymentDetails> maybePaymentDetails = (switch (request.processor) {
|
||||
case STRIPE -> stripeManager.getPaymentDetails(request.paymentIntentId);
|
||||
case BRAINTREE -> braintreeManager.getPaymentDetails(request.paymentIntentId);
|
||||
case STRIPE -> stripeManager.claimOneTimePurchase(request.paymentIntentId);
|
||||
case BRAINTREE -> braintreeManager.claimOneTimePurchase(request.paymentIntentId);
|
||||
case GOOGLE_PLAY_BILLING -> throw new BadRequestException("cannot use play billing for one-time donations");
|
||||
case APPLE_APP_STORE -> throw new BadRequestException("cannot use app store purchases for one-time donations");
|
||||
});
|
||||
@@ -383,21 +381,21 @@ public class OneTimeDonationController {
|
||||
} catch (final InvalidInputException e) {
|
||||
throw new BadRequestException("invalid receipt credential request", e);
|
||||
}
|
||||
try {
|
||||
issuedReceiptsManager.recordIssuance(paymentDetails.id(), request.processor,
|
||||
receiptCredentialRequest, clock.instant());
|
||||
} catch (WriteConflictException _) {
|
||||
throw new WebApplicationException(Response.Status.CONFLICT);
|
||||
}
|
||||
final Instant paidAt = oneTimeDonationsManager.getPaidAt(paymentDetails.id(), paymentDetails.created());
|
||||
final Instant paidAt = oneTimeDonationsManager.getPaidAt(request.processor, paymentDetails.id(), paymentDetails.created());
|
||||
final Instant expiration = paidAt
|
||||
.plus(levelDetails.levelExpiration())
|
||||
.truncatedTo(ChronoUnit.DAYS)
|
||||
.plus(1, ChronoUnit.DAYS);
|
||||
try {
|
||||
issuedReceiptsManager.recordOneTimeIssuance(paymentDetails.id(), request.processor,
|
||||
receiptCredentialRequest, expiration);
|
||||
} catch (WriteConflictException _) {
|
||||
throw new WebApplicationException(Response.Status.CONFLICT);
|
||||
}
|
||||
final ReceiptCredentialResponse receiptCredentialResponse;
|
||||
try {
|
||||
receiptCredentialResponse = zkReceiptOperations.issueReceiptCredential(
|
||||
receiptCredentialRequest, expiration.getEpochSecond(), levelDetails.level());
|
||||
receiptCredentialRequest, expiration.getEpochSecond(), levelDetails.level().getValue());
|
||||
} catch (final VerificationFailedException e) {
|
||||
throw new BadRequestException("receipt credential request failed verification", e);
|
||||
}
|
||||
|
||||
+43
-22
@@ -50,6 +50,7 @@ import java.util.Optional;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.Executor;
|
||||
import java.util.function.Function;
|
||||
import java.util.function.Supplier;
|
||||
import java.util.stream.Collectors;
|
||||
import javax.annotation.Nullable;
|
||||
import org.glassfish.jersey.server.ManagedAsync;
|
||||
@@ -64,6 +65,7 @@ import org.signal.libsignal.zkgroup.profiles.ExpiringProfileKeyCredentialRespons
|
||||
import org.signal.libsignal.zkgroup.profiles.ProfileKeyCommitment;
|
||||
import org.signal.libsignal.zkgroup.profiles.ProfileKeyCredentialRequest;
|
||||
import org.signal.libsignal.zkgroup.profiles.ServerZkProfileOperations;
|
||||
import org.whispersystems.textsecuregcm.asn.AsnInfoProvider;
|
||||
import org.whispersystems.textsecuregcm.auth.Anonymous;
|
||||
import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
|
||||
import org.whispersystems.textsecuregcm.auth.GroupSendTokenHeader;
|
||||
@@ -80,6 +82,7 @@ import org.whispersystems.textsecuregcm.entities.CreateProfileRequest;
|
||||
import org.whispersystems.textsecuregcm.entities.ExpiringProfileKeyCredentialProfileResponse;
|
||||
import org.whispersystems.textsecuregcm.entities.ProfileAvatarUploadAttributes;
|
||||
import org.whispersystems.textsecuregcm.entities.VersionedProfileResponse;
|
||||
import org.whispersystems.textsecuregcm.filters.RemoteAddressFilter;
|
||||
import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.identity.IdentityType;
|
||||
import org.whispersystems.textsecuregcm.identity.PniServiceIdentifier;
|
||||
@@ -108,6 +111,7 @@ public class ProfileController {
|
||||
private final RateLimiters rateLimiters;
|
||||
private final ProfilesManager profilesManager;
|
||||
private final AccountsManager accountsManager;
|
||||
private final Supplier<AsnInfoProvider> asnInfoProviderSupplier;
|
||||
private final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager;
|
||||
private final ProfileBadgeConverter profileBadgeConverter;
|
||||
private final Map<String, BadgeConfiguration> badgeConfigurationMap;
|
||||
@@ -124,25 +128,27 @@ public class ProfileController {
|
||||
private static final String DUPLICATE_AUTHENTICATION_COUNTER_NAME = name(ProfileController.class, "duplicateAuthentication");
|
||||
|
||||
public ProfileController(
|
||||
Clock clock,
|
||||
RateLimiters rateLimiters,
|
||||
AccountsManager accountsManager,
|
||||
ProfilesManager profilesManager,
|
||||
DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager,
|
||||
ProfileBadgeConverter profileBadgeConverter,
|
||||
BadgesConfiguration badgesConfiguration,
|
||||
PostPolicyGenerator policyGenerator,
|
||||
ServerSecretParams serverSecretParams,
|
||||
ServerZkProfileOperations zkProfileOperations,
|
||||
Executor batchIdentityCheckExecutor) {
|
||||
final Clock clock,
|
||||
final RateLimiters rateLimiters,
|
||||
final AccountsManager accountsManager,
|
||||
final ProfilesManager profilesManager,
|
||||
final Supplier<AsnInfoProvider> asnInfoProviderSupplier,
|
||||
final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager,
|
||||
final ProfileBadgeConverter profileBadgeConverter,
|
||||
final BadgesConfiguration badgesConfiguration,
|
||||
final PostPolicyGenerator policyGenerator,
|
||||
final ServerSecretParams serverSecretParams,
|
||||
final ServerZkProfileOperations zkProfileOperations,
|
||||
final Executor batchIdentityCheckExecutor) {
|
||||
this.clock = clock;
|
||||
this.rateLimiters = rateLimiters;
|
||||
this.accountsManager = accountsManager;
|
||||
this.profilesManager = profilesManager;
|
||||
this.asnInfoProviderSupplier = asnInfoProviderSupplier;
|
||||
this.dynamicConfigurationManager = dynamicConfigurationManager;
|
||||
this.profileBadgeConverter = profileBadgeConverter;
|
||||
this.badgeConfigurationMap = badgesConfiguration.getBadges().stream().collect(Collectors.toMap(
|
||||
BadgeConfiguration::getId, Function.identity()));
|
||||
this.badgeConfigurationMap = badgesConfiguration.getBadges().stream()
|
||||
.collect(Collectors.toMap(BadgeConfiguration::getId, Function.identity()));
|
||||
this.serverSecretParams = serverSecretParams;
|
||||
this.zkProfileOperations = zkProfileOperations;
|
||||
this.policyGenerator = policyGenerator;
|
||||
@@ -161,10 +167,12 @@ public class ProfileController {
|
||||
description = "If the request changed the avatar, the response body contains an upload form.")))
|
||||
@ApiResponse(responseCode = "400", description = "Invalid create profile request.")
|
||||
@ApiResponse(responseCode = "401", description = "Account authentication check failed.")
|
||||
@ApiResponse(responseCode = "403", description = "The request contained a payment address, but payments are not supported in the region of the account’s phone number.")
|
||||
@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")
|
||||
public Response setProfile(@Auth AuthenticatedDevice auth, @NotNull @Valid CreateProfileRequest request) {
|
||||
public Response setProfile(@Auth AuthenticatedDevice auth,
|
||||
@NotNull @Valid CreateProfileRequest request,
|
||||
@Context final ContainerRequestContext requestContext) {
|
||||
|
||||
final Account account = accountsManager.getByAccountIdentifier(auth.accountIdentifier())
|
||||
.orElseThrow(() -> new WebApplicationException(Response.Status.UNAUTHORIZED));
|
||||
@@ -176,7 +184,12 @@ public class ProfileController {
|
||||
final Optional<VersionedProfileV1> currentProfile =
|
||||
profilesManager.getV1(auth.accountIdentifier(), request.version());
|
||||
|
||||
if (request.paymentAddress() != null && request.paymentAddress().length != 0 && ProfileHelper.isPaymentAddressUpdateForbidden(account, Optional.empty(), currentProfile, dynamicConfigurationManager)) {
|
||||
final String remoteAddress = (String) requestContext.getProperty(RemoteAddressFilter.REMOTE_ADDRESS_ATTRIBUTE_NAME);
|
||||
|
||||
if (request.paymentAddress() != null &&
|
||||
request.paymentAddress().length != 0 &&
|
||||
ProfileHelper.isPaymentAddressUpdateForbidden(account, Optional.empty(), currentProfile, remoteAddress, asnInfoProviderSupplier.get(), dynamicConfigurationManager)) {
|
||||
|
||||
return Response.status(Response.Status.FORBIDDEN).build();
|
||||
}
|
||||
|
||||
@@ -198,7 +211,7 @@ public class ProfileController {
|
||||
currentAvatar.ifPresent(profilesManager::deleteAvatar);
|
||||
}
|
||||
|
||||
accountsManager.update(account.getIdentifier(IdentityType.ACI), a -> {
|
||||
accountsManager.update(account.getAccountIdentifier(), a -> {
|
||||
|
||||
final List<AccountBadge> updatedBadges = request.badges()
|
||||
.map(badges -> ProfileHelper.mergeBadgeIdsWithExistingAccountBadges(clock, badgeConfigurationMap, badges, a.getBadges()))
|
||||
@@ -401,11 +414,17 @@ public class ProfileController {
|
||||
final Optional<Account> maybeAccount = accountsManager.getByServiceIdentifier(identifier);
|
||||
|
||||
maybeAccount.ifPresent(account -> {
|
||||
final IdentityKey identityKey = account.getIdentityKey(identifier.identityType());
|
||||
if (identityKey == null) {
|
||||
final Optional<IdentityKey> maybeIdentityKey = switch (identifier.identityType()) {
|
||||
case ACI -> Optional.of(account.getAccountIdentityKey());
|
||||
case PNI -> account.getPhoneNumberIdentityKey();
|
||||
};
|
||||
|
||||
if (maybeIdentityKey.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
|
||||
final IdentityKey identityKey = maybeIdentityKey.get();
|
||||
|
||||
md.reset();
|
||||
byte[] digest = md.digest(identityKey.serialize());
|
||||
byte[] fingerprint = Util.truncate(digest, 4);
|
||||
@@ -490,7 +509,7 @@ public class ProfileController {
|
||||
final boolean isSelf,
|
||||
final ContainerRequestContext containerRequestContext) {
|
||||
|
||||
return new BaseProfileResponse(account.getIdentityKey(IdentityType.ACI),
|
||||
return new BaseProfileResponse(account.getAccountIdentityKey(),
|
||||
account.getUnidentifiedAccessKey().map(UnidentifiedAccessChecksum::generateFor).orElse(null),
|
||||
account.isUnrestrictedUnidentifiedAccess(),
|
||||
getAccountCapabilities(account),
|
||||
@@ -502,12 +521,14 @@ public class ProfileController {
|
||||
}
|
||||
|
||||
private BaseProfileResponse buildBaseProfileResponseForPhoneNumberIdentity(final Account account) {
|
||||
return new BaseProfileResponse(account.getIdentityKey(IdentityType.PNI),
|
||||
return new BaseProfileResponse(account.getPhoneNumberIdentityKey()
|
||||
.orElseThrow(() -> new IllegalStateException("Account retrieved by PNI does not have PNI identity key")),
|
||||
null,
|
||||
false,
|
||||
getAccountCapabilities(account),
|
||||
Collections.emptyList(),
|
||||
new PniServiceIdentifier(account.getPhoneNumberIdentifier()));
|
||||
new PniServiceIdentifier(account.getPhoneNumberIdentifier()
|
||||
.orElseThrow(() -> new IllegalStateException("Account retrieved by PNI does not have PNI"))));
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
+333
-17
@@ -13,6 +13,8 @@ import io.micrometer.core.instrument.Metrics;
|
||||
import io.micrometer.core.instrument.Tag;
|
||||
import io.micrometer.core.instrument.Tags;
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
import io.swagger.v3.oas.annotations.Parameter;
|
||||
import io.swagger.v3.oas.annotations.enums.ParameterIn;
|
||||
import io.swagger.v3.oas.annotations.headers.Header;
|
||||
import io.swagger.v3.oas.annotations.media.Content;
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
@@ -34,21 +36,30 @@ import jakarta.ws.rs.core.Context;
|
||||
import jakarta.ws.rs.core.MediaType;
|
||||
import jakarta.ws.rs.core.Response;
|
||||
import java.io.IOException;
|
||||
import java.time.Clock;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import javax.annotation.Nullable;
|
||||
import org.apache.commons.lang3.ArrayUtils;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.signal.libsignal.zkgroup.InvalidInputException;
|
||||
import org.signal.libsignal.zkgroup.VerificationFailedException;
|
||||
import org.signal.libsignal.zkgroup.receipts.ReceiptCredentialPresentation;
|
||||
import org.signal.libsignal.zkgroup.receipts.ServerZkReceiptOperations;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.auth.BasicAuthorizationHeader;
|
||||
import org.whispersystems.textsecuregcm.auth.InvalidRegistrationSessionException;
|
||||
import org.whispersystems.textsecuregcm.auth.MfaFailureException;
|
||||
import org.whispersystems.textsecuregcm.auth.PhoneVerificationTokenManager;
|
||||
import org.whispersystems.textsecuregcm.auth.RecoveryPasswordVerificationFailedException;
|
||||
import org.whispersystems.textsecuregcm.auth.RegistrationLockFailureException;
|
||||
import org.whispersystems.textsecuregcm.auth.RegistrationLockVerificationManager;
|
||||
import org.whispersystems.textsecuregcm.auth.UnverifiedRegistrationSessionException;
|
||||
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
|
||||
import org.whispersystems.textsecuregcm.entities.AccountCreationResponse;
|
||||
import org.whispersystems.textsecuregcm.entities.AccountIdentityResponse;
|
||||
import org.whispersystems.textsecuregcm.entities.PhoneVerificationRequest;
|
||||
@@ -56,12 +67,21 @@ import org.whispersystems.textsecuregcm.entities.RegistrationLockFailure;
|
||||
import org.whispersystems.textsecuregcm.entities.RegistrationRequest;
|
||||
import org.whispersystems.textsecuregcm.filters.RemoteAddressFilter;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimiters;
|
||||
import org.whispersystems.textsecuregcm.mappers.MfaFailureExceptionMapper;
|
||||
import org.whispersystems.textsecuregcm.metrics.UserAgentTagUtil;
|
||||
import org.whispersystems.textsecuregcm.spam.RegistrationFraudChecker;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.AnnotatedTotpKey;
|
||||
import org.whispersystems.textsecuregcm.storage.AnnotatedWebAuthnCredential;
|
||||
import org.whispersystems.textsecuregcm.storage.DeviceCapability;
|
||||
import org.whispersystems.textsecuregcm.storage.DeviceIdentityInfo;
|
||||
import org.whispersystems.textsecuregcm.storage.DeviceSpec;
|
||||
import org.whispersystems.textsecuregcm.storage.DynamicConfigurationManager;
|
||||
import org.whispersystems.textsecuregcm.storage.PhoneNumberRecoveryPasswordsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.ReceiptAlreadyRedeemedException;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.ReceiptCredentialPresentationFactory;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.ReceiptLevel;
|
||||
import org.whispersystems.textsecuregcm.util.HeaderUtils;
|
||||
import org.whispersystems.textsecuregcm.util.Util;
|
||||
|
||||
@@ -84,6 +104,10 @@ public class RegistrationController {
|
||||
private final RegistrationLockVerificationManager registrationLockVerificationManager;
|
||||
private final RateLimiters rateLimiters;
|
||||
private final RegistrationFraudChecker registrationFraudChecker;
|
||||
private final ReceiptCredentialPresentationFactory receiptCredentialPresentationFactory;
|
||||
private final ServerZkReceiptOperations serverZkReceiptOperations;
|
||||
private final Clock clock;
|
||||
private final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager;
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(RegistrationController.class);
|
||||
|
||||
@@ -91,13 +115,21 @@ public class RegistrationController {
|
||||
final PhoneVerificationTokenManager phoneVerificationTokenManager,
|
||||
final RegistrationLockVerificationManager registrationLockVerificationManager,
|
||||
final RateLimiters rateLimiters,
|
||||
final RegistrationFraudChecker registrationFraudChecker) {
|
||||
final RegistrationFraudChecker registrationFraudChecker,
|
||||
final ReceiptCredentialPresentationFactory receiptCredentialPresentationFactory,
|
||||
final ServerZkReceiptOperations serverZkReceiptOperations,
|
||||
final Clock clock,
|
||||
final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager) {
|
||||
|
||||
this.accounts = accounts;
|
||||
this.phoneVerificationTokenManager = phoneVerificationTokenManager;
|
||||
this.registrationLockVerificationManager = registrationLockVerificationManager;
|
||||
this.rateLimiters = rateLimiters;
|
||||
this.registrationFraudChecker = registrationFraudChecker;
|
||||
this.receiptCredentialPresentationFactory = receiptCredentialPresentationFactory;
|
||||
this.serverZkReceiptOperations = serverZkReceiptOperations;
|
||||
this.clock = clock;
|
||||
this.dynamicConfigurationManager = dynamicConfigurationManager;
|
||||
}
|
||||
|
||||
@POST
|
||||
@@ -112,7 +144,8 @@ public class RegistrationController {
|
||||
3. success \n
|
||||
""")
|
||||
@ApiResponse(responseCode = "200", description = "Account creation succeeded", useReturnTypeSchema = true)
|
||||
@ApiResponse(responseCode = "401", description = "The session identified in the request is not verified")
|
||||
@ApiResponse(responseCode = "400", description = "Invalid session ID or receipt credential presentation")
|
||||
@ApiResponse(responseCode = "401", description = "The session identified in the request is not verified, or the receipt credential presented fails verification, is expired, or is already redeemed")
|
||||
@ApiResponse(responseCode = "403", description = "Verification failed for the provided Registration Recovery Password")
|
||||
@ApiResponse(responseCode = "409", description = "The caller has not explicitly elected to skip transferring data from another device, but a device transfer is technically possible")
|
||||
@ApiResponse(responseCode = "422", description = "The request did not pass validation")
|
||||
@@ -120,17 +153,34 @@ public class RegistrationController {
|
||||
@ApiResponse(responseCode = "429", description = "Too many attempts", headers = @Header(
|
||||
name = "Retry-After",
|
||||
description = "If present, an positive integer indicating the number of seconds before a subsequent attempt could succeed"))
|
||||
@ApiResponse(responseCode = "441",
|
||||
description = """
|
||||
Second factor authentication failed. Either the account has one or more factors configured, and the request’s
|
||||
factor was incorrect or absent, or the account has no factors, but the request included a factor.
|
||||
""",
|
||||
content = @Content(schema = @Schema(implementation = MfaFailureExceptionMapper.MfaFailureResponse.class)))
|
||||
@ApiResponse(responseCode = "499", description = "Client must support post-quantum ratchet")
|
||||
public AccountCreationResponse register(
|
||||
@Parameter(
|
||||
in = ParameterIn.HEADER,
|
||||
name = HttpHeaders.AUTHORIZATION,
|
||||
description = """
|
||||
The basic auth header. For accounts with a phone number, the username must be the e164-formatted number that
|
||||
is being registered. For accounts without a phone number, the username is ignored on a fresh registration
|
||||
(it must be present, however, so any string that can't be parsed as an e164-formatted phone number or UUID
|
||||
is acceptable; "__no_number__" is recommended). For account recovery (re-registration) by ACI, it must be
|
||||
set to the ACI of the account being recovered. In all cases, the password is the password to be used for
|
||||
primary device authentication.
|
||||
""",
|
||||
required = true,
|
||||
schema = @Schema(type = "string")
|
||||
)
|
||||
@HeaderParam(HttpHeaders.AUTHORIZATION) @NotNull final BasicAuthorizationHeader authorizationHeader,
|
||||
@HeaderParam(HeaderUtils.X_SIGNAL_AGENT) final String signalAgent,
|
||||
@HeaderParam(HttpHeaders.USER_AGENT) final String userAgent,
|
||||
@NotNull @Valid final RegistrationRequest registrationRequest,
|
||||
@Context final ContainerRequestContext requestContext)
|
||||
throws RateLimitExceededException, InterruptedException, RegistrationLockFailureException {
|
||||
|
||||
final String number = authorizationHeader.getUsername();
|
||||
final String password = authorizationHeader.getPassword();
|
||||
throws RateLimitExceededException, InterruptedException, RegistrationLockFailureException, MfaFailureException {
|
||||
|
||||
if (!registrationRequest.isEverySignedKeyValid(userAgent)) {
|
||||
throw new WebApplicationException("Invalid signature", 422);
|
||||
@@ -143,7 +193,47 @@ public class RegistrationController {
|
||||
throw new WebApplicationException("Missing required device capability", 499);
|
||||
}
|
||||
|
||||
rateLimiters.getRegistrationLimiter().validate(number);
|
||||
final AccountCreationResponse response;
|
||||
|
||||
if (registrationRequest.receiptCredentialPresentation() != null && registrationRequest.receiptCredentialPresentation().length > 0) {
|
||||
// A receipt credential presentation will only be present if the caller is trying to register a new account
|
||||
// without a phone number, in which case we can (and must) ignore the "username" in the authentication header.
|
||||
response = registerAccountWithoutNumber(authorizationHeader.getPassword(), registrationRequest, userAgent, signalAgent);
|
||||
} else {
|
||||
// The caller is either trying to register a new account with a phone number or recover an account by ACI. Either
|
||||
// way, the "username" from the auth header is meaningful.
|
||||
@Nullable UUID recoveredAccountIdentifier;
|
||||
|
||||
try {
|
||||
recoveredAccountIdentifier = UUID.fromString(authorizationHeader.getUsername());
|
||||
} catch (final IllegalArgumentException _) {
|
||||
// The provided username is either a phone number or a nonsense string (for registration without a phone number)
|
||||
recoveredAccountIdentifier = null;
|
||||
}
|
||||
|
||||
if (recoveredAccountIdentifier != null) {
|
||||
response = recoverAccount(recoveredAccountIdentifier, authorizationHeader.getPassword(), registrationRequest, userAgent, signalAgent);
|
||||
} else {
|
||||
response = registerAccountWithNumber(authorizationHeader.getUsername(), authorizationHeader.getPassword(), registrationRequest, requestContext, userAgent, signalAgent);
|
||||
}
|
||||
}
|
||||
|
||||
return response;
|
||||
}
|
||||
|
||||
private AccountCreationResponse registerAccountWithNumber(
|
||||
final String number,
|
||||
final String password,
|
||||
final RegistrationRequest registrationRequest,
|
||||
final ContainerRequestContext requestContext,
|
||||
final String userAgent,
|
||||
final String signalAgent)
|
||||
throws RateLimitExceededException, InterruptedException, RegistrationLockFailureException, MfaFailureException {
|
||||
|
||||
if (registrationRequest.pniIdentityKey() == null) {
|
||||
// RegistrationRequest checks that either all phone number-associated information is present or all is absent
|
||||
throw new WebApplicationException("PNI keys and registration ID must be provided", 422);
|
||||
}
|
||||
|
||||
final PhoneVerificationRequest.VerificationType verificationType;
|
||||
try {
|
||||
@@ -164,9 +254,11 @@ public class RegistrationController {
|
||||
throw new ForbiddenException("recovery password could not be verified");
|
||||
}
|
||||
|
||||
rateLimiters.getRegistrationLimiter().validate(number);
|
||||
|
||||
// There can be at most one existing account for a set of numbers in the same equivalence class, so it's sufficient
|
||||
// to find the first one.
|
||||
final Optional<Account> existingAccount = Util.getAlternateForms(number)
|
||||
Optional<Account> existingAccount = Util.getAlternateForms(number)
|
||||
.stream()
|
||||
.map(accounts::getByE164)
|
||||
.filter(Optional::isPresent)
|
||||
@@ -186,14 +278,16 @@ public class RegistrationController {
|
||||
}
|
||||
|
||||
if (existingAccount.isPresent()) {
|
||||
assert existingAccount.get().getNumber().isPresent();
|
||||
registrationLockVerificationManager.verifyRegistrationLock(existingAccount.get(),
|
||||
registrationRequest.accountAttributes().getRegistrationLock(),
|
||||
userAgent, RegistrationLockVerificationManager.Flow.REGISTRATION, verificationType);
|
||||
|
||||
existingAccount = Optional.of(checkMfa(existingAccount.get(), registrationRequest.webAuthnResponse(), registrationRequest.totp()));
|
||||
}
|
||||
|
||||
final Account account = accounts.create(number,
|
||||
registrationRequest.accountAttributes(),
|
||||
existingAccount.map(Account::getBadges).orElseGet(ArrayList::new),
|
||||
registrationRequest.aciIdentityKey(),
|
||||
registrationRequest.pniIdentityKey(),
|
||||
new DeviceSpec(
|
||||
@@ -201,15 +295,18 @@ public class RegistrationController {
|
||||
password,
|
||||
signalAgent,
|
||||
registrationRequest.accountAttributes().getCapabilities(),
|
||||
registrationRequest.accountAttributes().getRegistrationId(),
|
||||
registrationRequest.accountAttributes().getPhoneNumberIdentityRegistrationId(),
|
||||
new DeviceIdentityInfo(
|
||||
registrationRequest.accountAttributes().getRegistrationId(),
|
||||
registrationRequest.deviceActivationRequest().aciSignedPreKey(),
|
||||
registrationRequest.deviceActivationRequest().aciPqLastResortPreKey()),
|
||||
Optional.of(new DeviceIdentityInfo(
|
||||
registrationRequest.accountAttributes().getPhoneNumberIdentityRegistrationId().get(),
|
||||
// We've already validated the presence of PNI keys by this point
|
||||
registrationRequest.deviceActivationRequest().pniSignedPreKey().get(),
|
||||
registrationRequest.deviceActivationRequest().pniPqLastResortPreKey().get())),
|
||||
registrationRequest.accountAttributes().getFetchesMessages(),
|
||||
registrationRequest.deviceActivationRequest().apnToken(),
|
||||
registrationRequest.deviceActivationRequest().gcmToken(),
|
||||
registrationRequest.deviceActivationRequest().aciSignedPreKey(),
|
||||
registrationRequest.deviceActivationRequest().pniSignedPreKey(),
|
||||
registrationRequest.deviceActivationRequest().aciPqLastResortPreKey(),
|
||||
registrationRequest.deviceActivationRequest().pniPqLastResortPreKey()),
|
||||
registrationRequest.deviceActivationRequest().gcmToken()),
|
||||
userAgent);
|
||||
|
||||
if (verificationType == PhoneVerificationRequest.VerificationType.SESSION) {
|
||||
@@ -236,4 +333,223 @@ public class RegistrationController {
|
||||
return new AccountCreationResponse(identityResponse, existingAccount.isPresent());
|
||||
}
|
||||
|
||||
private AccountCreationResponse registerAccountWithoutNumber(
|
||||
final String password,
|
||||
final RegistrationRequest registrationRequest,
|
||||
final String userAgent,
|
||||
final String signalAgent) {
|
||||
|
||||
if (!dynamicConfigurationManager.getConfiguration().getLoginPurchaseConfiguration().enabled()) {
|
||||
throw new BadRequestException("login purchases are not enabled");
|
||||
}
|
||||
|
||||
registrationRequest.accountAttributes().recoveryPassword()
|
||||
.filter(ArrayUtils::isNotEmpty)
|
||||
.orElseThrow(() -> new WebApplicationException("Account recovery password is required", 422));
|
||||
|
||||
final ReceiptCredentialPresentation receiptCredentialPresentation;
|
||||
try {
|
||||
receiptCredentialPresentation = receiptCredentialPresentationFactory
|
||||
.build(registrationRequest.receiptCredentialPresentation());
|
||||
} catch (InvalidInputException _) {
|
||||
throw new BadRequestException("Invalid receipt credential presentation");
|
||||
}
|
||||
try {
|
||||
serverZkReceiptOperations.verifyReceiptCredentialPresentation(receiptCredentialPresentation);
|
||||
} catch (VerificationFailedException _) {
|
||||
throw new NotAuthorizedException("Receipt credential presentation verification failed");
|
||||
}
|
||||
|
||||
final Instant receiptExpiration = Instant.ofEpochSecond(receiptCredentialPresentation.getReceiptExpirationTime());
|
||||
if (clock.instant().isAfter(receiptExpiration)) {
|
||||
throw new NotAuthorizedException("Receipt is already expired");
|
||||
}
|
||||
|
||||
final long receiptLevel = receiptCredentialPresentation.getReceiptLevel();
|
||||
if (receiptLevel != ReceiptLevel.LOGIN.getValue()) {
|
||||
throw new BadRequestException("Invalid receipt level");
|
||||
}
|
||||
|
||||
try {
|
||||
final Account account = accounts.create(
|
||||
registrationRequest.accountAttributes(),
|
||||
registrationRequest.aciIdentityKey(),
|
||||
receiptCredentialPresentation,
|
||||
new DeviceSpec(
|
||||
registrationRequest.accountAttributes().getName(),
|
||||
password,
|
||||
signalAgent,
|
||||
registrationRequest.accountAttributes().getCapabilities(),
|
||||
new DeviceIdentityInfo(registrationRequest.accountAttributes().getRegistrationId(), registrationRequest.deviceActivationRequest()
|
||||
.aciSignedPreKey(), registrationRequest.deviceActivationRequest().aciPqLastResortPreKey()),
|
||||
Optional.empty(),
|
||||
registrationRequest.accountAttributes().getFetchesMessages(),
|
||||
registrationRequest.deviceActivationRequest().apnToken(),
|
||||
registrationRequest.deviceActivationRequest().gcmToken()),
|
||||
userAgent);
|
||||
|
||||
Metrics.counter(ACCOUNT_CREATED_COUNTER_NAME, Tags.of(UserAgentTagUtil.getPlatformTag(userAgent),
|
||||
Tag.of(VERIFICATION_TYPE_TAG_NAME, registrationRequest.verificationType().name())))
|
||||
.increment();
|
||||
|
||||
final AccountIdentityResponse accountIdentityResponse = new AccountIdentityResponseBuilder(account).build();
|
||||
return new AccountCreationResponse(accountIdentityResponse, false);
|
||||
} catch (ReceiptAlreadyRedeemedException _) {
|
||||
throw new NotAuthorizedException("Receipt already redeemed");
|
||||
}
|
||||
}
|
||||
|
||||
private AccountCreationResponse recoverAccount(final UUID accountIdentifier,
|
||||
final String password,
|
||||
final RegistrationRequest registrationRequest,
|
||||
final String userAgent,
|
||||
final String signalAgent) throws RegistrationLockFailureException, RateLimitExceededException, MfaFailureException {
|
||||
|
||||
if (!dynamicConfigurationManager.getConfiguration().getLoginPurchaseConfiguration().enabled()) {
|
||||
throw new BadRequestException("login purchases are not enabled");
|
||||
}
|
||||
|
||||
if (ArrayUtils.isEmpty(registrationRequest.recoveryPassword())) {
|
||||
throw new BadRequestException("Recovery password required for authentication when recovering an account by identifier");
|
||||
}
|
||||
|
||||
if (registrationRequest.accountAttributes().recoveryPassword().isEmpty()) {
|
||||
throw new BadRequestException("Recovery password required for for storage when recovering an account by identifier");
|
||||
}
|
||||
|
||||
if (registrationRequest.pniIdentityKey() == null) {
|
||||
throw new BadRequestException("Must specify a PNI-associated identity key when recovering an account by identifier");
|
||||
}
|
||||
|
||||
Account existingAccount = accounts.getByAccountIdentifier(accountIdentifier)
|
||||
.orElseThrow(ForbiddenException::new);
|
||||
|
||||
final boolean passwordVerified = existingAccount.getAccountRecoveryPassword()
|
||||
.map(saltedRecoveryPasswordHash -> PhoneNumberRecoveryPasswordsManager.verify(saltedRecoveryPasswordHash, registrationRequest.recoveryPassword()))
|
||||
.orElse(false);
|
||||
|
||||
if (!passwordVerified) {
|
||||
throw new ForbiddenException();
|
||||
}
|
||||
|
||||
existingAccount = checkMfa(existingAccount, registrationRequest.webAuthnResponse(), registrationRequest.totp());
|
||||
|
||||
if (!registrationRequest.skipDeviceTransfer() && existingAccount.hasCapability(DeviceCapability.TRANSFER)) {
|
||||
// If a device transfer is possible, clients must explicitly opt out of a transfer (i.e. after prompting the user)
|
||||
// before we'll let them recover an account and start "from scratch"
|
||||
throw new WebApplicationException(Response.status(409, "device transfer available").build());
|
||||
}
|
||||
|
||||
final Account reclaimedAccount = existingAccount.getNumber().isPresent()
|
||||
? recoverAccountWithPhoneNumber(existingAccount, registrationRequest, password, userAgent, signalAgent)
|
||||
: recoverAccountWithoutPhoneNumber(existingAccount, registrationRequest, password, userAgent, signalAgent);
|
||||
|
||||
Metrics.counter(ACCOUNT_CREATED_COUNTER_NAME, Tags.of(UserAgentTagUtil.getPlatformTag(userAgent),
|
||||
Tag.of(VERIFICATION_TYPE_TAG_NAME, registrationRequest.verificationType().name())))
|
||||
.increment();
|
||||
|
||||
return new AccountCreationResponse(new AccountIdentityResponseBuilder(reclaimedAccount)
|
||||
.storageCapable(existingAccount.hasCapability(DeviceCapability.STORAGE))
|
||||
.build(), true);
|
||||
}
|
||||
|
||||
private Account recoverAccountWithoutPhoneNumber(final Account existingAccount,
|
||||
final RegistrationRequest registrationRequest,
|
||||
final String password,
|
||||
final String userAgent,
|
||||
final String signalAgent) {
|
||||
|
||||
return accounts.recover(existingAccount,
|
||||
registrationRequest.accountAttributes(),
|
||||
registrationRequest.aciIdentityKey(),
|
||||
Optional.empty(),
|
||||
new DeviceSpec(
|
||||
registrationRequest.accountAttributes().getName(),
|
||||
password,
|
||||
signalAgent,
|
||||
registrationRequest.accountAttributes().getCapabilities(),
|
||||
new DeviceIdentityInfo(
|
||||
registrationRequest.accountAttributes().getRegistrationId(),
|
||||
registrationRequest.deviceActivationRequest().aciSignedPreKey(),
|
||||
registrationRequest.deviceActivationRequest().aciPqLastResortPreKey()),
|
||||
Optional.empty(),
|
||||
registrationRequest.accountAttributes().getFetchesMessages(),
|
||||
registrationRequest.deviceActivationRequest().apnToken(),
|
||||
registrationRequest.deviceActivationRequest().gcmToken()),
|
||||
userAgent);
|
||||
}
|
||||
|
||||
private Account recoverAccountWithPhoneNumber(final Account existingAccount,
|
||||
final RegistrationRequest registrationRequest,
|
||||
final String password,
|
||||
final String userAgent,
|
||||
final String signalAgent) throws RegistrationLockFailureException, RateLimitExceededException {
|
||||
|
||||
registrationLockVerificationManager.verifyRegistrationLock(existingAccount,
|
||||
registrationRequest.accountAttributes().getRegistrationLock(),
|
||||
userAgent,
|
||||
RegistrationLockVerificationManager.Flow.REGISTRATION,
|
||||
PhoneVerificationRequest.VerificationType.RECOVERY_PASSWORD);
|
||||
|
||||
assert registrationRequest.pniIdentityKey() != null;
|
||||
|
||||
return accounts.recover(existingAccount,
|
||||
registrationRequest.accountAttributes(),
|
||||
registrationRequest.aciIdentityKey(),
|
||||
Optional.of(registrationRequest.pniIdentityKey()),
|
||||
new DeviceSpec(
|
||||
registrationRequest.accountAttributes().getName(),
|
||||
password,
|
||||
signalAgent,
|
||||
registrationRequest.accountAttributes().getCapabilities(),
|
||||
new DeviceIdentityInfo(
|
||||
registrationRequest.accountAttributes().getRegistrationId(),
|
||||
registrationRequest.deviceActivationRequest().aciSignedPreKey(),
|
||||
registrationRequest.deviceActivationRequest().aciPqLastResortPreKey()),
|
||||
Optional.of(new DeviceIdentityInfo(
|
||||
registrationRequest.accountAttributes().getPhoneNumberIdentityRegistrationId().get(),
|
||||
// We've already validated the presence of PNI keys by this point
|
||||
registrationRequest.deviceActivationRequest().pniSignedPreKey().orElseThrow(),
|
||||
registrationRequest.deviceActivationRequest().pniPqLastResortPreKey().orElseThrow())),
|
||||
registrationRequest.accountAttributes().getFetchesMessages(),
|
||||
registrationRequest.deviceActivationRequest().apnToken(),
|
||||
registrationRequest.deviceActivationRequest().gcmToken()),
|
||||
userAgent);
|
||||
}
|
||||
|
||||
/// @return the maybe-updated [Account] reference. Callers must use it to avoid stale reads and updates.
|
||||
private Account checkMfa(final Account account, @Nullable final String webAuthn, @Nullable final Integer totp) throws RateLimitExceededException, MfaFailureException {
|
||||
|
||||
final boolean hasTotp = account.getMfaKeys().values().stream().anyMatch(k -> k instanceof AnnotatedTotpKey);
|
||||
final boolean hasWebAuthn = account.getMfaKeys().values().stream().anyMatch(k -> k instanceof AnnotatedWebAuthnCredential);
|
||||
|
||||
if (!hasTotp && !hasWebAuthn) {
|
||||
if (totp != null || webAuthn != null) {
|
||||
throw new MfaFailureException(null, false);
|
||||
}
|
||||
return account;
|
||||
}
|
||||
|
||||
if (totp != null || webAuthn != null) {
|
||||
rateLimiters.getCheckMfaLimiter().validate(account.getAccountIdentifier());
|
||||
}
|
||||
|
||||
final Optional<Account> updatedAccount;
|
||||
if (hasWebAuthn && webAuthn != null) {
|
||||
updatedAccount = accounts.verifyWebAuthnAuthentication(account, webAuthn);
|
||||
} else {
|
||||
updatedAccount = Optional.empty();
|
||||
}
|
||||
|
||||
final boolean webAuthnVerified = updatedAccount.isPresent();
|
||||
|
||||
final boolean totpVerified = hasTotp && totp != null
|
||||
&& accounts.verifyTotp(account, clock.instant(), totp);
|
||||
|
||||
if (webAuthnVerified || totpVerified) {
|
||||
return updatedAccount.orElse(account);
|
||||
}
|
||||
|
||||
throw new MfaFailureException(accounts.startWebAuthnAuthentication(account).orElse(null), hasTotp);
|
||||
}
|
||||
}
|
||||
+26
-4
@@ -49,7 +49,6 @@ import jakarta.ws.rs.core.MediaType;
|
||||
import jakarta.ws.rs.core.Response;
|
||||
import jakarta.ws.rs.core.Response.Status;
|
||||
import java.io.IOException;
|
||||
import java.io.UncheckedIOException;
|
||||
import java.math.BigDecimal;
|
||||
import java.time.Clock;
|
||||
import java.time.Instant;
|
||||
@@ -66,6 +65,7 @@ import org.signal.libsignal.zkgroup.receipts.ReceiptCredentialResponse;
|
||||
import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
|
||||
import org.whispersystems.textsecuregcm.auth.DonationPermitHeader;
|
||||
import org.whispersystems.textsecuregcm.badges.BadgeTranslator;
|
||||
import org.whispersystems.textsecuregcm.configuration.LoginPurchaseConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.OneTimeDonationConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.SubscriptionConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.SubscriptionLevelConfiguration;
|
||||
@@ -91,6 +91,7 @@ import org.whispersystems.textsecuregcm.subscriptions.LevelConfiguration;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.PaymentMethod;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.PaymentProvider;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.ProcessorCustomer;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.ReceiptLevel;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.StripeManager;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionException;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionInvalidArgumentsException;
|
||||
@@ -106,6 +107,7 @@ public class SubscriptionController {
|
||||
private final Clock clock;
|
||||
private final SubscriptionConfiguration subscriptionConfiguration;
|
||||
private final OneTimeDonationConfiguration oneTimeDonationConfiguration;
|
||||
private final LoginPurchaseConfiguration loginPurchaseConfiguration;
|
||||
private final SubscriptionManager subscriptionManager;
|
||||
private final StripeManager stripeManager;
|
||||
private final BraintreeManager braintreeManager;
|
||||
@@ -124,6 +126,7 @@ public class SubscriptionController {
|
||||
Clock clock,
|
||||
SubscriptionConfiguration subscriptionConfiguration,
|
||||
OneTimeDonationConfiguration oneTimeDonationConfiguration,
|
||||
LoginPurchaseConfiguration loginPurchaseConfiguration,
|
||||
SubscriptionManager subscriptionManager,
|
||||
StripeManager stripeManager,
|
||||
BraintreeManager braintreeManager,
|
||||
@@ -137,6 +140,7 @@ public class SubscriptionController {
|
||||
this.clock = Objects.requireNonNull(clock);
|
||||
this.subscriptionConfiguration = Objects.requireNonNull(subscriptionConfiguration);
|
||||
this.oneTimeDonationConfiguration = Objects.requireNonNull(oneTimeDonationConfiguration);
|
||||
this.loginPurchaseConfiguration = Objects.requireNonNull(loginPurchaseConfiguration);
|
||||
this.stripeManager = Objects.requireNonNull(stripeManager);
|
||||
this.braintreeManager = Objects.requireNonNull(braintreeManager);
|
||||
this.googlePlayBillingManager = Objects.requireNonNull(googlePlayBillingManager);
|
||||
@@ -167,6 +171,10 @@ public class SubscriptionController {
|
||||
buildDonationLevelsConfiguration(subscriptionConfiguration, oneTimeDonationConfiguration, badgeTranslator,
|
||||
acceptableLanguages),
|
||||
new BackupConfiguration(backupLevels, subscriptionConfiguration.getbackupFreeTierMediaDuration().toDays()),
|
||||
new LoginConfiguration(ReceiptLevel.LOGIN.getValue(),
|
||||
loginPurchaseConfiguration.playProductId(),
|
||||
loginPurchaseConfiguration.playOptionId(),
|
||||
loginPurchaseConfiguration.appStoreProductId()),
|
||||
oneTimeDonationConfiguration.sepaMaximumEuros());
|
||||
}
|
||||
|
||||
@@ -532,9 +540,22 @@ public class SubscriptionController {
|
||||
Map<Long, LevelConfiguration> levels,
|
||||
@Schema(description = "Backup specific configuration")
|
||||
BackupConfiguration backup,
|
||||
@Schema(description = "Signal Login specific configuration")
|
||||
LoginConfiguration login,
|
||||
@Schema(description = "The maximum value of a one-time donation SEPA transaction")
|
||||
BigDecimal sepaMaximumEuros) {}
|
||||
|
||||
@Schema(description = "Configuration for one-time Signal Login purchases")
|
||||
public record LoginConfiguration(
|
||||
@Schema(description = "The receipt level associated with a Signal Login purchase")
|
||||
long level,
|
||||
@Schema(description = "The play billing productID associated with a Signal Login purchase")
|
||||
String playProductId,
|
||||
@Schema(description = "The play billing optionID to use to purchase a Signal Login")
|
||||
String playOptionId,
|
||||
@Schema(description = "The App Store productID associated with a Signal Login purchase")
|
||||
String appStoreProductId) {}
|
||||
|
||||
public record BackupConfiguration(
|
||||
@Schema(description = "A map of numeric backup level IDs to level-specific backup configuration")
|
||||
Map<String, BackupLevelConfiguration> levels,
|
||||
@@ -605,7 +626,7 @@ public class SubscriptionController {
|
||||
String currency,
|
||||
|
||||
@Schema(
|
||||
description = "The amount paid for the subscription in the currency's smallest unit",
|
||||
description = "The amount paid for the subscription in the currency's minor unit",
|
||||
externalDocs = @ExternalDocumentation(description = "Stripe Currencies", url = "https://docs.stripe.com/currencies"))
|
||||
BigDecimal amount,
|
||||
|
||||
@@ -657,7 +678,7 @@ public class SubscriptionController {
|
||||
subscriptionInformation.active(),
|
||||
subscriptionInformation.cancelAtPeriodEnd(),
|
||||
subscriptionInformation.price().currency(),
|
||||
subscriptionInformation.price().amount(),
|
||||
BigDecimal.valueOf(subscriptionInformation.price().amount()),
|
||||
subscriptionInformation.status().getApiValue(),
|
||||
subscriptionInformation.paymentProvider(),
|
||||
subscriptionInformation.paymentMethod(),
|
||||
@@ -735,7 +756,8 @@ public class SubscriptionController {
|
||||
try {
|
||||
final SubscriptionManager.ReceiptResult receiptCredential = subscriptionManager.createReceiptCredentials(
|
||||
subscriberCredentials, request.receiptCredentialRequest(),
|
||||
r -> SubscriptionsUtil.receiptExpirationWithGracePeriod(subscriptionConfiguration, r));
|
||||
r -> SubscriptionsUtil.receiptExpirationWithGracePeriod(subscriptionConfiguration, r),
|
||||
userAgent);
|
||||
|
||||
final ReceiptCredentialResponse receiptCredentialResponse = receiptCredential.receiptCredentialResponse();
|
||||
final CustomerAwareSubscriptionPaymentProcessor.ReceiptItem receipt = receiptCredential.receiptItem();
|
||||
|
||||
+12
-17
@@ -7,7 +7,6 @@ package org.whispersystems.textsecuregcm.controllers;
|
||||
|
||||
import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
|
||||
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import com.google.i18n.phonenumbers.NumberParseException;
|
||||
import com.google.i18n.phonenumbers.PhoneNumberUtil;
|
||||
import com.google.i18n.phonenumbers.Phonenumber;
|
||||
@@ -73,9 +72,7 @@ import org.whispersystems.textsecuregcm.entities.SubmitVerificationCodeRequest;
|
||||
import org.whispersystems.textsecuregcm.entities.UpdateVerificationSessionRequest;
|
||||
import org.whispersystems.textsecuregcm.entities.VerificationCodeRequest;
|
||||
import org.whispersystems.textsecuregcm.entities.VerificationSessionResponse;
|
||||
import org.whispersystems.textsecuregcm.experiment.ExperimentEnrollmentManager;
|
||||
import org.whispersystems.textsecuregcm.filters.RemoteAddressFilter;
|
||||
import org.whispersystems.textsecuregcm.identity.IdentityType;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimiters;
|
||||
import org.whispersystems.textsecuregcm.mappers.RegistrationServiceSenderExceptionMapper;
|
||||
import org.whispersystems.textsecuregcm.metrics.CaptchaMetrics;
|
||||
@@ -97,7 +94,7 @@ import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.DynamicConfigurationManager;
|
||||
import org.whispersystems.textsecuregcm.storage.PhoneNumberIdentifiers;
|
||||
import org.whispersystems.textsecuregcm.storage.RegistrationRecoveryPasswordsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.PhoneNumberRecoveryPasswordsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.VerificationSessionManager;
|
||||
import org.whispersystems.textsecuregcm.telephony.CarrierData;
|
||||
import org.whispersystems.textsecuregcm.telephony.CarrierDataException;
|
||||
@@ -132,48 +129,42 @@ public class VerificationController {
|
||||
private static final String EXISTING_ACCOUNT_PLATFORM = "existingAccountPlatform";
|
||||
private static final String EXISTING_ACCOUNT_RECENTLY_SEEN_TAG_NAME = "existingAccountRecentlySeen";
|
||||
|
||||
@VisibleForTesting
|
||||
static final String VERIFICATION_CODE_PUSH_NOTIFICATION_EXPERIMENT_NAME = "verificationCodePushNotification";
|
||||
|
||||
private final RegistrationServiceClient registrationServiceClient;
|
||||
private final VerificationSessionManager verificationSessionManager;
|
||||
private final PushNotificationManager pushNotificationManager;
|
||||
private final RegistrationCaptchaManager registrationCaptchaManager;
|
||||
private final RegistrationRecoveryPasswordsManager registrationRecoveryPasswordsManager;
|
||||
private final PhoneNumberRecoveryPasswordsManager phoneNumberRecoveryPasswordsManager;
|
||||
private final PhoneNumberIdentifiers phoneNumberIdentifiers;
|
||||
private final RateLimiters rateLimiters;
|
||||
private final AccountsManager accountsManager;
|
||||
private final CarrierDataProvider carrierDataProvider;
|
||||
private final RegistrationFraudChecker registrationFraudChecker;
|
||||
private final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager;
|
||||
private final ExperimentEnrollmentManager experimentEnrollmentManager;
|
||||
private final Clock clock;
|
||||
|
||||
public VerificationController(final RegistrationServiceClient registrationServiceClient,
|
||||
final VerificationSessionManager verificationSessionManager,
|
||||
final PushNotificationManager pushNotificationManager,
|
||||
final RegistrationCaptchaManager registrationCaptchaManager,
|
||||
final RegistrationRecoveryPasswordsManager registrationRecoveryPasswordsManager,
|
||||
final PhoneNumberRecoveryPasswordsManager phoneNumberRecoveryPasswordsManager,
|
||||
final PhoneNumberIdentifiers phoneNumberIdentifiers,
|
||||
final RateLimiters rateLimiters,
|
||||
final AccountsManager accountsManager,
|
||||
final CarrierDataProvider carrierDataProvider,
|
||||
final RegistrationFraudChecker registrationFraudChecker,
|
||||
final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager,
|
||||
final ExperimentEnrollmentManager experimentEnrollmentManager,
|
||||
final Clock clock) {
|
||||
this.registrationServiceClient = registrationServiceClient;
|
||||
this.verificationSessionManager = verificationSessionManager;
|
||||
this.pushNotificationManager = pushNotificationManager;
|
||||
this.registrationCaptchaManager = registrationCaptchaManager;
|
||||
this.registrationRecoveryPasswordsManager = registrationRecoveryPasswordsManager;
|
||||
this.phoneNumberRecoveryPasswordsManager = phoneNumberRecoveryPasswordsManager;
|
||||
this.phoneNumberIdentifiers = phoneNumberIdentifiers;
|
||||
this.rateLimiters = rateLimiters;
|
||||
this.accountsManager = accountsManager;
|
||||
this.carrierDataProvider = carrierDataProvider;
|
||||
this.registrationFraudChecker = registrationFraudChecker;
|
||||
this.dynamicConfigurationManager = dynamicConfigurationManager;
|
||||
this.experimentEnrollmentManager = experimentEnrollmentManager;
|
||||
this.clock = clock;
|
||||
}
|
||||
|
||||
@@ -665,8 +656,6 @@ public class VerificationController {
|
||||
}
|
||||
|
||||
accountsManager.getByE164(registrationServiceSession.number())
|
||||
.filter(existingAccount ->
|
||||
experimentEnrollmentManager.isEnrolled(existingAccount.getIdentifier(IdentityType.ACI), VERIFICATION_CODE_PUSH_NOTIFICATION_EXPERIMENT_NAME))
|
||||
.ifPresent(existingAccount -> {
|
||||
try {
|
||||
pushNotificationManager.sendVerificationCodeRequestedNotifications(existingAccount, clock.instant());
|
||||
@@ -749,7 +738,10 @@ public class VerificationController {
|
||||
// the RRP. It's possible the client will not actually be able to register (e.g. failed reglock challenge), and
|
||||
// so we will have removed the RRP unnecessarily. The impact of this is low, since the owner of the RRP
|
||||
// can always just fallback to session-based verification.
|
||||
existingRRP = registrationRecoveryPasswordsManager.remove(phoneNumberIdentifiers.getPhoneNumberIdentifier(registrationServiceSession.number()).join());
|
||||
//
|
||||
// Note that we do not remove the recovery password from the account itself because re-creation is imminent, and
|
||||
// that process will overwrite the recovery password (along with the rest of the account record).
|
||||
existingRRP = phoneNumberRecoveryPasswordsManager.remove(phoneNumberIdentifiers.getPhoneNumberIdentifier(registrationServiceSession.number()).join());
|
||||
}
|
||||
|
||||
Optional<Account> maybeExistingAccount;
|
||||
@@ -824,7 +816,10 @@ public class VerificationController {
|
||||
// the RRP. It's possible the client will not actually be able to register (e.g. failed reglock challenge), and
|
||||
// so we will have removed the RRP unnecessarily. The impact of this is low, since the owner of the RRP
|
||||
// can always just fallback to session-based verification.
|
||||
registrationRecoveryPasswordsManager.remove(phoneNumberIdentifiers.getPhoneNumberIdentifier(registrationServiceSession.number()).join());
|
||||
//
|
||||
// Note that we do not remove the recovery password from the account itself because re-creation is imminent, and
|
||||
// that process will overwrite the recovery password (along with the rest of the account record).
|
||||
phoneNumberRecoveryPasswordsManager.remove(phoneNumberIdentifiers.getPhoneNumberIdentifier(registrationServiceSession.number()).join());
|
||||
}
|
||||
|
||||
return registrationServiceSession;
|
||||
|
||||
+13
-5
@@ -14,6 +14,7 @@ import jakarta.validation.constraints.AssertTrue;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import javax.annotation.Nullable;
|
||||
import org.apache.commons.lang3.ArrayUtils;
|
||||
import org.whispersystems.textsecuregcm.auth.UnidentifiedAccessUtil;
|
||||
import org.whispersystems.textsecuregcm.storage.DeviceCapability;
|
||||
import org.whispersystems.textsecuregcm.util.ByteArrayAdapter;
|
||||
@@ -52,15 +53,17 @@ public class AccountAttributes {
|
||||
public AccountAttributes(
|
||||
final boolean fetchesMessages,
|
||||
final int registrationId,
|
||||
final int phoneNumberIdentifierRegistrationId,
|
||||
final Integer phoneNumberIdentifierRegistrationId,
|
||||
final byte[] name,
|
||||
final String registrationLock,
|
||||
final boolean discoverableByPhoneNumber,
|
||||
final Set<DeviceCapability> capabilities) {
|
||||
final Set<DeviceCapability> capabilities,
|
||||
@Nullable final byte[] recoveryPassword) {
|
||||
|
||||
this.deviceAttributes = new DeviceAttributes(fetchesMessages, registrationId, phoneNumberIdentifierRegistrationId, name, capabilities);
|
||||
this.registrationLock = registrationLock;
|
||||
this.discoverableByPhoneNumber = discoverableByPhoneNumber;
|
||||
this.recoveryPassword = recoveryPassword;
|
||||
}
|
||||
|
||||
public boolean getFetchesMessages() {
|
||||
@@ -71,8 +74,8 @@ public class AccountAttributes {
|
||||
return deviceAttributes.registrationId();
|
||||
}
|
||||
|
||||
public int getPhoneNumberIdentityRegistrationId() {
|
||||
return deviceAttributes.phoneNumberIdentityRegistrationId();
|
||||
public Optional<Integer> getPhoneNumberIdentityRegistrationId() {
|
||||
return Optional.ofNullable(deviceAttributes.phoneNumberIdentityRegistrationId());
|
||||
}
|
||||
|
||||
public byte[] getName() {
|
||||
@@ -101,7 +104,7 @@ public class AccountAttributes {
|
||||
}
|
||||
|
||||
public Optional<byte[]> recoveryPassword() {
|
||||
return Optional.ofNullable(recoveryPassword);
|
||||
return Optional.ofNullable(recoveryPassword).filter(ArrayUtils::isNotEmpty);
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
@@ -128,6 +131,11 @@ public class AccountAttributes {
|
||||
return this;
|
||||
}
|
||||
|
||||
public AccountAttributes setDiscoverableByPhoneNumber(final boolean discoverableByPhoneNumber) {
|
||||
this.discoverableByPhoneNumber = discoverableByPhoneNumber;
|
||||
return this;
|
||||
}
|
||||
|
||||
@AssertTrue
|
||||
@Schema(hidden = true)
|
||||
public boolean isUnrestrictedUakValid() {
|
||||
|
||||
+17
-12
@@ -13,6 +13,7 @@ import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import java.time.Instant;
|
||||
import java.time.temporal.ChronoUnit;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import javax.annotation.Nullable;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountBadge;
|
||||
@@ -36,21 +37,24 @@ public record AccountDataReportResponse(UUID reportId,
|
||||
builder.append(String.format("""
|
||||
Report ID: %s
|
||||
Report timestamp: %s
|
||||
|
||||
|
||||
""",
|
||||
reportId,
|
||||
reportTimestamp.truncatedTo(ChronoUnit.SECONDS)));
|
||||
|
||||
// account
|
||||
builder.append(String.format("""
|
||||
# Account
|
||||
Phone number: %s
|
||||
Allow sealed sender from anyone: %s
|
||||
Find account by phone number: %s
|
||||
""",
|
||||
data.account.phoneNumber(),
|
||||
data.account.allowSealedSenderFromAnyone(),
|
||||
data.account.findAccountByPhoneNumber()));
|
||||
builder.append("# Account\n");
|
||||
|
||||
data.account.phoneNumber().ifPresent(phoneNumber -> {
|
||||
builder.append(String.format("""
|
||||
Phone number: %s
|
||||
Find account by phone number: %s
|
||||
""",
|
||||
phoneNumber,
|
||||
data.account.findAccountByPhoneNumber()));
|
||||
});
|
||||
|
||||
builder.append(String.format("Allow sealed sender from anyone: %s%n", data.account.allowSealedSenderFromAnyone()));
|
||||
|
||||
// badges
|
||||
builder.append("Badges:");
|
||||
@@ -93,9 +97,10 @@ public record AccountDataReportResponse(UUID reportId,
|
||||
|
||||
}
|
||||
|
||||
public record AccountDataReport(String phoneNumber, List<BadgeDataReport> badges, boolean allowSealedSenderFromAnyone,
|
||||
public record AccountDataReport(Optional<String> phoneNumber,
|
||||
List<BadgeDataReport> badges,
|
||||
boolean allowSealedSenderFromAnyone,
|
||||
boolean findAccountByPhoneNumber) {
|
||||
|
||||
}
|
||||
|
||||
public record DeviceDataReport(byte id,
|
||||
|
||||
+9
-5
@@ -8,6 +8,7 @@ package org.whispersystems.textsecuregcm.entities;
|
||||
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
|
||||
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import javax.annotation.Nullable;
|
||||
import org.whispersystems.textsecuregcm.util.ByteArrayBase64UrlAdapter;
|
||||
@@ -16,11 +17,11 @@ public record AccountIdentityResponse(
|
||||
@Schema(description = "the account identifier for this account")
|
||||
UUID uuid,
|
||||
|
||||
@Schema(description = "the phone number associated with this account")
|
||||
String number,
|
||||
@Schema(description = "the phone number associated with this account; may be null if this account does not have a phone number")
|
||||
Optional<String> number,
|
||||
|
||||
@Schema(description = "the account identifier for this account's phone-number identity")
|
||||
UUID pni,
|
||||
@Schema(description = "the account identifier for this account's phone-number identity; may be null if this account does not have a phone number")
|
||||
Optional<UUID> pni,
|
||||
|
||||
@Schema(description = "a hash of this account's username, if set")
|
||||
@JsonSerialize(using = ByteArrayBase64UrlAdapter.Serializing.class)
|
||||
@@ -34,5 +35,8 @@ public record AccountIdentityResponse(
|
||||
boolean storageCapable,
|
||||
|
||||
@Schema(description = "entitlements for this account and their current expirations")
|
||||
Entitlements entitlements) {
|
||||
Entitlements entitlements,
|
||||
|
||||
@Schema(description = "salt to generate PNI auth credentials for accounts without a phone number; null if this account has a phone number")
|
||||
@Nullable byte[] authCredentialSalt) {
|
||||
}
|
||||
+6
-12
@@ -1,10 +1,8 @@
|
||||
package org.whispersystems.textsecuregcm.entities;
|
||||
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
|
||||
import jakarta.validation.Valid;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
public record DeviceActivationRequest(
|
||||
@@ -15,12 +13,10 @@ public record DeviceActivationRequest(
|
||||
""")
|
||||
ECSignedPreKey aciSignedPreKey,
|
||||
|
||||
@NotNull
|
||||
@Valid
|
||||
@Schema(requiredMode = Schema.RequiredMode.REQUIRED, description = """
|
||||
A signed EC pre-key to be associated with this account's PNI.
|
||||
@Schema(requiredMode = Schema.RequiredMode.NOT_REQUIRED, description = """
|
||||
If the account has a phone number, a signed EC pre-key to be associated with this account's PNI.
|
||||
""")
|
||||
ECSignedPreKey pniSignedPreKey,
|
||||
Optional<@Valid ECSignedPreKey> pniSignedPreKey,
|
||||
|
||||
@NotNull
|
||||
@Valid
|
||||
@@ -29,12 +25,10 @@ public record DeviceActivationRequest(
|
||||
""")
|
||||
KEMSignedPreKey aciPqLastResortPreKey,
|
||||
|
||||
@NotNull
|
||||
@Valid
|
||||
@Schema(requiredMode = Schema.RequiredMode.REQUIRED, description = """
|
||||
A signed Kyber-1024 "last resort" pre-key to be associated with this account's PNI.
|
||||
@Schema(requiredMode = Schema.RequiredMode.NOT_REQUIRED, description = """
|
||||
If the account has a phone number, a signed Kyber-1024 "last resort" pre-key to be associated with this account's PNI.
|
||||
""")
|
||||
KEMSignedPreKey pniPqLastResortPreKey,
|
||||
Optional<@Valid KEMSignedPreKey> pniPqLastResortPreKey,
|
||||
|
||||
@Schema(requiredMode = Schema.RequiredMode.NOT_REQUIRED, description = """
|
||||
An APNs token set for the account's primary device. If provided, the account's primary
|
||||
|
||||
+6
-4
@@ -13,6 +13,7 @@ import com.fasterxml.jackson.databind.annotation.JsonSerialize;
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import jakarta.validation.constraints.AssertTrue;
|
||||
import jakarta.validation.constraints.Size;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import javax.annotation.Nullable;
|
||||
import org.whispersystems.textsecuregcm.storage.DeviceCapability;
|
||||
@@ -24,16 +25,16 @@ public record DeviceAttributes(
|
||||
|
||||
int registrationId,
|
||||
|
||||
@JsonProperty("pniRegistrationId") int phoneNumberIdentityRegistrationId,
|
||||
@JsonProperty("pniRegistrationId")
|
||||
@Nullable
|
||||
Integer phoneNumberIdentityRegistrationId,
|
||||
|
||||
@JsonSerialize(using = ByteArrayAdapter.Serializing.class)
|
||||
|
||||
@JsonDeserialize(using = ByteArrayAdapter.Deserializing.class)
|
||||
@Size(max = 225)
|
||||
byte[] name,
|
||||
|
||||
@JsonSerialize(using = DeviceCapabilityAdapter.Serializer.class)
|
||||
|
||||
@JsonDeserialize(using = DeviceCapabilityAdapter.Deserializer.class)
|
||||
@Nullable
|
||||
Set<DeviceCapability> capabilities) {
|
||||
@@ -41,6 +42,7 @@ public record DeviceAttributes(
|
||||
@AssertTrue
|
||||
@Schema(hidden = true)
|
||||
public boolean isEachRegistrationIdValid() {
|
||||
return validRegistrationId(registrationId) && validRegistrationId(phoneNumberIdentityRegistrationId);
|
||||
return validRegistrationId(registrationId) &&
|
||||
(phoneNumberIdentityRegistrationId == null || validRegistrationId(phoneNumberIdentityRegistrationId));
|
||||
}
|
||||
}
|
||||
@@ -8,7 +8,6 @@ package org.whispersystems.textsecuregcm.entities;
|
||||
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
|
||||
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import org.whispersystems.textsecuregcm.identity.IdentityType;
|
||||
import org.whispersystems.textsecuregcm.storage.Device;
|
||||
import org.whispersystems.textsecuregcm.util.ByteArrayAdapter;
|
||||
import org.whispersystems.textsecuregcm.util.ByteArrayBase64WithPaddingAdapter;
|
||||
@@ -33,7 +32,10 @@ public record DeviceInfo(long id,
|
||||
byte[] createdAtCiphertext) {
|
||||
|
||||
public static DeviceInfo forDevice(final Device device) {
|
||||
return new DeviceInfo(device.getId(), device.getName(), device.getLastSeen(), device.getRegistrationId(
|
||||
IdentityType.ACI), device.getCreatedAtCiphertext());
|
||||
return new DeviceInfo(device.getId(),
|
||||
device.getName(),
|
||||
device.getLastSeen(),
|
||||
device.getAccountRegistrationId(),
|
||||
device.getCreatedAtCiphertext());
|
||||
}
|
||||
}
|
||||
+2
-2
@@ -6,7 +6,6 @@ package org.whispersystems.textsecuregcm.entities;
|
||||
|
||||
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
|
||||
import com.google.protobuf.ByteString;
|
||||
import com.webauthn4j.converter.jackson.deserializer.json.ByteArrayBase64Deserializer;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import jakarta.validation.constraints.AssertTrue;
|
||||
@@ -19,12 +18,13 @@ import javax.annotation.Nullable;
|
||||
import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.identity.ServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
|
||||
import org.whispersystems.textsecuregcm.util.ByteArrayAdapter;
|
||||
|
||||
public record IncomingMessage(int type,
|
||||
byte destinationDeviceId,
|
||||
int destinationRegistrationId,
|
||||
|
||||
@JsonDeserialize(using = ByteArrayBase64Deserializer.class)
|
||||
@JsonDeserialize(using = ByteArrayAdapter.Deserializing.class)
|
||||
@NotNull
|
||||
// Note that max size is validated elsewhere in the interest of controlling responses and
|
||||
// reporting additional metrics.
|
||||
|
||||
+2
-2
@@ -33,9 +33,9 @@ public record LinkDeviceRequest(@Schema(requiredMode = Schema.RequiredMode.REQUI
|
||||
public LinkDeviceRequest(@JsonProperty("verificationCode") String verificationCode,
|
||||
@JsonProperty("accountAttributes") DeviceAttributes deviceAttributes,
|
||||
@JsonProperty("aciSignedPreKey") @NotNull @Valid ECSignedPreKey aciSignedPreKey,
|
||||
@JsonProperty("pniSignedPreKey") @NotNull @Valid ECSignedPreKey pniSignedPreKey,
|
||||
@JsonProperty("pniSignedPreKey") Optional<@Valid ECSignedPreKey> pniSignedPreKey,
|
||||
@JsonProperty("aciPqLastResortPreKey") @NotNull @Valid KEMSignedPreKey aciPqLastResortPreKey,
|
||||
@JsonProperty("pniPqLastResortPreKey") @NotNull @Valid KEMSignedPreKey pniPqLastResortPreKey,
|
||||
@JsonProperty("pniPqLastResortPreKey") Optional<@Valid KEMSignedPreKey> pniPqLastResortPreKey,
|
||||
@JsonProperty("apnToken") Optional<@Valid ApnRegistrationId> apnToken,
|
||||
@JsonProperty("gcmToken") Optional<@Valid GcmRegistrationId> gcmToken) {
|
||||
|
||||
|
||||
+2
-1
@@ -5,7 +5,8 @@
|
||||
|
||||
package org.whispersystems.textsecuregcm.entities;
|
||||
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
|
||||
public record LinkDeviceResponse(UUID uuid, UUID pni, byte deviceId) {
|
||||
public record LinkDeviceResponse(UUID uuid, Optional<UUID> pni, byte deviceId) {
|
||||
}
|
||||
+26
-5
@@ -10,31 +10,52 @@ import static org.apache.commons.lang3.StringUtils.isNotBlank;
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import jakarta.validation.constraints.AssertTrue;
|
||||
import jakarta.ws.rs.ClientErrorException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Base64;
|
||||
import java.util.List;
|
||||
import org.apache.commons.lang3.ArrayUtils;
|
||||
import org.apache.http.HttpStatus;
|
||||
|
||||
public interface PhoneVerificationRequest {
|
||||
|
||||
enum VerificationType {
|
||||
SESSION,
|
||||
RECOVERY_PASSWORD
|
||||
RECOVERY_PASSWORD,
|
||||
RECEIPT_CREDENTIAL
|
||||
}
|
||||
|
||||
String sessionId();
|
||||
|
||||
byte[] recoveryPassword();
|
||||
|
||||
default byte[] receiptCredentialPresentation() {
|
||||
return null;
|
||||
}
|
||||
|
||||
// for the @AssertTrue to work with bean validation, method name must follow 'isSmth()'/'getSmth()' naming convention
|
||||
@AssertTrue
|
||||
@Schema(hidden = true)
|
||||
default boolean isValid() {
|
||||
// checking that exactly one of sessionId/recoveryPassword is non-empty
|
||||
return isNotBlank(sessionId()) ^ (recoveryPassword() != null && recoveryPassword().length > 0);
|
||||
// exactly one of sessionId/recoveryPassword/receiptCredentialPresentation should be present
|
||||
return presentVerificationTypes().size() == 1;
|
||||
}
|
||||
|
||||
default PhoneVerificationRequest.VerificationType verificationType() {
|
||||
return isNotBlank(sessionId()) ? PhoneVerificationRequest.VerificationType.SESSION
|
||||
: PhoneVerificationRequest.VerificationType.RECOVERY_PASSWORD;
|
||||
return presentVerificationTypes().get(0);
|
||||
}
|
||||
|
||||
default List<VerificationType> presentVerificationTypes() {
|
||||
final List<VerificationType> types = new ArrayList<>(1);
|
||||
if (isNotBlank(sessionId())) {
|
||||
types.add(VerificationType.SESSION);
|
||||
}
|
||||
if (ArrayUtils.isNotEmpty(recoveryPassword())) {
|
||||
types.add(VerificationType.RECOVERY_PASSWORD);
|
||||
}
|
||||
if (ArrayUtils.isNotEmpty(receiptCredentialPresentation())) {
|
||||
types.add(VerificationType.RECEIPT_CREDENTIAL);
|
||||
}
|
||||
return types;
|
||||
}
|
||||
|
||||
default byte[] decodeSessionId() {
|
||||
|
||||
-1
@@ -22,7 +22,6 @@ public abstract class PreKeySignatureValidator {
|
||||
final Collection<SignedPreKey<?>> signedPreKeys,
|
||||
@Nullable final String userAgent,
|
||||
final String context) {
|
||||
|
||||
final boolean success = signedPreKeys.stream().allMatch(signedPreKey -> signedPreKey.signatureValid(identityKey));
|
||||
|
||||
if (!success) {
|
||||
|
||||
+81
-10
@@ -14,26 +14,62 @@ import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import jakarta.validation.Valid;
|
||||
import jakarta.validation.constraints.AssertTrue;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
import jakarta.validation.constraints.PositiveOrZero;
|
||||
import java.util.List;
|
||||
import java.util.stream.Stream;
|
||||
import javax.annotation.Nullable;
|
||||
import jakarta.validation.constraints.Size;
|
||||
import org.apache.commons.lang3.ArrayUtils;
|
||||
import org.signal.libsignal.protocol.IdentityKey;
|
||||
import org.whispersystems.textsecuregcm.util.ByteArrayAdapter;
|
||||
import org.whispersystems.textsecuregcm.util.IdentityKeyAdapter;
|
||||
|
||||
public record RegistrationRequest(@Schema(requiredMode = Schema.RequiredMode.NOT_REQUIRED, description = """
|
||||
The ID of an existing verification session as it appears in a verification session
|
||||
metadata object. Must be provided if `recoveryPassword` is not provided; must not be
|
||||
provided if `recoveryPassword` is provided.
|
||||
metadata object. Must be provided if `recoveryPassword` and `receiptCredentialPresentation`
|
||||
are not provided; must not be provided if `recoveryPassword` or `receiptCredentialPresentation`
|
||||
is provided.
|
||||
""")
|
||||
@Nullable
|
||||
String sessionId,
|
||||
|
||||
@JsonDeserialize(using = ByteArrayAdapter.Deserializing.class)
|
||||
@Schema(requiredMode = Schema.RequiredMode.NOT_REQUIRED, description = """
|
||||
A base64-encoded registration recovery password. Must be provided if `sessionId` is
|
||||
not provided; must not be provided if `sessionId` is provided
|
||||
A base64-encoded registration recovery password. Must be provided if `sessionId` and
|
||||
`receiptCredentialPresentation` are not provided; must not be provided if `sessionId`
|
||||
or `receiptCredentialPresentation` is provided. Registration recovery passwords must
|
||||
be specified when reclaiming an account by account identifier.
|
||||
""")
|
||||
@Nullable
|
||||
byte[] recoveryPassword,
|
||||
|
||||
@JsonDeserialize(using = ByteArrayAdapter.Deserializing.class)
|
||||
@Schema(requiredMode = Schema.RequiredMode.NOT_REQUIRED, description = """
|
||||
A base64-encoded receipt credential presentation that allows for redeeming a Signal Login.
|
||||
Must be provided if `sessionId` and `recoveryPassword` are not provided;
|
||||
must not be provided if `sessionId` or `recoveryPassword` is provided. Must not be
|
||||
provided if recovering a previously used account.
|
||||
""")
|
||||
@Nullable
|
||||
byte[] receiptCredentialPresentation,
|
||||
|
||||
@Schema(requiredMode = Schema.RequiredMode.NOT_REQUIRED, description = """
|
||||
A TOTP one-time password; required if recovering an account that has TOTP keys. Must
|
||||
not be provided if `receiptCredentialPresentation` is provided.
|
||||
""")
|
||||
@PositiveOrZero
|
||||
@Nullable
|
||||
Integer totp,
|
||||
|
||||
@Schema(requiredMode = Schema.RequiredMode.NOT_REQUIRED, description = """
|
||||
A JSON-serialized assertion response from a completed authentication ceremony.
|
||||
See https://www.w3.org/TR/webauthn/#authenticatorassertionresponse.
|
||||
""")
|
||||
@Nullable
|
||||
// There is no documented max size, but 8kiB should be enough
|
||||
@Size(min = 1, max = 8192)
|
||||
String webAuthnResponse,
|
||||
|
||||
@NotNull
|
||||
@Valid
|
||||
@Schema(requiredMode = Schema.RequiredMode.REQUIRED)
|
||||
@@ -58,13 +94,17 @@ public record RegistrationRequest(@Schema(requiredMode = Schema.RequiredMode.NOT
|
||||
@JsonDeserialize(using = IdentityKeyAdapter.Deserializer.class)
|
||||
IdentityKey aciIdentityKey,
|
||||
|
||||
@NotNull
|
||||
@Valid
|
||||
@Schema(requiredMode = Schema.RequiredMode.REQUIRED, description = """
|
||||
@Schema(requiredMode = Schema.RequiredMode.NOT_REQUIRED, description = """
|
||||
The PNI-associated identity key for the account, encoded as a base64 string.
|
||||
Must be provided for an account with a phone number or when recovering an account by
|
||||
ID (even if the recovered account does not have a phone number, in which case
|
||||
PNI-associated key material will be ignored). Must be absent when registering an
|
||||
account without a phone number.
|
||||
""")
|
||||
@JsonSerialize(using = IdentityKeyAdapter.Serializer.class)
|
||||
@JsonDeserialize(using = IdentityKeyAdapter.Deserializer.class)
|
||||
@Nullable
|
||||
IdentityKey pniIdentityKey,
|
||||
|
||||
@NotNull
|
||||
@@ -75,14 +115,18 @@ public record RegistrationRequest(@Schema(requiredMode = Schema.RequiredMode.NOT
|
||||
|
||||
public boolean isEverySignedKeyValid(@Nullable final String userAgent) {
|
||||
if (deviceActivationRequest().aciSignedPreKey() == null ||
|
||||
deviceActivationRequest().pniSignedPreKey() == null ||
|
||||
deviceActivationRequest().aciPqLastResortPreKey() == null ||
|
||||
deviceActivationRequest().pniPqLastResortPreKey() == null) {
|
||||
deviceActivationRequest().aciPqLastResortPreKey() == null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
final boolean allPniPresentOrAllAbsent = ((pniIdentityKey == null) == deviceActivationRequest().pniSignedPreKey().isEmpty())
|
||||
&& ((pniIdentityKey == null) == deviceActivationRequest().pniPqLastResortPreKey().isEmpty());
|
||||
if (!allPniPresentOrAllAbsent) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return PreKeySignatureValidator.validatePreKeySignatures(aciIdentityKey(), List.of(deviceActivationRequest().aciSignedPreKey(), deviceActivationRequest().aciPqLastResortPreKey()), userAgent, "register")
|
||||
&& PreKeySignatureValidator.validatePreKeySignatures(pniIdentityKey(), List.of(deviceActivationRequest().pniSignedPreKey(), deviceActivationRequest().pniPqLastResortPreKey()), userAgent, "register");
|
||||
&& (pniIdentityKey == null || PreKeySignatureValidator.validatePreKeySignatures(pniIdentityKey(), List.of(deviceActivationRequest().pniSignedPreKey().get(), deviceActivationRequest().pniPqLastResortPreKey().get()), userAgent, "register"));
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
@@ -98,4 +142,31 @@ public record RegistrationRequest(@Schema(requiredMode = Schema.RequiredMode.NOT
|
||||
return deviceActivationRequest().apnToken().isPresent() ^ deviceActivationRequest().gcmToken().isPresent();
|
||||
}
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
@AssertTrue
|
||||
@Schema(hidden = true)
|
||||
boolean isAllOrNoPhoneNumberInformationProvided() {
|
||||
final boolean expectPresence = pniIdentityKey != null;
|
||||
|
||||
return Stream.of(pniIdentityKey != null,
|
||||
accountAttributes().getPhoneNumberIdentityRegistrationId().isPresent(),
|
||||
deviceActivationRequest().pniSignedPreKey().isPresent(),
|
||||
deviceActivationRequest().pniPqLastResortPreKey().isPresent())
|
||||
.allMatch(present -> present == expectPresence);
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
@AssertTrue
|
||||
@Schema(hidden = true)
|
||||
boolean isMfaAbsentWhenUsingReceipt() {
|
||||
return ArrayUtils.isEmpty(receiptCredentialPresentation) || (totp == null && webAuthnResponse == null);
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
@AssertTrue
|
||||
@Schema(hidden = true)
|
||||
boolean isAtMostOneMfaPresent() {
|
||||
return totp == null || webAuthnResponse == null;
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -65,7 +65,7 @@ abstract class IdleDevicePushNotificationExperiment implements PushNotificationE
|
||||
} else {
|
||||
pushTokenType = null;
|
||||
}
|
||||
return new DeviceLastSeenState(true, device.getRegistrationId(IdentityType.ACI), hasPushToken(device), device.getLastSeen(), pushTokenType);
|
||||
return new DeviceLastSeenState(true, device.getAccountRegistrationId(), hasPushToken(device), device.getLastSeen(), pushTokenType);
|
||||
} else {
|
||||
return DeviceLastSeenState.MISSING_DEVICE_STATE;
|
||||
}
|
||||
|
||||
+303
-16
@@ -12,13 +12,18 @@ import java.security.SecureRandom;
|
||||
import java.time.Clock;
|
||||
import java.time.Instant;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
import java.util.Collections;
|
||||
import java.util.HashMap;
|
||||
import java.util.HexFormat;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import java.util.function.Function;
|
||||
import java.util.stream.Collectors;
|
||||
import javax.annotation.Nullable;
|
||||
import org.signal.chat.account.Capabilities;
|
||||
import org.signal.chat.account.ChangeNumberRequest;
|
||||
import org.signal.chat.account.ChangeNumberResponse;
|
||||
@@ -26,6 +31,8 @@ import org.signal.chat.account.ClearRegistrationLockRequest;
|
||||
import org.signal.chat.account.ClearRegistrationLockResponse;
|
||||
import org.signal.chat.account.ConfigureUnidentifiedAccessRequest;
|
||||
import org.signal.chat.account.ConfigureUnidentifiedAccessResponse;
|
||||
import org.signal.chat.account.ConfirmTotpKeyRequest;
|
||||
import org.signal.chat.account.ConfirmTotpKeyResponse;
|
||||
import org.signal.chat.account.ConfirmUsernameHashRequest;
|
||||
import org.signal.chat.account.ConfirmUsernameHashResponse;
|
||||
import org.signal.chat.account.DeleteAccountRequest;
|
||||
@@ -35,6 +42,12 @@ import org.signal.chat.account.DeleteUsernameHashResponse;
|
||||
import org.signal.chat.account.DeleteUsernameLinkRequest;
|
||||
import org.signal.chat.account.DeleteUsernameLinkResponse;
|
||||
import org.signal.chat.account.ExternalServiceCredentials;
|
||||
import org.signal.chat.account.FinishMfaVerificationRequest;
|
||||
import org.signal.chat.account.FinishMfaVerificationResponse;
|
||||
import org.signal.chat.account.FinishWebAuthnRegistrationRequest;
|
||||
import org.signal.chat.account.FinishWebAuthnRegistrationResponse;
|
||||
import org.signal.chat.account.GenerateTotpKeyRequest;
|
||||
import org.signal.chat.account.GenerateTotpKeyResponse;
|
||||
import org.signal.chat.account.GetAccountDataReportRequest;
|
||||
import org.signal.chat.account.GetAccountDataReportResponse;
|
||||
import org.signal.chat.account.GetAccountIdentityRequest;
|
||||
@@ -43,11 +56,19 @@ import org.signal.chat.account.GetCapabilitiesRequest;
|
||||
import org.signal.chat.account.GetCapabilitiesResponse;
|
||||
import org.signal.chat.account.GetEntitlementsRequest;
|
||||
import org.signal.chat.account.GetEntitlementsResponse;
|
||||
import org.signal.chat.account.ListMfaKeysRequest;
|
||||
import org.signal.chat.account.ListMfaKeysResponse;
|
||||
import org.signal.chat.account.ListMfaKeysResponse.MfaKeyMetadata.MfaKeyType;
|
||||
import org.signal.chat.account.StartMfaVerificationResponse.WebAuthnAuthenticationParameters;
|
||||
import org.signal.chat.account.RegistrationLockFailure;
|
||||
import org.signal.chat.account.RemoveMfaKeyRequest;
|
||||
import org.signal.chat.account.RemoveMfaKeyResponse;
|
||||
import org.signal.chat.account.ReserveUsernameHashRequest;
|
||||
import org.signal.chat.account.ReserveUsernameHashResponse;
|
||||
import org.signal.chat.account.SetDiscoverableByPhoneNumberRequest;
|
||||
import org.signal.chat.account.SetDiscoverableByPhoneNumberResponse;
|
||||
import org.signal.chat.account.SetMfaKeyMetadataRequest;
|
||||
import org.signal.chat.account.SetMfaKeyMetadataResponse;
|
||||
import org.signal.chat.account.SetRegistrationLockRequest;
|
||||
import org.signal.chat.account.SetRegistrationLockResponse;
|
||||
import org.signal.chat.account.SetRegistrationRecoveryPasswordRequest;
|
||||
@@ -58,9 +79,16 @@ import org.signal.chat.account.SetZkCredentialKeyRequest;
|
||||
import org.signal.chat.account.SetZkCredentialKeyResponse;
|
||||
import org.signal.chat.account.SimpleAccountsGrpc;
|
||||
import org.signal.chat.account.StaleDevices;
|
||||
import org.signal.chat.account.StartMfaVerificationRequest;
|
||||
import org.signal.chat.account.StartMfaVerificationResponse;
|
||||
import org.signal.chat.account.StartWebAuthnRegistrationRequest;
|
||||
import org.signal.chat.account.StartWebAuthnRegistrationResponse;
|
||||
import org.signal.chat.account.StartWebAuthnRegistrationResponse.WebAuthnCreateParameters;
|
||||
import org.signal.chat.account.TotpParameters;
|
||||
import org.signal.chat.account.UsernameNotAvailable;
|
||||
import org.signal.chat.common.AccountIdentifiers;
|
||||
import org.signal.chat.errors.FailedPrecondition;
|
||||
import org.signal.chat.errors.NotFound;
|
||||
import org.signal.chat.messages.SendMessageType;
|
||||
import org.signal.libsignal.protocol.IdentityKey;
|
||||
import org.signal.libsignal.protocol.InvalidKeyException;
|
||||
@@ -74,6 +102,8 @@ import org.whispersystems.textsecuregcm.auth.SaltedTokenHash;
|
||||
import org.whispersystems.textsecuregcm.auth.UnverifiedRegistrationSessionException;
|
||||
import org.whispersystems.textsecuregcm.auth.grpc.AuthenticatedDevice;
|
||||
import org.whispersystems.textsecuregcm.auth.grpc.AuthenticationUtil;
|
||||
import org.whispersystems.textsecuregcm.auth.webauthn.AuthenticationCeremonyParameters;
|
||||
import org.whispersystems.textsecuregcm.auth.webauthn.RegistrationCeremonyParameters;
|
||||
import org.whispersystems.textsecuregcm.controllers.MessageDeliveryNotAllowedException;
|
||||
import org.whispersystems.textsecuregcm.controllers.MismatchedDevicesException;
|
||||
import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
|
||||
@@ -83,21 +113,28 @@ import org.whispersystems.textsecuregcm.entities.IncomingMessage;
|
||||
import org.whispersystems.textsecuregcm.entities.KEMSignedPreKey;
|
||||
import org.whispersystems.textsecuregcm.entities.MessageProtos;
|
||||
import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.identity.IdentityType;
|
||||
import org.whispersystems.textsecuregcm.identity.PniServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimiters;
|
||||
import org.whispersystems.textsecuregcm.push.MessageTooLargeException;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.AnnotatedMfaKey;
|
||||
import org.whispersystems.textsecuregcm.storage.AnnotatedTotpKey;
|
||||
import org.whispersystems.textsecuregcm.storage.AnnotatedWebAuthnCredential;
|
||||
import org.whispersystems.textsecuregcm.storage.ChangeNumberManager;
|
||||
import org.whispersystems.textsecuregcm.storage.DeviceCapability;
|
||||
import org.whispersystems.textsecuregcm.storage.RegistrationRecoveryPasswordsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.PhoneNumberRecoveryPasswordsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.TooManyMfaKeysException;
|
||||
import org.whispersystems.textsecuregcm.storage.TooManyTotpKeysException;
|
||||
import org.whispersystems.textsecuregcm.storage.TotpKey;
|
||||
import org.whispersystems.textsecuregcm.storage.UsernameHashNotAvailableException;
|
||||
import org.whispersystems.textsecuregcm.storage.UsernameReservationNotFoundException;
|
||||
import org.whispersystems.textsecuregcm.util.NoStackTraceRuntimeException;
|
||||
import org.whispersystems.textsecuregcm.util.RegistrationIdValidator;
|
||||
import org.whispersystems.textsecuregcm.util.SystemMapper;
|
||||
import org.whispersystems.textsecuregcm.util.UUIDUtil;
|
||||
import org.whispersystems.textsecuregcm.util.UsernameHashZkProofVerifier;
|
||||
import software.amazon.awssdk.services.dynamodb.model.TransactWriteItem;
|
||||
|
||||
public class AccountsGrpcService extends SimpleAccountsGrpc.AccountsImplBase {
|
||||
|
||||
@@ -106,21 +143,24 @@ public class AccountsGrpcService extends SimpleAccountsGrpc.AccountsImplBase {
|
||||
private final AccountsManager accountsManager;
|
||||
private final RateLimiters rateLimiters;
|
||||
private final UsernameHashZkProofVerifier usernameHashZkProofVerifier;
|
||||
private final RegistrationRecoveryPasswordsManager registrationRecoveryPasswordsManager;
|
||||
private final PhoneNumberRecoveryPasswordsManager phoneNumberRecoveryPasswordsManager;
|
||||
private final Clock clock;
|
||||
private final ChangeNumberManager changeNumberManager;
|
||||
|
||||
private static class MfaKeyNotFoundException extends NoStackTraceRuntimeException {
|
||||
}
|
||||
|
||||
public AccountsGrpcService(final AccountsManager accountsManager,
|
||||
final RateLimiters rateLimiters,
|
||||
final UsernameHashZkProofVerifier usernameHashZkProofVerifier,
|
||||
final RegistrationRecoveryPasswordsManager registrationRecoveryPasswordsManager,
|
||||
final PhoneNumberRecoveryPasswordsManager phoneNumberRecoveryPasswordsManager,
|
||||
final Clock clock,
|
||||
final ChangeNumberManager changeNumberManager) {
|
||||
|
||||
this.accountsManager = accountsManager;
|
||||
this.rateLimiters = rateLimiters;
|
||||
this.usernameHashZkProofVerifier = usernameHashZkProofVerifier;
|
||||
this.registrationRecoveryPasswordsManager = registrationRecoveryPasswordsManager;
|
||||
this.phoneNumberRecoveryPasswordsManager = phoneNumberRecoveryPasswordsManager;
|
||||
this.clock = clock;
|
||||
this.changeNumberManager = changeNumberManager;
|
||||
}
|
||||
@@ -171,10 +211,14 @@ public class AccountsGrpcService extends SimpleAccountsGrpc.AccountsImplBase {
|
||||
final SaltedTokenHash credentials =
|
||||
SaltedTokenHash.generateFor(formatRegistrationLock(request.getRegistrationLock().toByteArray()));
|
||||
|
||||
accountsManager.update(AuthenticationUtil.requireAuthenticatedDevice().accountIdentifier(),
|
||||
account -> account.setRegistrationLock(credentials.hash(), credentials.salt()));
|
||||
try {
|
||||
accountsManager.update(AuthenticationUtil.requireAuthenticatedDevice().accountIdentifier(),
|
||||
account -> account.setRegistrationLock(credentials.hash(), credentials.salt()));
|
||||
|
||||
return SetRegistrationLockResponse.getDefaultInstance();
|
||||
return SetRegistrationLockResponse.getDefaultInstance();
|
||||
} catch (IllegalArgumentException _) {
|
||||
throw GrpcExceptions.invalidArguments(null);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -273,7 +317,7 @@ public class AccountsGrpcService extends SimpleAccountsGrpc.AccountsImplBase {
|
||||
? account.getUsernameLinkHandle()
|
||||
: UUID.randomUUID();
|
||||
|
||||
accountsManager.update(account.getIdentifier(IdentityType.ACI),
|
||||
accountsManager.update(account.getAccountIdentifier(),
|
||||
a -> a.setUsernameLinkDetails(linkHandle, request.getUsernameCiphertext().toByteArray()));
|
||||
|
||||
return responseBuilder.setUsernameLinkHandle(UUIDUtil.toByteString(linkHandle)).build();
|
||||
@@ -310,15 +354,29 @@ public class AccountsGrpcService extends SimpleAccountsGrpc.AccountsImplBase {
|
||||
@Override
|
||||
public SetDiscoverableByPhoneNumberResponse setDiscoverableByPhoneNumber(final SetDiscoverableByPhoneNumberRequest request) {
|
||||
accountsManager.update(AuthenticationUtil.requireAuthenticatedDevice().accountIdentifier(),
|
||||
account -> account.setDiscoverableByPhoneNumber(request.getDiscoverableByPhoneNumber()));
|
||||
account -> {
|
||||
if (account.getNumber().isEmpty()) {
|
||||
throw GrpcExceptions.invalidArguments("account does not have a phone number");
|
||||
}
|
||||
|
||||
account.setDiscoverableByPhoneNumber(request.getDiscoverableByPhoneNumber());
|
||||
});
|
||||
|
||||
return SetDiscoverableByPhoneNumberResponse.getDefaultInstance();
|
||||
}
|
||||
|
||||
@Override
|
||||
public SetRegistrationRecoveryPasswordResponse setRegistrationRecoveryPassword(final SetRegistrationRecoveryPasswordRequest request) {
|
||||
registrationRecoveryPasswordsManager.store(getAuthenticatedAccount().getIdentifier(IdentityType.PNI),
|
||||
request.getRegistrationRecoveryPassword().toByteArray());
|
||||
final Account account = getAuthenticatedAccount();
|
||||
final byte[] recoveryPassword = request.getRegistrationRecoveryPassword().toByteArray();
|
||||
|
||||
final Collection<TransactWriteItem> additionalWriteItems = account.getPhoneNumberIdentifier()
|
||||
.map(phoneNumberIdentifier ->
|
||||
List.of(phoneNumberRecoveryPasswordsManager.buildTransactWriteItemForStorePassword(phoneNumberIdentifier, recoveryPassword)))
|
||||
.orElseGet(Collections::emptyList);
|
||||
|
||||
// TODO Once we retire `AccountController`, replace this with a new `AccountsManager#setRecoveryPassword` method
|
||||
accountsManager.update(account.getAccountIdentifier(), a -> a.setAccountRecoveryPassword(recoveryPassword), additionalWriteItems);
|
||||
|
||||
return SetRegistrationRecoveryPasswordResponse.getDefaultInstance();
|
||||
}
|
||||
@@ -514,11 +572,240 @@ public class AccountsGrpcService extends SimpleAccountsGrpc.AccountsImplBase {
|
||||
return GetCapabilitiesResponse.newBuilder().setCapabilities(builder.build()).build();
|
||||
}
|
||||
|
||||
@Override
|
||||
public GenerateTotpKeyResponse generateTotpKey(final GenerateTotpKeyRequest request) {
|
||||
try {
|
||||
final Account account = getAuthenticatedAccount();
|
||||
if (account.getNumber().isPresent()) {
|
||||
throw GrpcExceptions.invalidArguments("TOTP keys may not be generated for an account with a number");
|
||||
}
|
||||
|
||||
final TotpKey pendingTotpKey =
|
||||
accountsManager.generatePendingTotpKey(AuthenticationUtil.requireAuthenticatedDevice().accountIdentifier());
|
||||
|
||||
return GenerateTotpKeyResponse.newBuilder()
|
||||
.setKeyGenerated(GenerateTotpKeyResponse.KeyGenerated.newBuilder()
|
||||
.setKey(ByteString.copyFrom(pendingTotpKey.getEncoded()))
|
||||
.setTotpParameters(toGrpcTotpParameters(pendingTotpKey.totpParameters()))
|
||||
.build())
|
||||
.build();
|
||||
} catch (final TooManyTotpKeysException _) {
|
||||
return GenerateTotpKeyResponse.newBuilder()
|
||||
.setTooManyTotpKeys(FailedPrecondition.getDefaultInstance())
|
||||
.build();
|
||||
} catch (final TooManyMfaKeysException _) {
|
||||
return GenerateTotpKeyResponse.newBuilder()
|
||||
.setTooManyMfaKeys(FailedPrecondition.getDefaultInstance())
|
||||
.build();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public ConfirmTotpKeyResponse confirmTotpKey(final ConfirmTotpKeyRequest request) {
|
||||
try {
|
||||
final Account account = getAuthenticatedAccount();
|
||||
if (account.getNumber().isPresent()) {
|
||||
throw GrpcExceptions.invalidArguments("TOTP keys may not be added to an account with a number");
|
||||
}
|
||||
|
||||
final Optional<Byte> maybeConfirmedTotpKeyId =
|
||||
accountsManager.confirmPendingTotpKey(
|
||||
AuthenticationUtil.requireAuthenticatedDevice().accountIdentifier(),
|
||||
request.getOneTimePassword(),
|
||||
clock.instant(),
|
||||
request.getMetadataCiphertext().toByteArray());
|
||||
|
||||
return maybeConfirmedTotpKeyId.map(keyId -> ConfirmTotpKeyResponse.newBuilder()
|
||||
.setKeyConfirmed(ConfirmTotpKeyResponse.KeyConfirmed.newBuilder()
|
||||
.setKeyId(keyId)
|
||||
.build())
|
||||
.build()).orElseGet(() -> ConfirmTotpKeyResponse.newBuilder()
|
||||
.setOneTimePasswordNotVerified(FailedPrecondition.getDefaultInstance())
|
||||
.build());
|
||||
} catch (TooManyMfaKeysException _) {
|
||||
return ConfirmTotpKeyResponse.newBuilder()
|
||||
.setTooManyMfaKeys(FailedPrecondition.getDefaultInstance())
|
||||
.build();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public StartWebAuthnRegistrationResponse startWebAuthnRegistration(final StartWebAuthnRegistrationRequest request) {
|
||||
|
||||
final Account account = getAuthenticatedAccount();
|
||||
if (account.getNumber().isPresent()) {
|
||||
throw GrpcExceptions.invalidArguments("WebAuthn keys may not be set for an account with a number");
|
||||
}
|
||||
|
||||
try {
|
||||
final RegistrationCeremonyParameters registrationParameters =
|
||||
accountsManager.startWebAuthnRegistration(AuthenticationUtil.requireAuthenticatedDevice().accountIdentifier());
|
||||
|
||||
return StartWebAuthnRegistrationResponse.newBuilder()
|
||||
.setParams(WebAuthnCreateParameters.newBuilder()
|
||||
.setUserHandle(ByteString.copyFrom(registrationParameters.userHandle()))
|
||||
.addAllAllowedAlgorithms(registrationParameters.allowedAlgorithms())
|
||||
.addAllExcludeCredentialIds(
|
||||
registrationParameters.excludedCredentialIds().stream().map(ByteString::copyFrom).toList()))
|
||||
.build();
|
||||
} catch (TooManyMfaKeysException _) {
|
||||
return StartWebAuthnRegistrationResponse.newBuilder()
|
||||
.setTooManyMfaKeys(FailedPrecondition.getDefaultInstance())
|
||||
.build();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public FinishWebAuthnRegistrationResponse finishWebAuthnRegistration(final FinishWebAuthnRegistrationRequest request) {
|
||||
final Account account = getAuthenticatedAccount();
|
||||
if (account.getNumber().isPresent()) {
|
||||
throw GrpcExceptions.invalidArguments("WebAuthn keys may not be set for an account with a number");
|
||||
}
|
||||
|
||||
try {
|
||||
final Optional<Byte> maybeKeyId = accountsManager.finishWebAuthnRegistration(
|
||||
AuthenticationUtil.requireAuthenticatedDevice().accountIdentifier(),
|
||||
request.getAttestationObject().toByteArray(),
|
||||
request.getCollectedClientDataJson(),
|
||||
request.getMetadataCiphertext().toByteArray());
|
||||
|
||||
return maybeKeyId.map(
|
||||
keyId -> FinishWebAuthnRegistrationResponse.newBuilder()
|
||||
.setKeyConfirmed(FinishWebAuthnRegistrationResponse.KeyConfirmed.newBuilder().setKeyId(keyId)))
|
||||
.orElseGet(() -> FinishWebAuthnRegistrationResponse.newBuilder().setKeyNotConfirmed(FailedPrecondition.getDefaultInstance()))
|
||||
.build();
|
||||
} catch (TooManyMfaKeysException _) {
|
||||
return FinishWebAuthnRegistrationResponse.newBuilder()
|
||||
.setTooManyMfaKeys(FailedPrecondition.getDefaultInstance())
|
||||
.build();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public ListMfaKeysResponse listMfaKeys(final ListMfaKeysRequest request) {
|
||||
final ListMfaKeysResponse.Builder responseBuilder = ListMfaKeysResponse.newBuilder();
|
||||
|
||||
getAuthenticatedAccount().getMfaKeys().forEach((keyId, mfaKey) -> {
|
||||
assert mfaKey.metadataCiphertext() != null;
|
||||
|
||||
responseBuilder.putKeys(
|
||||
keyId,
|
||||
ListMfaKeysResponse.MfaKeyMetadata.newBuilder()
|
||||
.setMetadataCiphertext(ByteString.copyFrom(mfaKey.metadataCiphertext()))
|
||||
.setType(switch (mfaKey) {
|
||||
case AnnotatedTotpKey _ -> MfaKeyType.MFA_KEY_TYPE_TOTP;
|
||||
case AnnotatedWebAuthnCredential _ -> MfaKeyType.MFA_KEY_TYPE_WEBAUTHN;
|
||||
}).build());
|
||||
});
|
||||
|
||||
return responseBuilder.build();
|
||||
}
|
||||
|
||||
@Override
|
||||
public SetMfaKeyMetadataResponse setMfaKeyMetadata(final SetMfaKeyMetadataRequest request) {
|
||||
final byte keyId = validateMfaKeyId(request.getKeyId());
|
||||
|
||||
try {
|
||||
accountsManager.update(AuthenticationUtil.requireAuthenticatedDevice().accountIdentifier(), account -> {
|
||||
final Map<Byte, AnnotatedMfaKey> mfaKeys = new HashMap<>(account.getMfaKeys());
|
||||
@Nullable final AnnotatedMfaKey existingKey = mfaKeys.get(keyId);
|
||||
|
||||
if (existingKey == null) {
|
||||
throw new MfaKeyNotFoundException();
|
||||
}
|
||||
|
||||
mfaKeys.put(keyId, existingKey.withMetadataCiphertext(request.getMetadataCiphertext().toByteArray()));
|
||||
|
||||
account.setMfaKeys(mfaKeys);
|
||||
});
|
||||
|
||||
return SetMfaKeyMetadataResponse.newBuilder()
|
||||
.setSuccess(SetMfaKeyMetadataResponse.MetadataUpdated.getDefaultInstance())
|
||||
.build();
|
||||
} catch (final MfaKeyNotFoundException _) {
|
||||
return SetMfaKeyMetadataResponse.newBuilder()
|
||||
.setKeyNotFound(NotFound.getDefaultInstance())
|
||||
.build();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public RemoveMfaKeyResponse removeMfaKey(final RemoveMfaKeyRequest request) {
|
||||
final byte keyId = validateMfaKeyId(request.getKeyId());
|
||||
|
||||
accountsManager.update(AuthenticationUtil.requireAuthenticatedDevice().accountIdentifier(), account -> {
|
||||
final Map<Byte, AnnotatedMfaKey> mfaKeys = new HashMap<>(account.getMfaKeys());
|
||||
mfaKeys.remove(keyId);
|
||||
|
||||
account.setMfaKeys(mfaKeys);
|
||||
});
|
||||
|
||||
return RemoveMfaKeyResponse.getDefaultInstance();
|
||||
}
|
||||
|
||||
@Override
|
||||
public StartMfaVerificationResponse startMfaVerification(final StartMfaVerificationRequest request) {
|
||||
final Account account = getAuthenticatedAccount();
|
||||
|
||||
final StartMfaVerificationResponse.Builder builder = StartMfaVerificationResponse.newBuilder()
|
||||
.setHasTotp(account.getMfaKeys().values().stream().anyMatch(AnnotatedTotpKey.class::isInstance));
|
||||
|
||||
accountsManager.startWebAuthnAuthentication(account)
|
||||
.map(AccountsGrpcService::toGrpcWebAuthnAuthenticationParameters)
|
||||
.ifPresent(builder::setWebauthnAuthenticationParameters);
|
||||
|
||||
return builder.build();
|
||||
}
|
||||
|
||||
@Override
|
||||
public FinishMfaVerificationResponse finishMfaVerification(final FinishMfaVerificationRequest request) throws RateLimitExceededException {
|
||||
rateLimiters.getCheckMfaLimiter().validate(AuthenticationUtil.requireAuthenticatedDevice().accountIdentifier());
|
||||
|
||||
final Account account = getAuthenticatedAccount();
|
||||
|
||||
final boolean success = switch (request.getCredentialCase()) {
|
||||
case TOTP_PASSWORD -> accountsManager.verifyTotp(account, clock.instant(), request.getTotpPassword());
|
||||
case WEBAUTHN_AUTHENTICATION_RESPONSE_JSON ->
|
||||
accountsManager.verifyWebAuthnAuthentication(account, request.getWebauthnAuthenticationResponseJson()).isPresent();
|
||||
case CREDENTIAL_NOT_SET -> false;
|
||||
};
|
||||
|
||||
return FinishMfaVerificationResponse.newBuilder().setSuccess(success).build();
|
||||
}
|
||||
|
||||
private byte validateMfaKeyId(final int keyId) {
|
||||
if (keyId < 0 || keyId > Account.MAX_MFA_KEY_ID) {
|
||||
throw GrpcExceptions.invalidArguments("MFA key ID out of range");
|
||||
}
|
||||
|
||||
return (byte) keyId;
|
||||
}
|
||||
|
||||
private static TotpParameters toGrpcTotpParameters(final org.whispersystems.textsecuregcm.storage.TotpParameters totpParameters) {
|
||||
return TotpParameters.newBuilder()
|
||||
.setAlgorithm(totpParameters.algorithm())
|
||||
.setPasswordLength(totpParameters.passwordLength())
|
||||
.setTimeStepSeconds(Math.toIntExact(totpParameters.timeStep().toSeconds()))
|
||||
.build();
|
||||
}
|
||||
|
||||
private static WebAuthnAuthenticationParameters toGrpcWebAuthnAuthenticationParameters(final AuthenticationCeremonyParameters parameters) {
|
||||
return WebAuthnAuthenticationParameters.newBuilder()
|
||||
.setChallenge(ByteString.copyFrom(parameters.challenge()))
|
||||
.setTimeoutSeconds((int) parameters.timeout().toSeconds())
|
||||
.addAllAllowedCredentialIds(parameters.allowedCredentialIds().stream().map(ByteString::copyFrom).toList())
|
||||
.build();
|
||||
}
|
||||
|
||||
private static AccountIdentifiers buildAccountIdentifiers(final Account account) {
|
||||
final AccountIdentifiers.Builder accountIdentifiersBuilder = AccountIdentifiers.newBuilder()
|
||||
.addServiceIdentifiers(GrpcServiceIdentifierUtil.toGrpcServiceIdentifier(new AciServiceIdentifier(account.getAccountIdentifier())))
|
||||
.addServiceIdentifiers(GrpcServiceIdentifierUtil.toGrpcServiceIdentifier(new PniServiceIdentifier(account.getPhoneNumberIdentifier())))
|
||||
.setE164(account.getNumber());
|
||||
.addServiceIdentifiers(GrpcServiceIdentifierUtil.toGrpcServiceIdentifier(new AciServiceIdentifier(account.getAccountIdentifier())));
|
||||
|
||||
account.getPhoneNumberIdentifier()
|
||||
.map(phoneNumberIdentifier -> GrpcServiceIdentifierUtil.toGrpcServiceIdentifier(new PniServiceIdentifier(phoneNumberIdentifier)))
|
||||
.ifPresent(accountIdentifiersBuilder::addServiceIdentifiers);
|
||||
|
||||
account.getNumber().ifPresent(accountIdentifiersBuilder::setE164);
|
||||
|
||||
account.getUsernameHash().ifPresent(usernameHash ->
|
||||
accountIdentifiersBuilder.setUsernameHash(ByteString.copyFrom(usernameHash)));
|
||||
@@ -560,7 +847,7 @@ public class AccountsGrpcService extends SimpleAccountsGrpc.AccountsImplBase {
|
||||
}
|
||||
|
||||
private static StatusRuntimeException invalidSignatureException(final String fieldName) {
|
||||
return GrpcExceptions.fieldViolation(fieldName, "pre-key signature did not match PNI identity key");
|
||||
return GrpcExceptions.fieldViolation(fieldName, "pre-key signature did not match PNI identity key");
|
||||
}
|
||||
|
||||
private static <T, U> Map<Byte, U> transformDeviceMap(final Map<Integer, T> byDeviceId, final Function<T, U> f) {
|
||||
|
||||
+1
-1
@@ -265,7 +265,7 @@ public class BackupsAnonymousGrpcService extends SimpleBackupsAnonymousGrpc.Back
|
||||
final BackupManager.ListMediaResult listResult = backupManager.list(
|
||||
backupUser,
|
||||
request.hasCursor() ? Optional.of(request.getCursor()) : Optional.empty(),
|
||||
request.getLimit());
|
||||
request.hasLimit() ? Optional.of(request.getLimit()) : Optional.empty());
|
||||
final ListMediaResponse.ListResult.Builder builder = ListMediaResponse.ListResult.newBuilder();
|
||||
for (BackupManager.StorageDescriptorWithLength sd : listResult.media()) {
|
||||
builder.addPage(ListMediaResponse.ListEntry.newBuilder()
|
||||
|
||||
@@ -16,6 +16,7 @@ import java.util.Optional;
|
||||
import java.util.stream.Collectors;
|
||||
import org.signal.chat.backup.GetBackupAuthCredentialsRequest;
|
||||
import org.signal.chat.backup.GetBackupAuthCredentialsResponse;
|
||||
import org.signal.chat.backup.GetBackupIdLimitsResponse;
|
||||
import org.signal.chat.backup.RedeemReceiptRequest;
|
||||
import org.signal.chat.backup.RedeemReceiptResponse;
|
||||
import org.signal.chat.backup.SetBackupIdRequest;
|
||||
@@ -138,6 +139,16 @@ public class BackupsGrpcService extends SimpleBackupsGrpc.BackupsImplBase {
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public GetBackupIdLimitsResponse getBackupIdLimits(final Empty request) {
|
||||
final Account account = authenticatedAccount();
|
||||
final BackupAuthManager.BackupIdRotationLimit limit = backupAuthManager.checkBackupIdRotationLimit(account);
|
||||
return GetBackupIdLimitsResponse.newBuilder()
|
||||
.setHasPermitsRemaining(limit.hasPermitsRemaining())
|
||||
.setRetryAfterSeconds(limit.nextPermitAvailable().getSeconds())
|
||||
.build();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Throwable mapException(final Throwable throwable) {
|
||||
return switch (throwable) {
|
||||
|
||||
+45
-11
@@ -1,14 +1,18 @@
|
||||
package org.whispersystems.textsecuregcm.grpc;
|
||||
|
||||
import java.io.IOException;
|
||||
import com.google.protobuf.Empty;
|
||||
import org.signal.chat.challenge.AnswerChallengeRequest;
|
||||
import org.signal.chat.challenge.AnswerChallengeResponse;
|
||||
import org.signal.chat.challenge.RequestPushChallengeRequest;
|
||||
import org.signal.chat.challenge.RequestPushChallengeResponse;
|
||||
import org.signal.chat.challenge.SimpleChallengeGrpc;
|
||||
import org.whispersystems.textsecuregcm.auth.grpc.AuthenticatedDevice;
|
||||
import org.signal.chat.errors.FailedPrecondition;
|
||||
import org.whispersystems.textsecuregcm.auth.grpc.AuthenticationUtil;
|
||||
import org.whispersystems.textsecuregcm.captcha.InvalidCaptchaArgumentException;
|
||||
import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimitChallengeManager;
|
||||
import org.whispersystems.textsecuregcm.push.NotPushRegisteredException;
|
||||
import org.whispersystems.textsecuregcm.spam.ChallengeConstraintChecker;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountsManager;
|
||||
@@ -28,19 +32,21 @@ public class ChallengeGrpcService extends SimpleChallengeGrpc.ChallengeImplBase
|
||||
}
|
||||
|
||||
@Override
|
||||
public AnswerChallengeResponse handleChallengeResponse(final AnswerChallengeRequest request)
|
||||
public AnswerChallengeResponse answerChallenge(final AnswerChallengeRequest request)
|
||||
throws RateLimitExceededException, IOException {
|
||||
|
||||
final AuthenticatedDevice authenticatedDevice = AuthenticationUtil.requireAuthenticatedDevice();
|
||||
final Account account = accountsManager.getByAccountIdentifier(authenticatedDevice.accountIdentifier())
|
||||
.orElseThrow(() -> GrpcExceptions.invalidCredentials("invalid credentials"));
|
||||
|
||||
final ChallengeConstraintChecker.ChallengeConstraints constraints = challengeConstraintChecker.challengeConstraintsGrpc(
|
||||
account);
|
||||
final Account account = requireAuthenticatedAccount();
|
||||
final ChallengeConstraintChecker.ChallengeConstraints constraints =
|
||||
challengeConstraintChecker.challengeConstraintsGrpc(account);
|
||||
|
||||
final boolean success = switch (request.getRequestCase()) {
|
||||
case PUSH -> constraints.pushPermitted() && rateLimitChallengeManager.answerPushChallenge(account,
|
||||
request.getPush().getChallenge());
|
||||
case PUSH -> {
|
||||
if (!constraints.pushPermitted()) {
|
||||
throw GrpcExceptions.rateLimitExceeded(null);
|
||||
}
|
||||
|
||||
yield rateLimitChallengeManager.answerPushChallenge(account, request.getPush().getChallenge());
|
||||
}
|
||||
case CAPTCHA -> {
|
||||
try {
|
||||
yield rateLimitChallengeManager.answerCaptchaChallenge(
|
||||
@@ -49,7 +55,7 @@ public class ChallengeGrpcService extends SimpleChallengeGrpc.ChallengeImplBase
|
||||
RequestAttributesUtil.getRemoteAddress().getHostAddress(),
|
||||
RequestAttributesUtil.getUserAgent().orElse(null),
|
||||
constraints.captchaScoreThreshold());
|
||||
} catch (InvalidCaptchaArgumentException e) {
|
||||
} catch (final InvalidCaptchaArgumentException e) {
|
||||
throw GrpcExceptions.invalidArguments(e.getMessage());
|
||||
}
|
||||
}
|
||||
@@ -60,4 +66,32 @@ public class ChallengeGrpcService extends SimpleChallengeGrpc.ChallengeImplBase
|
||||
.setSuccess(success)
|
||||
.build();
|
||||
}
|
||||
|
||||
@Override
|
||||
public RequestPushChallengeResponse requestPushChallenge(final RequestPushChallengeRequest request) {
|
||||
final Account account = requireAuthenticatedAccount();
|
||||
final ChallengeConstraintChecker.ChallengeConstraints constraints =
|
||||
challengeConstraintChecker.challengeConstraintsGrpc(account);
|
||||
|
||||
if (!constraints.pushPermitted()) {
|
||||
throw GrpcExceptions.rateLimitExceeded(null);
|
||||
}
|
||||
|
||||
try {
|
||||
rateLimitChallengeManager.sendPushChallenge(account);
|
||||
} catch (NotPushRegisteredException _) {
|
||||
return RequestPushChallengeResponse.newBuilder()
|
||||
.setNoPushToken(FailedPrecondition.getDefaultInstance())
|
||||
.build();
|
||||
}
|
||||
|
||||
return RequestPushChallengeResponse.newBuilder()
|
||||
.setSentPushChallenge(Empty.getDefaultInstance())
|
||||
.build();
|
||||
}
|
||||
|
||||
private Account requireAuthenticatedAccount() {
|
||||
return accountsManager.getByAccountIdentifier(AuthenticationUtil.requireAuthenticatedDevice().accountIdentifier())
|
||||
.orElseThrow(() -> GrpcExceptions.invalidCredentials("invalid credentials"));
|
||||
}
|
||||
}
|
||||
+34
-20
@@ -10,10 +10,12 @@ import java.time.Clock;
|
||||
import java.time.Instant;
|
||||
import java.time.temporal.ChronoUnit;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import org.signal.chat.common.ZkCredential;
|
||||
import org.signal.chat.credentials.ExternalServiceType;
|
||||
import org.signal.chat.credentials.GetCreateCallLinkCredentialsRequest;
|
||||
import org.signal.chat.credentials.GetCreateCallLinkCredentialsResponse;
|
||||
import org.signal.chat.credentials.GetCreateCallLinkCredentialRequest;
|
||||
import org.signal.chat.credentials.GetCreateCallLinkCredentialResponse;
|
||||
import org.signal.chat.credentials.GetDeliveryCertificateRequest;
|
||||
import org.signal.chat.credentials.GetDeliveryCertificateResponse;
|
||||
import org.signal.chat.credentials.GetExternalServiceCredentialsRequest;
|
||||
@@ -24,6 +26,7 @@ import org.signal.chat.credentials.SimpleCredentialsGrpc;
|
||||
import org.signal.libsignal.protocol.ServiceId;
|
||||
import org.signal.libsignal.zkgroup.GenericServerSecretParams;
|
||||
import org.signal.libsignal.zkgroup.InvalidInputException;
|
||||
import org.signal.libsignal.zkgroup.auth.AuthCredentialWithPniResponse;
|
||||
import org.signal.libsignal.zkgroup.auth.ServerZkAuthOperations;
|
||||
import org.signal.libsignal.zkgroup.calllinks.CallLinkAuthCredentialResponse;
|
||||
import org.signal.libsignal.zkgroup.calllinks.CreateCallLinkCredentialRequest;
|
||||
@@ -34,7 +37,6 @@ import org.whispersystems.textsecuregcm.auth.RedemptionRange;
|
||||
import org.whispersystems.textsecuregcm.auth.grpc.AuthenticatedDevice;
|
||||
import org.whispersystems.textsecuregcm.auth.grpc.AuthenticationUtil;
|
||||
import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
|
||||
import org.whispersystems.textsecuregcm.identity.IdentityType;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimiters;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountsManager;
|
||||
@@ -93,12 +95,16 @@ public class CredentialsGrpcService extends SimpleCredentialsGrpc.CredentialsImp
|
||||
final Account account = accountsManager.getByAccountIdentifier(authenticatedDevice.accountIdentifier())
|
||||
.orElseThrow(() -> GrpcExceptions.invalidCredentials("invalid credentials"));
|
||||
|
||||
return GetDeliveryCertificateResponse.newBuilder()
|
||||
.setCertificateWithE164(ByteString.copyFrom(
|
||||
certificateGenerator.createFor(account, authenticatedDevice.deviceId(), true)))
|
||||
final GetDeliveryCertificateResponse.Builder responseBuilder = GetDeliveryCertificateResponse.newBuilder()
|
||||
.setCertificateWithoutE164(ByteString.copyFrom(
|
||||
certificateGenerator.createFor(account, authenticatedDevice.deviceId(), false)))
|
||||
.build();
|
||||
certificateGenerator.createFor(account, authenticatedDevice.deviceId(), false)));
|
||||
|
||||
if (account.getNumber().isPresent()) {
|
||||
responseBuilder.setCertificateWithE164(ByteString.copyFrom(
|
||||
certificateGenerator.createFor(account, authenticatedDevice.deviceId(), true)));
|
||||
}
|
||||
|
||||
return responseBuilder.build();
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -117,21 +123,30 @@ public class CredentialsGrpcService extends SimpleCredentialsGrpc.CredentialsImp
|
||||
accountsManager.getByAccountIdentifier(AuthenticationUtil.requireAuthenticatedDevice().accountIdentifier())
|
||||
.orElseThrow(() -> GrpcExceptions.invalidCredentials("invalid credentials"));
|
||||
|
||||
final ServiceId.Aci aci = new ServiceId.Aci(account.getIdentifier(IdentityType.ACI));
|
||||
final ServiceId.Pni pni = new ServiceId.Pni(account.getIdentifier(IdentityType.PNI));
|
||||
final ServiceId.Aci aci = new ServiceId.Aci(account.getAccountIdentifier());
|
||||
final Optional<ServiceId.Pni> maybePni = account.getPhoneNumberIdentifier().map(ServiceId.Pni::new);
|
||||
|
||||
final GetGroupCredentialsResponse.Builder responseBuilder = GetGroupCredentialsResponse.newBuilder()
|
||||
.setPni(UUIDUtil.toByteString(pni.getRawUUID()));
|
||||
final GetGroupCredentialsResponse.Builder responseBuilder = GetGroupCredentialsResponse.newBuilder();
|
||||
|
||||
maybePni.ifPresent(pni -> responseBuilder.setPni(UUIDUtil.toByteString(pni.getRawUUID())));
|
||||
|
||||
for (final Instant redemption : redemptionRange) {
|
||||
responseBuilder.addGroupCredentials(GetGroupCredentialsResponse.CredentialAndRedemptionTime.newBuilder()
|
||||
.setRedemptionTimeSeconds(redemption.getEpochSecond())
|
||||
final AuthCredentialWithPniResponse authCredentialWithPniResponse =
|
||||
maybePni.map(pni ->
|
||||
serverZkAuthOperations.issueAuthCredentialWithPniZkc(aci, pni, redemption))
|
||||
.orElseGet(() -> serverZkAuthOperations.issueAuthCredentialZkcWithoutPni(aci,
|
||||
account.getAuthCredentialSalt()
|
||||
.orElseThrow(
|
||||
() -> new IllegalStateException("account without PNI must have auth credential salt")),
|
||||
redemption));
|
||||
responseBuilder.addGroupCredentials(ZkCredential.newBuilder()
|
||||
.setRedemptionTime(redemption.getEpochSecond())
|
||||
.setCredential(ByteString.copyFrom(
|
||||
serverZkAuthOperations.issueAuthCredentialWithPniZkc(aci, pni, redemption).serialize()))
|
||||
authCredentialWithPniResponse.serialize()))
|
||||
.build());
|
||||
|
||||
responseBuilder.addCallLinkAuthCredentials(GetGroupCredentialsResponse.CredentialAndRedemptionTime.newBuilder()
|
||||
.setRedemptionTimeSeconds(redemption.getEpochSecond())
|
||||
responseBuilder.addCallLinkAuthCredentials(ZkCredential.newBuilder()
|
||||
.setRedemptionTime(redemption.getEpochSecond())
|
||||
.setCredential(ByteString.copyFrom(
|
||||
CallLinkAuthCredentialResponse.issueCredential(aci, redemption, serverSecretParams).serialize()))
|
||||
.build());
|
||||
@@ -141,7 +156,7 @@ public class CredentialsGrpcService extends SimpleCredentialsGrpc.CredentialsImp
|
||||
}
|
||||
|
||||
@Override
|
||||
public GetCreateCallLinkCredentialsResponse getCreateCallLinkCredentials(final GetCreateCallLinkCredentialsRequest request)
|
||||
public GetCreateCallLinkCredentialResponse getCreateCallLinkCredential(final GetCreateCallLinkCredentialRequest request)
|
||||
throws RateLimitExceededException {
|
||||
|
||||
final UUID accountIdentifier = AuthenticationUtil.requireAuthenticatedDevice().accountIdentifier();
|
||||
@@ -153,8 +168,7 @@ public class CredentialsGrpcService extends SimpleCredentialsGrpc.CredentialsImp
|
||||
final CreateCallLinkCredentialRequest createCallLinkCredentialRequest =
|
||||
new CreateCallLinkCredentialRequest(request.getCredentialRequest().toByteArray());
|
||||
|
||||
return GetCreateCallLinkCredentialsResponse.newBuilder()
|
||||
.setRedemptionTimeSeconds(truncatedDayTimestamp.getEpochSecond())
|
||||
return GetCreateCallLinkCredentialResponse.newBuilder()
|
||||
.setCredential(ByteString.copyFrom(createCallLinkCredentialRequest.issueCredential(
|
||||
new ServiceId.Aci(accountIdentifier),
|
||||
truncatedDayTimestamp,
|
||||
|
||||
@@ -20,6 +20,7 @@ public class DeviceCapabilityUtil {
|
||||
case DEVICE_CAPABILITY_SPARSE_POST_QUANTUM_RATCHET -> DeviceCapability.SPARSE_POST_QUANTUM_RATCHET;
|
||||
case DEVICE_CAPABILITY_PROFILES_V2 -> DeviceCapability.PROFILES_V2;
|
||||
case DEVICE_CAPABILITY_USERNAME_CHANGE_SYNC_MESSAGE -> DeviceCapability.USERNAME_CHANGE_SYNC_MESSAGE;
|
||||
case DEVICE_CAPABILITY_OPTIONAL_PHONE_NUMBER -> DeviceCapability.OPTIONAL_PHONE_NUMBER;
|
||||
case DEVICE_CAPABILITY_UNSPECIFIED, UNRECOGNIZED ->
|
||||
throw GrpcExceptions.invalidArguments("unrecognized device capability");
|
||||
};
|
||||
@@ -33,6 +34,7 @@ public class DeviceCapabilityUtil {
|
||||
case SPARSE_POST_QUANTUM_RATCHET -> org.signal.chat.common.DeviceCapability.DEVICE_CAPABILITY_SPARSE_POST_QUANTUM_RATCHET;
|
||||
case PROFILES_V2 -> org.signal.chat.common.DeviceCapability.DEVICE_CAPABILITY_PROFILES_V2;
|
||||
case USERNAME_CHANGE_SYNC_MESSAGE -> org.signal.chat.common.DeviceCapability.DEVICE_CAPABILITY_USERNAME_CHANGE_SYNC_MESSAGE;
|
||||
case OPTIONAL_PHONE_NUMBER -> org.signal.chat.common.DeviceCapability.DEVICE_CAPABILITY_OPTIONAL_PHONE_NUMBER;
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -54,7 +54,7 @@ public class DevicesGrpcService extends SimpleDevicesGrpc.DevicesImplBase {
|
||||
GetDevicesResponse.LinkedDevice.newBuilder()
|
||||
.setId(device.getId())
|
||||
.setLastSeen(device.getLastSeen())
|
||||
.setRegistrationId(device.getRegistrationId(IdentityType.ACI))
|
||||
.setRegistrationId(device.getAccountRegistrationId())
|
||||
.setCreatedAtCiphertext(ByteString.copyFrom(device.getCreatedAtCiphertext()));
|
||||
|
||||
if (device.getName() != null) {
|
||||
@@ -104,7 +104,7 @@ public class DevicesGrpcService extends SimpleDevicesGrpc.DevicesImplBase {
|
||||
return SetDeviceNameResponse.newBuilder().setTargetDeviceNotFound(NotFound.getDefaultInstance()).build();
|
||||
}
|
||||
|
||||
accountsManager.updateDevice(account.getIdentifier(IdentityType.ACI), deviceId, device -> device.setName(request.getName().toByteArray()));
|
||||
accountsManager.updateDevice(account.getAccountIdentifier(), deviceId, device -> device.setName(request.getName().toByteArray()));
|
||||
|
||||
return SetDeviceNameResponse.newBuilder().setSuccess(Empty.getDefaultInstance()).build();
|
||||
}
|
||||
@@ -141,7 +141,7 @@ public class DevicesGrpcService extends SimpleDevicesGrpc.DevicesImplBase {
|
||||
// Unlike FCM tokens, we need current "last updated" timestamps for APNs tokens and so update device records
|
||||
// unconditionally if it's an APNS request
|
||||
if (request.hasApnsTokenRequest() || !Objects.equals(device.getGcmId(), fcmToken)) {
|
||||
accountsManager.updateDevice(account.getIdentifier(IdentityType.ACI), authenticatedDevice.deviceId(), d -> {
|
||||
accountsManager.updateDevice(account.getAccountIdentifier(), authenticatedDevice.deviceId(), d -> {
|
||||
d.setApnId(apnsToken);
|
||||
d.setGcmId(fcmToken);
|
||||
d.setFetchesMessages(false);
|
||||
|
||||
+6
-2
@@ -29,6 +29,7 @@ import org.whispersystems.textsecuregcm.storage.AccountsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.DonationPermitsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.RedeemedReceiptsManager;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.ReceiptCredentialPresentationFactory;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.ReceiptLevel;
|
||||
|
||||
public class DonationsGrpcService extends SimpleDonationsGrpc.DonationsImplBase {
|
||||
|
||||
@@ -73,14 +74,17 @@ public class DonationsGrpcService extends SimpleDonationsGrpc.DonationsImplBase
|
||||
final ReceiptSerial receiptSerial = receiptCredentialPresentation.getReceiptSerial();
|
||||
final Instant receiptExpiration = Instant.ofEpochSecond(receiptCredentialPresentation.getReceiptExpirationTime());
|
||||
final long receiptLevel = receiptCredentialPresentation.getReceiptLevel();
|
||||
final String badgeId = badgesConfiguration.getReceiptLevels().get(receiptLevel);
|
||||
final String badgeId = ReceiptLevel
|
||||
.lookupLevel(receiptLevel)
|
||||
.map(badgesConfiguration.getReceiptLevels()::get)
|
||||
.orElse(null);
|
||||
if (badgeId == null) {
|
||||
// Since the receipt presentation checked out, the server messed up because it doesn't recognize a receipt level it previously issued.
|
||||
LOGGER.error("Server doesn't recognize previously issued receipt level; please check badgesConfiguration for issues");
|
||||
throw GrpcExceptions.unavailable("server does not recognize the requested receipt level");
|
||||
}
|
||||
final boolean receiptMatched = redeemedReceiptsManager.put(
|
||||
receiptSerial, receiptExpiration.getEpochSecond(), receiptLevel, authenticatedDevice.accountIdentifier());
|
||||
receiptSerial, receiptExpiration, receiptLevel, authenticatedDevice.accountIdentifier());
|
||||
if (!receiptMatched) {
|
||||
return RedeemReceiptResponse.newBuilder()
|
||||
.setAlreadyRedeemed(FailedPrecondition.newBuilder()
|
||||
|
||||
+8
-6
@@ -12,12 +12,13 @@ import io.grpc.ServerCallHandler;
|
||||
import io.grpc.ServerInterceptor;
|
||||
import io.grpc.Status;
|
||||
import io.grpc.StatusRuntimeException;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.util.ExceptionUtils;
|
||||
import org.whispersystems.textsecuregcm.util.logging.ImpossibleEvents;
|
||||
import java.io.IOException;
|
||||
import java.io.UncheckedIOException;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountNotFoundException;
|
||||
import org.whispersystems.textsecuregcm.util.ExceptionUtils;
|
||||
import org.whispersystems.textsecuregcm.util.logging.ImpossibleEvents;
|
||||
|
||||
/**
|
||||
* This interceptor observes responses from the service and if the response status is {@link Status#UNKNOWN}
|
||||
@@ -52,6 +53,7 @@ public class ErrorMappingInterceptor implements ServerInterceptor {
|
||||
|
||||
final StatusRuntimeException statusException = switch (cause) {
|
||||
case ConvertibleToGrpcStatus e -> e.toStatusRuntimeException();
|
||||
case AccountNotFoundException _ -> GrpcExceptions.invalidCredentials("invalid credentials");
|
||||
case UncheckedIOException e -> {
|
||||
log.warn("RPC {} encountered UncheckedIOException", call.getMethodDescriptor().getFullMethodName(), e.getCause());
|
||||
yield GrpcExceptions.unavailable();
|
||||
@@ -62,7 +64,7 @@ public class ErrorMappingInterceptor implements ServerInterceptor {
|
||||
}
|
||||
case IllegalStateException e -> {
|
||||
ImpossibleEvents.logImpossible(log, e.getMessage(), e);
|
||||
yield GrpcExceptions.unavailable(e.getMessage());
|
||||
yield GrpcExceptions.unavailable();
|
||||
}
|
||||
case null -> {
|
||||
log.error("RPC {} finished with status UNKNOWN: {}",
|
||||
@@ -72,7 +74,7 @@ public class ErrorMappingInterceptor implements ServerInterceptor {
|
||||
default -> {
|
||||
log.error("RPC {} finished with status UNKNOWN",
|
||||
call.getMethodDescriptor().getFullMethodName(), status.getCause());
|
||||
yield GrpcExceptions.unavailable(status.getCause().getMessage());
|
||||
yield GrpcExceptions.unavailable();
|
||||
}
|
||||
};
|
||||
super.close(statusException.getStatus(), statusException.getTrailers());
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
/*
|
||||
* Copyright 2026 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.grpc;
|
||||
|
||||
import com.google.protobuf.InvalidProtocolBufferException;
|
||||
import com.google.rpc.ErrorInfo;
|
||||
import java.io.UncheckedIOException;
|
||||
import java.util.Optional;
|
||||
|
||||
public class ErrorUtil {
|
||||
public static Optional<ErrorInfo> errorInfo(final com.google.rpc.Status statusProto) {
|
||||
return statusProto.getDetailsList().stream()
|
||||
.filter(any -> any.is(ErrorInfo.class))
|
||||
.map(errorInfo -> {
|
||||
try {
|
||||
return errorInfo.unpack(ErrorInfo.class);
|
||||
} catch (final InvalidProtocolBufferException e) {
|
||||
throw new UncheckedIOException(e);
|
||||
}
|
||||
})
|
||||
.findFirst();
|
||||
}
|
||||
}
|
||||
+2
-1
@@ -18,6 +18,7 @@ import org.whispersystems.textsecuregcm.WhisperServerConfiguration;
|
||||
import org.whispersystems.textsecuregcm.auth.ExternalServiceCredentialsGenerator;
|
||||
import org.whispersystems.textsecuregcm.configuration.DirectoryV2ClientConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.PaymentsServiceConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.SecureStorageServiceConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.SecureValueRecoveryConfiguration;
|
||||
|
||||
public enum ExternalServiceDefinitions {
|
||||
@@ -48,7 +49,7 @@ public enum ExternalServiceDefinitions {
|
||||
.build();
|
||||
}),
|
||||
STORAGE(ExternalServiceType.EXTERNAL_SERVICE_TYPE_STORAGE, (chatConfig, _) -> {
|
||||
final PaymentsServiceConfiguration cfg = chatConfig.getPaymentsServiceConfiguration();
|
||||
final SecureStorageServiceConfiguration cfg = chatConfig.getSecureStorageServiceConfiguration();
|
||||
return ExternalServiceCredentialsGenerator
|
||||
.builder(cfg.userAuthenticationTokenSharedSecret())
|
||||
.prependUsername(true)
|
||||
|
||||
+29
-8
@@ -6,22 +6,19 @@
|
||||
package org.whispersystems.textsecuregcm.grpc;
|
||||
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import io.grpc.Status;
|
||||
import org.signal.keytransparency.client.AciMonitorRequest;
|
||||
import org.signal.keytransparency.client.ConsistencyParameters;
|
||||
import com.google.protobuf.Any;
|
||||
import com.google.rpc.ErrorInfo;
|
||||
import com.google.rpc.Status;
|
||||
import io.grpc.StatusRuntimeException;
|
||||
import io.grpc.protobuf.StatusProto;
|
||||
import org.signal.keytransparency.client.DistinguishedRequest;
|
||||
import org.signal.keytransparency.client.DistinguishedResponse;
|
||||
import org.signal.keytransparency.client.E164MonitorRequest;
|
||||
import org.signal.keytransparency.client.E164SearchRequest;
|
||||
import org.signal.keytransparency.client.MonitorRequest;
|
||||
import org.signal.keytransparency.client.MonitorResponse;
|
||||
import org.signal.keytransparency.client.MonitorResponseV2;
|
||||
import org.signal.keytransparency.client.SearchRequest;
|
||||
import org.signal.keytransparency.client.SearchResponse;
|
||||
import org.signal.keytransparency.client.SearchResponseV2;
|
||||
import org.signal.keytransparency.client.SimpleKeyTransparencyQueryServiceGrpc;
|
||||
import org.signal.keytransparency.client.UsernameHashMonitorRequest;
|
||||
import org.whispersystems.textsecuregcm.controllers.AccountController;
|
||||
import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
|
||||
import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.keytransparency.KeyTransparencyServiceClient;
|
||||
@@ -88,4 +85,28 @@ public class KeyTransparencyGrpcService extends
|
||||
|
||||
return request;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Throwable mapException(final Throwable throwable) {
|
||||
// Reconstruct the exception so that we can override the backing service domain with chat's own domain.
|
||||
if (throwable instanceof StatusRuntimeException s) {
|
||||
final ErrorInfo.Builder errInfoBuilder = ErrorInfo.newBuilder()
|
||||
.setDomain(GrpcExceptions.DOMAIN);
|
||||
|
||||
final Status statusProto = StatusProto.fromStatusAndTrailers(s.getStatus(), s.getTrailers());
|
||||
|
||||
ErrorUtil.errorInfo(statusProto)
|
||||
.map(ErrorInfo::getReason)
|
||||
.ifPresent(errInfoBuilder::setReason);
|
||||
|
||||
return StatusProto.toStatusRuntimeException(Status.newBuilder()
|
||||
// See https://github.com/signalapp/key-transparency-server/blob/30b7a2a40604fbe04545d47f26e4c5a35f5d3161/cmd/kt-server/errors.go#L32
|
||||
// for a list of error codes that the key transparency service can generate.
|
||||
.setCode(statusProto.getCode())
|
||||
.setMessage(statusProto.getMessage())
|
||||
.addDetails(Any.pack(errInfoBuilder.build()))
|
||||
.build());
|
||||
}
|
||||
return throwable;
|
||||
}
|
||||
}
|
||||
+9
-5
@@ -10,6 +10,7 @@ import java.security.MessageDigest;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import java.time.Clock;
|
||||
import java.util.Arrays;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.Flow;
|
||||
import org.signal.chat.errors.FailedUnidentifiedAuthorization;
|
||||
import org.signal.chat.errors.NotFound;
|
||||
@@ -94,14 +95,17 @@ public class KeysAnonymousGrpcService extends SimpleKeysAnonymousGrpc.KeysAnonym
|
||||
request.getFingerprint().toByteArray()))
|
||||
.flatMap(serviceIdentifierAndFingerprint -> Mono.fromFuture(
|
||||
() -> accountsManager.getByServiceIdentifierAsync(serviceIdentifierAndFingerprint.getT1()))
|
||||
.map(maybeAccount -> maybeAccount.flatMap(
|
||||
account -> switch (serviceIdentifierAndFingerprint.getT1().identityType()) {
|
||||
case ACI -> Optional.of(account.getAccountIdentityKey());
|
||||
case PNI -> account.getPhoneNumberIdentityKey();
|
||||
}))
|
||||
.flatMap(Mono::justOrEmpty)
|
||||
.filter(account -> !fingerprintMatches(account.getIdentityKey(serviceIdentifierAndFingerprint.getT1()
|
||||
.identityType()), serviceIdentifierAndFingerprint.getT2()))
|
||||
.map(account -> CheckIdentityKeyResponse.newBuilder()
|
||||
.filter(identityKey -> !fingerprintMatches(identityKey, serviceIdentifierAndFingerprint.getT2()))
|
||||
.map(identityKey -> CheckIdentityKeyResponse.newBuilder()
|
||||
.setTargetIdentifier(
|
||||
GrpcServiceIdentifierUtil.toGrpcServiceIdentifier(serviceIdentifierAndFingerprint.getT1()))
|
||||
.setIdentityKey(ByteString.copyFrom(account.getIdentityKey(serviceIdentifierAndFingerprint.getT1()
|
||||
.identityType()).serialize()))
|
||||
.setIdentityKey(ByteString.copyFrom(identityKey.serialize()))
|
||||
.build())));
|
||||
}
|
||||
|
||||
|
||||
@@ -6,13 +6,12 @@
|
||||
package org.whispersystems.textsecuregcm.grpc;
|
||||
|
||||
import com.google.protobuf.ByteString;
|
||||
import java.util.Arrays;
|
||||
import io.grpc.StatusRuntimeException;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.Stream;
|
||||
import io.grpc.StatusRuntimeException;
|
||||
import org.signal.chat.common.EcPreKey;
|
||||
import org.signal.chat.common.EcSignedPreKey;
|
||||
import org.signal.chat.common.KemSignedPreKey;
|
||||
@@ -22,15 +21,14 @@ import org.signal.libsignal.protocol.IdentityKey;
|
||||
import org.signal.libsignal.protocol.InvalidKeyException;
|
||||
import org.signal.libsignal.protocol.ecc.ECPublicKey;
|
||||
import org.signal.libsignal.protocol.kem.KEMPublicKey;
|
||||
import org.whispersystems.textsecuregcm.auth.UnidentifiedAccessChecksum;
|
||||
import org.whispersystems.textsecuregcm.entities.ECPreKey;
|
||||
import org.whispersystems.textsecuregcm.entities.ECSignedPreKey;
|
||||
import org.whispersystems.textsecuregcm.entities.KEMSignedPreKey;
|
||||
import org.whispersystems.textsecuregcm.auth.UnidentifiedAccessChecksum;
|
||||
import org.whispersystems.textsecuregcm.identity.IdentityType;
|
||||
import org.whispersystems.textsecuregcm.identity.ServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.Device;
|
||||
import org.whispersystems.textsecuregcm.storage.DeviceCapability;
|
||||
import org.whispersystems.textsecuregcm.storage.KeyIdUtil;
|
||||
import org.whispersystems.textsecuregcm.storage.KeysManager;
|
||||
|
||||
@@ -74,8 +72,14 @@ class KeysGrpcHelper {
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
final IdentityKey identityKey = switch (targetServiceIdentifier.identityType()) {
|
||||
case ACI -> targetAccount.getAccountIdentityKey();
|
||||
case PNI -> targetAccount.getPhoneNumberIdentityKey()
|
||||
.orElseThrow(() -> new IllegalArgumentException("Target account does not have a PNI identity key"));
|
||||
};
|
||||
|
||||
final AccountPreKeyBundles.Builder preKeyBundlesBuilder = AccountPreKeyBundles.newBuilder()
|
||||
.setIdentityKey(ByteString.copyFrom(targetAccount.getIdentityKey(targetServiceIdentifier.identityType()).serialize()))
|
||||
.setIdentityKey(ByteString.copyFrom(identityKey.serialize()))
|
||||
.setUnrestrictedUnidentifiedAccess(targetServiceIdentifier.identityType() == IdentityType.ACI && targetAccount.isUnrestrictedUnidentifiedAccess());
|
||||
|
||||
// Set the UAK hash if the account has a UAK and we're targeting an ACI. PNIs don't allow unidentified access.
|
||||
@@ -89,6 +93,11 @@ class KeysGrpcHelper {
|
||||
preKeysByDeviceId.forEach((deviceId, devicePreKeys) -> {
|
||||
final Device device = targetAccount.getDevice(deviceId).orElseThrow();
|
||||
|
||||
final int registrationId = switch (targetServiceIdentifier.identityType()) {
|
||||
case ACI -> device.getAccountRegistrationId();
|
||||
case PNI -> device.getPhoneNumberIdentityRegistrationId()
|
||||
.orElseThrow(() -> new IllegalArgumentException("Device does not have a PNI registration ID"));
|
||||
};
|
||||
|
||||
final DevicePreKeyBundle.Builder builder = DevicePreKeyBundle.newBuilder()
|
||||
.setEcSignedPreKey(EcSignedPreKey.newBuilder()
|
||||
@@ -99,7 +108,7 @@ class KeysGrpcHelper {
|
||||
.setKeyId(KeyIdUtil.toUnsignedInt(devicePreKeys.kemSignedPreKey().keyId()))
|
||||
.setPublicKey(ByteString.copyFrom(devicePreKeys.kemSignedPreKey().serializedPublicKey()))
|
||||
.setSignature(ByteString.copyFrom(devicePreKeys.kemSignedPreKey().signature())))
|
||||
.setRegistrationId(device.getRegistrationId(targetServiceIdentifier.identityType()));
|
||||
.setRegistrationId(registrationId);
|
||||
|
||||
devicePreKeys.ecPreKey().ifPresent(ecPreKey -> builder.setEcOneTimePreKey(EcPreKey.newBuilder()
|
||||
.setKeyId(KeyIdUtil.toUnsignedInt(ecPreKey.keyId()))
|
||||
|
||||
@@ -60,17 +60,21 @@ public class KeysGrpcService extends SimpleKeysGrpc.KeysImplBase {
|
||||
final AuthenticatedDevice authenticatedDevice = AuthenticationUtil.requireAuthenticatedDevice();
|
||||
final Account account = getAuthenticatedAccount(authenticatedDevice.accountIdentifier());
|
||||
|
||||
final CompletableFuture<Integer> aciEcKeyCountFuture =
|
||||
keysManager.getEcCount(account.getIdentifier(IdentityType.ACI), authenticatedDevice.deviceId());
|
||||
final UUID aci = account.getAccountIdentifier();
|
||||
|
||||
final CompletableFuture<Integer> pniEcKeyCountFuture =
|
||||
keysManager.getEcCount(account.getIdentifier(IdentityType.PNI), authenticatedDevice.deviceId());
|
||||
final CompletableFuture<Integer> aciEcKeyCountFuture =
|
||||
keysManager.getEcCount(aci, authenticatedDevice.deviceId());
|
||||
|
||||
final CompletableFuture<Integer> pniEcKeyCountFuture = account.getPhoneNumberIdentifier()
|
||||
.map(pni -> keysManager.getEcCount(pni, authenticatedDevice.deviceId()))
|
||||
.orElseGet(() -> CompletableFuture.completedFuture(0));
|
||||
|
||||
final CompletableFuture<Integer> aciKemKeyCountFuture =
|
||||
keysManager.getPqCount(account.getIdentifier(IdentityType.ACI), authenticatedDevice.deviceId());
|
||||
keysManager.getPqCount(aci, authenticatedDevice.deviceId());
|
||||
|
||||
final CompletableFuture<Integer> pniKemKeyCountFuture =
|
||||
keysManager.getPqCount(account.getIdentifier(IdentityType.PNI), authenticatedDevice.deviceId());
|
||||
final CompletableFuture<Integer> pniKemKeyCountFuture = account.getPhoneNumberIdentifier()
|
||||
.map(pni -> keysManager.getPqCount(pni, authenticatedDevice.deviceId()))
|
||||
.orElseGet(() -> CompletableFuture.completedFuture(0));
|
||||
|
||||
CompletableFuture.allOf(aciEcKeyCountFuture, pniEcKeyCountFuture, aciKemKeyCountFuture, pniKemKeyCountFuture).join();
|
||||
|
||||
@@ -99,7 +103,10 @@ public class KeysGrpcService extends SimpleKeysGrpc.KeysImplBase {
|
||||
final Optional<Integer> targetRegistrationId = maybeTargetAccount
|
||||
.filter(_ -> request.hasDeviceId())
|
||||
.flatMap(targetAccount -> targetAccount.getDevice(deviceId))
|
||||
.map(device -> device.getRegistrationId(targetIdentifier.identityType()));
|
||||
.flatMap(device -> switch (targetIdentifier.identityType()) {
|
||||
case ACI -> Optional.of(device.getAccountRegistrationId());
|
||||
case PNI -> device.getPhoneNumberIdentityRegistrationId();
|
||||
});
|
||||
|
||||
final String rateLimitKey = RateLimitKeys.preKeyLimiterKey(
|
||||
authenticatedDevice.accountIdentifier(),
|
||||
@@ -154,11 +161,19 @@ public class KeysGrpcService extends SimpleKeysGrpc.KeysImplBase {
|
||||
|
||||
final Account account = getAuthenticatedAccount(authenticatedAccountUuid);
|
||||
|
||||
final IdentityKey identityKey = switch (identityType) {
|
||||
case ACI -> account.getAccountIdentityKey();
|
||||
case PNI -> account.getPhoneNumberIdentityKey()
|
||||
.orElseThrow(() -> new IllegalArgumentException("Account does not have a PNI identity key"));
|
||||
};
|
||||
|
||||
final UUID identifier = getIdentifier(account, identityType);
|
||||
|
||||
final List<K> preKeys = requestPreKeys.stream()
|
||||
.map(requestPreKey -> extractPreKeyFunction.apply(requestPreKey, account.getIdentityKey(identityType)))
|
||||
.map(requestPreKey -> extractPreKeyFunction.apply(requestPreKey, identityKey))
|
||||
.toList();
|
||||
|
||||
storeKeysFunction.apply(account.getIdentifier(identityType), preKeys).join();
|
||||
storeKeysFunction.apply(identifier, preKeys).join();
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -166,15 +181,10 @@ public class KeysGrpcService extends SimpleKeysGrpc.KeysImplBase {
|
||||
final AuthenticatedDevice authenticatedDevice = AuthenticationUtil.requireAuthenticatedDevice();
|
||||
|
||||
storeRepeatedUseKey(authenticatedDevice.accountIdentifier(),
|
||||
request.getIdentityType(),
|
||||
IdentityTypeUtil.fromGrpcIdentityType(request.getIdentityType()),
|
||||
request.getSignedPreKey(),
|
||||
(preKey, identityKey) -> KeysGrpcHelper.checkEcSignedPreKey(preKey, identityKey, INVALID_PUBLIC_KEY_EXCEPTION, INVALID_SIGNATURE_EXCEPTION),
|
||||
(account, signedPreKey) -> {
|
||||
final IdentityType identityType = IdentityTypeUtil.fromGrpcIdentityType(request.getIdentityType());
|
||||
final UUID identifier = account.getIdentifier(identityType);
|
||||
|
||||
return keysManager.storeEcSignedPreKeys(identifier, authenticatedDevice.deviceId(), signedPreKey);
|
||||
});
|
||||
(identifier, signedPreKey) -> keysManager.storeEcSignedPreKeys(identifier, authenticatedDevice.deviceId(), signedPreKey));
|
||||
|
||||
return SetPreKeyResponse.getDefaultInstance();
|
||||
}
|
||||
@@ -184,36 +194,46 @@ public class KeysGrpcService extends SimpleKeysGrpc.KeysImplBase {
|
||||
final AuthenticatedDevice authenticatedDevice = AuthenticationUtil.requireAuthenticatedDevice();
|
||||
|
||||
storeRepeatedUseKey(authenticatedDevice.accountIdentifier(),
|
||||
request.getIdentityType(),
|
||||
IdentityTypeUtil.fromGrpcIdentityType(request.getIdentityType()),
|
||||
request.getSignedPreKey(),
|
||||
(preKey, identityKey) -> KeysGrpcHelper.checkKemSignedPreKey(preKey, identityKey, INVALID_PUBLIC_KEY_EXCEPTION, INVALID_SIGNATURE_EXCEPTION),
|
||||
(account, lastResortKey) -> {
|
||||
final UUID identifier =
|
||||
account.getIdentifier(IdentityTypeUtil.fromGrpcIdentityType(request.getIdentityType()));
|
||||
|
||||
return keysManager.storePqLastResort(identifier, authenticatedDevice.deviceId(), lastResortKey);
|
||||
});
|
||||
(identifier, lastResortKey) -> keysManager.storePqLastResort(identifier, authenticatedDevice.deviceId(), lastResortKey));
|
||||
|
||||
return SetPreKeyResponse.getDefaultInstance();
|
||||
}
|
||||
|
||||
private <K, R> void storeRepeatedUseKey(final UUID authenticatedAccountUuid,
|
||||
final org.signal.chat.common.IdentityType identityType,
|
||||
final IdentityType identityType,
|
||||
final R storeKeyRequest,
|
||||
final BiFunction<R, IdentityKey, K> extractKeyFunction,
|
||||
final BiFunction<Account, K, CompletableFuture<Void>> storeKeyFunction) {
|
||||
final BiFunction<UUID, K, CompletableFuture<Void>> storeKeyFunction) {
|
||||
|
||||
final Account account = getAuthenticatedAccount(authenticatedAccountUuid);
|
||||
final IdentityKey identityKey = switch (identityType) {
|
||||
case ACI -> account.getAccountIdentityKey();
|
||||
case PNI -> account.getPhoneNumberIdentityKey()
|
||||
.orElseThrow(() -> GrpcExceptions.invalidArguments("account does not have a PNI identity key"));
|
||||
};
|
||||
|
||||
final IdentityKey identityKey = account.getIdentityKey(IdentityTypeUtil.fromGrpcIdentityType(identityType));
|
||||
final UUID identifier = getIdentifier(account, identityType);
|
||||
final K key = extractKeyFunction.apply(storeKeyRequest, identityKey);
|
||||
|
||||
storeKeyFunction.apply(account, key).join();
|
||||
storeKeyFunction.apply(identifier, key).join();
|
||||
}
|
||||
|
||||
|
||||
private Account getAuthenticatedAccount(final UUID authenticatedAccountId) {
|
||||
return accountsManager.getByAccountIdentifier(authenticatedAccountId)
|
||||
.orElseThrow(() -> GrpcExceptions.invalidCredentials("invalid credentials"));
|
||||
}
|
||||
|
||||
/// Get the identity of the requested `idenityType`, or throw an invalid arguments status if `account` does not
|
||||
/// contain that type.
|
||||
private static UUID getIdentifier(Account account, IdentityType identityType) {
|
||||
return switch (identityType) {
|
||||
case ACI -> account.getAccountIdentifier();
|
||||
case PNI -> account.getPhoneNumberIdentifier()
|
||||
.orElseThrow(() -> GrpcExceptions.invalidArguments("PNI identity type not allowed for an account without a phone number"));
|
||||
};
|
||||
}
|
||||
|
||||
}
|
||||
+97
@@ -0,0 +1,97 @@
|
||||
/*
|
||||
* Copyright 2026 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
package org.whispersystems.textsecuregcm.grpc;
|
||||
|
||||
import com.google.protobuf.ByteString;
|
||||
import java.io.IOException;
|
||||
import org.signal.chat.errors.FailedPrecondition;
|
||||
import org.signal.chat.errors.NotFound;
|
||||
import org.signal.chat.purchase.CreateLoginReceiptCredentialRequest;
|
||||
import org.signal.chat.purchase.CreateLoginReceiptCredentialResponse;
|
||||
import org.signal.chat.purchase.PaymentRequired;
|
||||
import org.signal.chat.purchase.SimpleLoginPurchaseGrpc;
|
||||
import org.signal.libsignal.zkgroup.InvalidInputException;
|
||||
import org.signal.libsignal.zkgroup.VerificationFailedException;
|
||||
import org.signal.libsignal.zkgroup.receipts.ReceiptCredentialRequest;
|
||||
import org.signal.libsignal.zkgroup.receipts.ReceiptCredentialResponse;
|
||||
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
|
||||
import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
|
||||
import org.whispersystems.textsecuregcm.storage.DynamicConfigurationManager;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.LoginPurchaseManager;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.PaymentProvider;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionChargeFailurePaymentRequiredException;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionInvalidArgumentsException;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionNotFoundException;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionPaymentRequiredException;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionReceiptAlreadyRedeemedException;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionReceiptRequestedForOpenPaymentException;
|
||||
|
||||
public class LoginPurchaseGrpcService extends SimpleLoginPurchaseGrpc.LoginPurchaseImplBase {
|
||||
|
||||
private final LoginPurchaseManager loginPurchaseManager;
|
||||
private final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager;
|
||||
|
||||
public LoginPurchaseGrpcService(
|
||||
final LoginPurchaseManager loginPurchaseManager,
|
||||
final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager) {
|
||||
this.loginPurchaseManager = loginPurchaseManager;
|
||||
this.dynamicConfigurationManager = dynamicConfigurationManager;
|
||||
}
|
||||
|
||||
@Override
|
||||
public CreateLoginReceiptCredentialResponse createLoginReceiptCredential(
|
||||
final CreateLoginReceiptCredentialRequest request) throws IOException, RateLimitExceededException {
|
||||
|
||||
if (!dynamicConfigurationManager.getConfiguration().getLoginPurchaseConfiguration().enabled()) {
|
||||
throw GrpcExceptions.invalidArguments("method not allowed");
|
||||
}
|
||||
|
||||
final PaymentProvider paymentProvider = PaymentProvider.fromProto(request.getProcessor())
|
||||
.orElseThrow(() -> GrpcExceptions.fieldViolation("payment_provider", "Unrecognized payment provider"));
|
||||
|
||||
final ReceiptCredentialRequest receiptCredentialRequest;
|
||||
try {
|
||||
receiptCredentialRequest = new ReceiptCredentialRequest(request.getReceiptCredentialRequest().toByteArray());
|
||||
} catch (final InvalidInputException e) {
|
||||
throw GrpcExceptions.fieldViolation("receipt_credential_request", "invalid receipt credential request");
|
||||
}
|
||||
|
||||
try {
|
||||
final ReceiptCredentialResponse receiptCredentialResponse = loginPurchaseManager.generateReceipt(
|
||||
paymentProvider, request.getPurchaseIdentifier(), receiptCredentialRequest);
|
||||
|
||||
return CreateLoginReceiptCredentialResponse.newBuilder()
|
||||
.setResult(CreateLoginReceiptCredentialResponse.CreateLoginReceiptCredentialResult.newBuilder()
|
||||
.setReceiptCredentialResponse(ByteString.copyFrom(receiptCredentialResponse.serialize())))
|
||||
.build();
|
||||
} catch (final SubscriptionReceiptRequestedForOpenPaymentException e) {
|
||||
return CreateLoginReceiptCredentialResponse.newBuilder()
|
||||
.setPaymentStillProcessing(FailedPrecondition.getDefaultInstance())
|
||||
.build();
|
||||
} catch (final SubscriptionChargeFailurePaymentRequiredException e) {
|
||||
return CreateLoginReceiptCredentialResponse.newBuilder()
|
||||
.setPaymentRequired(PaymentRequired.newBuilder()
|
||||
.setChargeFailure(SubscriptionsUtil.toChargeFailure(e.getProcessor(), e.getChargeFailure())))
|
||||
.build();
|
||||
} catch (final SubscriptionPaymentRequiredException e) {
|
||||
return CreateLoginReceiptCredentialResponse.newBuilder()
|
||||
.setPaymentRequired(PaymentRequired.getDefaultInstance())
|
||||
.build();
|
||||
} catch (final SubscriptionNotFoundException e) {
|
||||
return CreateLoginReceiptCredentialResponse.newBuilder()
|
||||
.setPaymentNotFound(NotFound.getDefaultInstance())
|
||||
.build();
|
||||
} catch (final SubscriptionReceiptAlreadyRedeemedException e) {
|
||||
return CreateLoginReceiptCredentialResponse.newBuilder()
|
||||
.setReceiptAlreadyIssued(FailedPrecondition.getDefaultInstance())
|
||||
.build();
|
||||
} catch (final SubscriptionInvalidArgumentsException e) {
|
||||
throw GrpcExceptions.invalidArguments(e.errorDetail().orElse(""));
|
||||
} catch (final VerificationFailedException e) {
|
||||
throw GrpcExceptions.fieldViolation("receipt_credential_request",
|
||||
"receipt credential request failed verification");
|
||||
}
|
||||
}
|
||||
}
|
||||
Loaded 100 of 367 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user