mirror of
https://github.com/signalapp/Signal-Server.git
synced 2026-12-01 02:46:47 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ed0a723fef | ||
|
|
5c31ef43c9 | ||
|
|
43fd8518c0 | ||
|
|
19a08f01e8 | ||
|
|
33498cf147 | ||
|
|
beeb85cf8d | ||
|
|
ccd860207b | ||
|
|
2c835b5c51 | ||
|
|
5caa951c61 | ||
|
|
4d8c4d6693 | ||
|
|
a9d0574ea8 | ||
|
|
3954494eae | ||
|
|
ed6a2c55eb | ||
|
|
b6ee074149 | ||
|
|
f6b3500e92 | ||
|
|
a71dc48b9b | ||
|
|
bc5eed48c3 | ||
|
|
2ecf3cb303 | ||
|
|
bed33d042a | ||
|
|
d7975626be | ||
|
|
3ac7aba6b2 | ||
|
|
1dde612855 | ||
|
|
4ec97cf006 | ||
|
|
d51c6fd2f8 | ||
|
|
d868e3075c | ||
|
|
ae61ee5486 | ||
|
|
58fd9ddb27 | ||
|
|
a953cb33b7 | ||
|
|
95b90e7c5a | ||
|
|
6a3ecb2881 | ||
|
|
6cf4241283 | ||
|
|
42141e51a1 | ||
|
|
b01945ff50 |
No files matched your search
@@ -117,7 +117,7 @@ public class TestUser {
|
||||
}
|
||||
|
||||
public AccountAttributes accountAttributes() {
|
||||
return new AccountAttributes(true, registrationId, "", "", true, new Device.DeviceCapabilities())
|
||||
return new AccountAttributes(true, registrationId, "", "", true, new Device.DeviceCapabilities(false, false, false, false))
|
||||
.withUnidentifiedAccessKey(unidentifiedAccessKey)
|
||||
.withRecoveryPassword(registrationPassword);
|
||||
}
|
||||
|
||||
@@ -243,6 +243,9 @@ recaptcha:
|
||||
hCaptcha:
|
||||
apiKey: secret://hCaptcha.apiKey
|
||||
|
||||
shortCode:
|
||||
baseUrl: https://example.com/shortcodes/
|
||||
|
||||
storageService:
|
||||
uri: storage.example.com
|
||||
userAuthenticationTokenSharedSecret: secret://storageService.userAuthenticationTokenSharedSecret
|
||||
|
||||
+10
@@ -50,6 +50,7 @@ import org.whispersystems.textsecuregcm.configuration.ReportMessageConfiguration
|
||||
import org.whispersystems.textsecuregcm.configuration.SecureBackupServiceConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.SecureStorageServiceConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.SecureValueRecovery2Configuration;
|
||||
import org.whispersystems.textsecuregcm.configuration.ShortCodeExpanderConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.SpamFilterConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.StripeConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.SubscriptionConfiguration;
|
||||
@@ -202,6 +203,11 @@ public class WhisperServerConfiguration extends Configuration {
|
||||
@JsonProperty
|
||||
private HCaptchaConfiguration hCaptcha;
|
||||
|
||||
@Valid
|
||||
@NotNull
|
||||
@JsonProperty
|
||||
private ShortCodeExpanderConfiguration shortCode;
|
||||
|
||||
@Valid
|
||||
@NotNull
|
||||
@JsonProperty
|
||||
@@ -334,6 +340,10 @@ public class WhisperServerConfiguration extends Configuration {
|
||||
return hCaptcha;
|
||||
}
|
||||
|
||||
public ShortCodeExpanderConfiguration getShortCodeRetrieverConfiguration() {
|
||||
return shortCode;
|
||||
}
|
||||
|
||||
public WebSocketConfiguration getWebSocketConfiguration() {
|
||||
return webSocket;
|
||||
}
|
||||
|
||||
@@ -83,6 +83,7 @@ import org.whispersystems.textsecuregcm.captcha.CaptchaChecker;
|
||||
import org.whispersystems.textsecuregcm.captcha.HCaptchaClient;
|
||||
import org.whispersystems.textsecuregcm.captcha.RecaptchaClient;
|
||||
import org.whispersystems.textsecuregcm.captcha.RegistrationCaptchaManager;
|
||||
import org.whispersystems.textsecuregcm.captcha.ShortCodeExpander;
|
||||
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.secrets.SecretStore;
|
||||
import org.whispersystems.textsecuregcm.configuration.secrets.SecretsModule;
|
||||
@@ -115,6 +116,7 @@ import org.whispersystems.textsecuregcm.controllers.VerificationController;
|
||||
import org.whispersystems.textsecuregcm.currency.CoinMarketCapClient;
|
||||
import org.whispersystems.textsecuregcm.currency.CurrencyConversionManager;
|
||||
import org.whispersystems.textsecuregcm.currency.FixerClient;
|
||||
import org.whispersystems.textsecuregcm.grpc.ProfileGrpcService;
|
||||
import org.whispersystems.textsecuregcm.experiment.ExperimentEnrollmentManager;
|
||||
import org.whispersystems.textsecuregcm.filters.RemoteDeprecationFilter;
|
||||
import org.whispersystems.textsecuregcm.filters.RequestStatisticsFilter;
|
||||
@@ -202,7 +204,6 @@ import org.whispersystems.textsecuregcm.util.logging.UncaughtExceptionHandler;
|
||||
import org.whispersystems.textsecuregcm.websocket.AuthenticatedConnectListener;
|
||||
import org.whispersystems.textsecuregcm.websocket.ProvisioningConnectListener;
|
||||
import org.whispersystems.textsecuregcm.websocket.WebSocketAccountAuthenticator;
|
||||
import org.whispersystems.textsecuregcm.workers.AnalyzeDeviceCapabilitiesCommand;
|
||||
import org.whispersystems.textsecuregcm.workers.AssignUsernameCommand;
|
||||
import org.whispersystems.textsecuregcm.workers.CertificateCommand;
|
||||
import org.whispersystems.textsecuregcm.workers.CheckDynamicConfigurationCommand;
|
||||
@@ -228,6 +229,7 @@ import software.amazon.awssdk.auth.credentials.WebIdentityTokenFileCredentialsPr
|
||||
import software.amazon.awssdk.regions.Region;
|
||||
import software.amazon.awssdk.services.dynamodb.DynamoDbAsyncClient;
|
||||
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
|
||||
import software.amazon.awssdk.services.s3.S3AsyncClient;
|
||||
import software.amazon.awssdk.services.s3.S3Client;
|
||||
|
||||
public class WhisperServerService extends Application<WhisperServerConfiguration> {
|
||||
@@ -265,7 +267,6 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
bootstrap.addCommand(new ScheduledApnPushNotificationSenderServiceCommand());
|
||||
bootstrap.addCommand(new MessagePersisterServiceCommand());
|
||||
bootstrap.addCommand(new MigrateSignedECPreKeysCommand());
|
||||
bootstrap.addCommand(new AnalyzeDeviceCapabilitiesCommand());
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -581,7 +582,10 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
.connectTimeout(Duration.ofSeconds(10)).build();
|
||||
HCaptchaClient hCaptchaClient = new HCaptchaClient(config.getHCaptchaConfiguration().apiKey().value(), hcaptchaHttpClient,
|
||||
dynamicConfigurationManager);
|
||||
CaptchaChecker captchaChecker = new CaptchaChecker(List.of(recaptchaClient, hCaptchaClient));
|
||||
HttpClient shortCodeRetrieverHttpClient = HttpClient.newBuilder().version(HttpClient.Version.HTTP_2)
|
||||
.connectTimeout(Duration.ofSeconds(10)).build();
|
||||
ShortCodeExpander shortCodeRetriever = new ShortCodeExpander(shortCodeRetrieverHttpClient, config.getShortCodeRetrieverConfiguration().baseUrl());
|
||||
CaptchaChecker captchaChecker = new CaptchaChecker(shortCodeRetriever, List.of(recaptchaClient, hCaptchaClient));
|
||||
|
||||
PushChallengeManager pushChallengeManager = new PushChallengeManager(pushNotificationManager,
|
||||
pushChallengeDynamoDb);
|
||||
@@ -616,6 +620,10 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
.credentialsProvider(cdnCredentialsProvider)
|
||||
.region(Region.of(config.getCdnConfiguration().region()))
|
||||
.build();
|
||||
S3AsyncClient asyncCdnS3Client = S3AsyncClient.builder()
|
||||
.credentialsProvider(cdnCredentialsProvider)
|
||||
.region(Region.of(config.getCdnConfiguration().region()))
|
||||
.build();
|
||||
|
||||
final GcsAttachmentGenerator gcsAttachmentGenerator = new GcsAttachmentGenerator(
|
||||
config.getGcpAttachmentsConfiguration().domain(),
|
||||
@@ -647,7 +655,9 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
// TODO: specialize metrics with user-agent platform
|
||||
.intercept(new MetricCollectingServerInterceptor(Metrics.globalRegistry))
|
||||
.addService(ServerInterceptors.intercept(new KeysGrpcService(accountsManager, keys, rateLimiters), basicCredentialAuthenticationInterceptor))
|
||||
.addService(new KeysAnonymousGrpcService(accountsManager, keys));
|
||||
.addService(new KeysAnonymousGrpcService(accountsManager, keys))
|
||||
.addService(ServerInterceptors.intercept(new ProfileGrpcService(clock, accountsManager, profilesManager, dynamicConfigurationManager,
|
||||
config.getBadges(), asyncCdnS3Client, profileCdnPolicyGenerator, profileCdnPolicySigner, config.getCdnConfiguration().bucket()), basicCredentialAuthenticationInterceptor));
|
||||
|
||||
RemoteDeprecationFilter remoteDeprecationFilter = new RemoteDeprecationFilter(dynamicConfigurationManager);
|
||||
environment.servlets()
|
||||
|
||||
-9
@@ -32,9 +32,6 @@ public class BaseAccountAuthenticator {
|
||||
private static final String AUTHENTICATION_SUCCEEDED_TAG_NAME = "succeeded";
|
||||
private static final String AUTHENTICATION_FAILURE_REASON_TAG_NAME = "reason";
|
||||
private static final String ENABLED_TAG_NAME = "enabled";
|
||||
private static final String AUTHENTICATION_HAS_STORY_CAPABILITY = "hasStoryCapability";
|
||||
|
||||
private static final String STORY_ADOPTION_COUNTER_NAME = name(BaseAccountAuthenticator.class, "storyAdoption");
|
||||
|
||||
private static final String DAYS_SINCE_LAST_SEEN_DISTRIBUTION_NAME = name(BaseAccountAuthenticator.class, "daysSinceLastSeen");
|
||||
private static final String IS_PRIMARY_DEVICE_TAG = "isPrimary";
|
||||
@@ -75,7 +72,6 @@ public class BaseAccountAuthenticator {
|
||||
public Optional<AuthenticatedAccount> authenticate(BasicCredentials basicCredentials, boolean enabledRequired) {
|
||||
boolean succeeded = false;
|
||||
String failureReason = null;
|
||||
boolean hasStoryCapability = false;
|
||||
|
||||
try {
|
||||
final UUID accountUuid;
|
||||
@@ -94,8 +90,6 @@ public class BaseAccountAuthenticator {
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
hasStoryCapability = account.map(Account::isStoriesSupported).orElse(false);
|
||||
|
||||
Optional<Device> device = account.get().getDevice(deviceId);
|
||||
|
||||
if (device.isEmpty()) {
|
||||
@@ -150,9 +144,6 @@ public class BaseAccountAuthenticator {
|
||||
}
|
||||
|
||||
Metrics.counter(AUTHENTICATION_COUNTER_NAME, tags).increment();
|
||||
|
||||
Tags storyTags = Tags.of(AUTHENTICATION_HAS_STORY_CAPABILITY, String.valueOf(hasStoryCapability));
|
||||
Metrics.counter(STORY_ADOPTION_COUNTER_NAME, storyTags).increment();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -5,30 +5,7 @@
|
||||
|
||||
package org.whispersystems.textsecuregcm.auth;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public class TurnToken {
|
||||
|
||||
@JsonProperty
|
||||
private String username;
|
||||
|
||||
@JsonProperty
|
||||
private String password;
|
||||
|
||||
@JsonProperty
|
||||
private List<String> urls;
|
||||
|
||||
public TurnToken(String username, String password, List<String> urls) {
|
||||
this.username = username;
|
||||
this.password = password;
|
||||
this.urls = urls;
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
List<String> getUrls() {
|
||||
return urls;
|
||||
}
|
||||
public record TurnToken(String username, String password, List<String> urls) {
|
||||
}
|
||||
@@ -23,6 +23,7 @@ import java.time.Instant;
|
||||
import java.util.Base64;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
|
||||
public class TurnTokenGenerator {
|
||||
|
||||
@@ -39,9 +40,9 @@ public class TurnTokenGenerator {
|
||||
this.turnSecret = turnSecret;
|
||||
}
|
||||
|
||||
public TurnToken generate(final String e164) {
|
||||
public TurnToken generate(final UUID aci) {
|
||||
try {
|
||||
final List<String> urls = urls(e164);
|
||||
final List<String> urls = urls(aci);
|
||||
final Mac mac = Mac.getInstance(ALGORITHM);
|
||||
final long validUntilSeconds = Instant.now().plus(Duration.ofDays(1)).getEpochSecond();
|
||||
final long user = Util.ensureNonNegativeInt(new SecureRandom().nextInt());
|
||||
@@ -56,12 +57,12 @@ public class TurnTokenGenerator {
|
||||
}
|
||||
}
|
||||
|
||||
private List<String> urls(final String e164) {
|
||||
private List<String> urls(final UUID aci) {
|
||||
final DynamicTurnConfiguration turnConfig = dynamicConfigurationManager.getConfiguration().getTurnConfiguration();
|
||||
|
||||
// Check if number is enrolled to test out specific turn servers
|
||||
final Optional<TurnUriConfiguration> enrolled = turnConfig.getUriConfigs().stream()
|
||||
.filter(config -> config.getEnrolledNumbers().contains(e164))
|
||||
.filter(config -> config.getEnrolledAcis().contains(aci))
|
||||
.findFirst();
|
||||
|
||||
if (enrolled.isPresent()) {
|
||||
|
||||
@@ -29,9 +29,15 @@ public class CaptchaChecker {
|
||||
@VisibleForTesting
|
||||
static final String SEPARATOR = ".";
|
||||
|
||||
private static final String SHORT_SUFFIX = "-short";
|
||||
|
||||
private final ShortCodeExpander shortCodeExpander;
|
||||
private final Map<String, CaptchaClient> captchaClientMap;
|
||||
|
||||
public CaptchaChecker(final List<CaptchaClient> captchaClients) {
|
||||
public CaptchaChecker(
|
||||
final ShortCodeExpander shortCodeRetriever,
|
||||
final List<CaptchaClient> captchaClients) {
|
||||
this.shortCodeExpander = shortCodeRetriever;
|
||||
this.captchaClientMap = captchaClients.stream()
|
||||
.collect(Collectors.toMap(CaptchaClient::scheme, Function.identity()));
|
||||
}
|
||||
@@ -63,9 +69,17 @@ public class CaptchaChecker {
|
||||
final String prefix = parts[0];
|
||||
final String siteKey = parts[1].toLowerCase(Locale.ROOT).strip();
|
||||
final String action = parts[2];
|
||||
final String token = parts[3];
|
||||
String token = parts[3];
|
||||
|
||||
final CaptchaClient client = this.captchaClientMap.get(prefix);
|
||||
String provider = prefix;
|
||||
if (prefix.endsWith(SHORT_SUFFIX)) {
|
||||
// This is a "short" solution that points to the actual solution. We need to fetch the
|
||||
// full solution before proceeding
|
||||
provider = prefix.substring(0, prefix.length() - SHORT_SUFFIX.length());
|
||||
token = shortCodeExpander.retrieve(token).orElseThrow(() -> new BadRequestException("invalid shortcode"));
|
||||
}
|
||||
|
||||
final CaptchaClient client = this.captchaClientMap.get(provider);
|
||||
if (client == null) {
|
||||
throw new BadRequestException("invalid captcha scheme");
|
||||
}
|
||||
@@ -92,7 +106,7 @@ public class CaptchaChecker {
|
||||
Metrics.counter(ASSESSMENTS_COUNTER_NAME,
|
||||
"action", action,
|
||||
"score", result.getScoreString(),
|
||||
"provider", prefix)
|
||||
"provider", provider)
|
||||
.increment();
|
||||
return result;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
/*
|
||||
* Copyright 2023 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.captcha;
|
||||
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import org.apache.http.HttpStatus;
|
||||
import java.io.IOException;
|
||||
import java.net.URI;
|
||||
import java.net.http.HttpClient;
|
||||
import java.net.http.HttpRequest;
|
||||
import java.net.http.HttpResponse;
|
||||
import java.util.Optional;
|
||||
|
||||
import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
|
||||
|
||||
public class ShortCodeExpander {
|
||||
private static final String EXPAND_COUNTER_NAME = name(ShortCodeExpander.class, "expand");
|
||||
|
||||
private final HttpClient client;
|
||||
private final URI shortenerHost;
|
||||
|
||||
public ShortCodeExpander(final HttpClient client, final String shortenerHost) {
|
||||
this.client = client;
|
||||
this.shortenerHost = URI.create(shortenerHost);
|
||||
}
|
||||
|
||||
public Optional<String> retrieve(final String shortCode) throws IOException {
|
||||
final URI uri = shortenerHost.resolve(shortCode);
|
||||
final HttpRequest request = HttpRequest.newBuilder().uri(uri).GET().build();
|
||||
|
||||
try {
|
||||
final HttpResponse<String> response = this.client.send(request, HttpResponse.BodyHandlers.ofString());
|
||||
Metrics.counter(EXPAND_COUNTER_NAME, "responseCode", Integer.toString(response.statusCode())).increment();
|
||||
return switch (response.statusCode()) {
|
||||
case HttpStatus.SC_OK -> Optional.of(response.body());
|
||||
case HttpStatus.SC_NOT_FOUND -> Optional.empty();
|
||||
default -> throw new IOException("Failed to look up shortcode");
|
||||
};
|
||||
} catch (InterruptedException e) {
|
||||
throw new IOException(e);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
}
|
||||
+9
@@ -0,0 +1,9 @@
|
||||
/*
|
||||
* Copyright 2023 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.configuration;
|
||||
|
||||
public record ShortCodeExpanderConfiguration(String baseUrl) {
|
||||
}
|
||||
+5
-3
@@ -6,6 +6,7 @@ import javax.validation.constraints.NotNull;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
|
||||
public class TurnUriConfiguration {
|
||||
@JsonProperty
|
||||
@@ -22,7 +23,8 @@ public class TurnUriConfiguration {
|
||||
/**
|
||||
* Enrolled numbers will always get this uri list
|
||||
*/
|
||||
private Set<String> enrolledNumbers = Collections.emptySet();
|
||||
@JsonProperty
|
||||
private Set<UUID> enrolledAcis = Collections.emptySet();
|
||||
|
||||
public List<String> getUris() {
|
||||
return uris;
|
||||
@@ -32,7 +34,7 @@ public class TurnUriConfiguration {
|
||||
return weight;
|
||||
}
|
||||
|
||||
public Set<String> getEnrolledNumbers() {
|
||||
return Collections.unmodifiableSet(enrolledNumbers);
|
||||
public Set<UUID> getEnrolledAcis() {
|
||||
return Collections.unmodifiableSet(enrolledAcis);
|
||||
}
|
||||
}
|
||||
+2
-19
@@ -4,7 +4,6 @@
|
||||
*/
|
||||
package org.whispersystems.textsecuregcm.controllers;
|
||||
|
||||
import com.codahale.metrics.annotation.Timed;
|
||||
import io.dropwizard.auth.Auth;
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
import io.swagger.v3.oas.annotations.Parameter;
|
||||
@@ -91,16 +90,14 @@ public class AccountController {
|
||||
this.usernameHashZkProofVerifier = usernameHashZkProofVerifier;
|
||||
}
|
||||
|
||||
@Timed
|
||||
@GET
|
||||
@Path("/turn/")
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
public TurnToken getTurnToken(@Auth AuthenticatedAccount auth) throws RateLimitExceededException {
|
||||
rateLimiters.getTurnLimiter().validate(auth.getAccount().getUuid());
|
||||
return turnTokenGenerator.generate(auth.getAccount().getNumber());
|
||||
return turnTokenGenerator.generate(auth.getAccount().getUuid());
|
||||
}
|
||||
|
||||
@Timed
|
||||
@PUT
|
||||
@Path("/gcm/")
|
||||
@Consumes(MediaType.APPLICATION_JSON)
|
||||
@@ -124,7 +121,6 @@ public class AccountController {
|
||||
});
|
||||
}
|
||||
|
||||
@Timed
|
||||
@DELETE
|
||||
@Path("/gcm/")
|
||||
@ChangesDeviceEnabledState
|
||||
@@ -139,7 +135,6 @@ public class AccountController {
|
||||
});
|
||||
}
|
||||
|
||||
@Timed
|
||||
@PUT
|
||||
@Path("/apn/")
|
||||
@Consumes(MediaType.APPLICATION_JSON)
|
||||
@@ -165,7 +160,6 @@ public class AccountController {
|
||||
});
|
||||
}
|
||||
|
||||
@Timed
|
||||
@DELETE
|
||||
@Path("/apn/")
|
||||
@ChangesDeviceEnabledState
|
||||
@@ -175,6 +169,7 @@ public class AccountController {
|
||||
|
||||
accounts.updateDevice(account, device.getId(), d -> {
|
||||
d.setApnId(null);
|
||||
d.setVoipApnId(null);
|
||||
d.setFetchesMessages(false);
|
||||
if (d.getId() == 1) {
|
||||
d.setUserAgent("OWI");
|
||||
@@ -184,7 +179,6 @@ public class AccountController {
|
||||
});
|
||||
}
|
||||
|
||||
@Timed
|
||||
@PUT
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@Path("/registration_lock")
|
||||
@@ -195,14 +189,12 @@ public class AccountController {
|
||||
a -> a.setRegistrationLock(credentials.hash(), credentials.salt()));
|
||||
}
|
||||
|
||||
@Timed
|
||||
@DELETE
|
||||
@Path("/registration_lock")
|
||||
public void removeRegistrationLock(@Auth AuthenticatedAccount auth) {
|
||||
accounts.update(auth.getAccount(), a -> a.setRegistrationLock(null, null));
|
||||
}
|
||||
|
||||
@Timed
|
||||
@PUT
|
||||
@Path("/name/")
|
||||
public void setName(@Auth DisabledPermittedAuthenticatedAccount disabledPermittedAuth, @NotNull @Valid DeviceName deviceName) {
|
||||
@@ -211,7 +203,6 @@ public class AccountController {
|
||||
accounts.updateDevice(account, device.getId(), d -> d.setName(deviceName.getDeviceName()));
|
||||
}
|
||||
|
||||
@Timed
|
||||
@PUT
|
||||
@Path("/attributes/")
|
||||
@Consumes(MediaType.APPLICATION_JSON)
|
||||
@@ -268,7 +259,6 @@ public class AccountController {
|
||||
auth.getAccount().isStorageSupported());
|
||||
}
|
||||
|
||||
@Timed
|
||||
@DELETE
|
||||
@Path("/username_hash")
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@@ -285,7 +275,6 @@ public class AccountController {
|
||||
accounts.clearUsernameHash(auth.getAccount());
|
||||
}
|
||||
|
||||
@Timed
|
||||
@PUT
|
||||
@Path("/username_hash/reserve")
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@@ -325,7 +314,6 @@ public class AccountController {
|
||||
}
|
||||
}
|
||||
|
||||
@Timed
|
||||
@PUT
|
||||
@Path("/username_hash/confirm")
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@@ -370,7 +358,6 @@ public class AccountController {
|
||||
}
|
||||
}
|
||||
|
||||
@Timed
|
||||
@GET
|
||||
@Path("/username_hash/{usernameHash}")
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@@ -408,7 +395,6 @@ public class AccountController {
|
||||
.orElseThrow(() -> new WebApplicationException(Status.NOT_FOUND));
|
||||
}
|
||||
|
||||
@Timed
|
||||
@PUT
|
||||
@Path("/username_link")
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@@ -443,7 +429,6 @@ public class AccountController {
|
||||
return new UsernameLinkHandle(usernameLinkHandle);
|
||||
}
|
||||
|
||||
@Timed
|
||||
@DELETE
|
||||
@Path("/username_link")
|
||||
@Operation(
|
||||
@@ -462,7 +447,6 @@ public class AccountController {
|
||||
clearUsernameLink(auth.getAccount());
|
||||
}
|
||||
|
||||
@Timed
|
||||
@GET
|
||||
@Path("/username_link/{uuid}")
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@@ -518,7 +502,6 @@ public class AccountController {
|
||||
return Response.status(maybeAccount.map(ignored -> Status.OK).orElse(Status.NOT_FOUND)).build();
|
||||
}
|
||||
|
||||
@Timed
|
||||
@DELETE
|
||||
@Path("/me")
|
||||
public void deleteAccount(@Auth DisabledPermittedAuthenticatedAccount auth) throws InterruptedException {
|
||||
|
||||
-5
@@ -7,7 +7,6 @@ package org.whispersystems.textsecuregcm.controllers;
|
||||
|
||||
import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
|
||||
|
||||
import com.codahale.metrics.annotation.Timed;
|
||||
import com.google.common.net.HttpHeaders;
|
||||
import io.dropwizard.auth.Auth;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
@@ -76,7 +75,6 @@ public class AccountControllerV2 {
|
||||
this.rateLimiters = rateLimiters;
|
||||
}
|
||||
|
||||
@Timed
|
||||
@PUT
|
||||
@Path("/number")
|
||||
@Consumes(MediaType.APPLICATION_JSON)
|
||||
@@ -155,7 +153,6 @@ public class AccountControllerV2 {
|
||||
}
|
||||
}
|
||||
|
||||
@Timed
|
||||
@PUT
|
||||
@Path("/phone_number_identity_key_distribution")
|
||||
@Consumes(MediaType.APPLICATION_JSON)
|
||||
@@ -208,7 +205,6 @@ public class AccountControllerV2 {
|
||||
}
|
||||
}
|
||||
|
||||
@Timed
|
||||
@PUT
|
||||
@Path("/phone_number_discoverability")
|
||||
@Consumes(MediaType.APPLICATION_JSON)
|
||||
@@ -221,7 +217,6 @@ public class AccountControllerV2 {
|
||||
phoneNumberDiscoverability.discoverableByPhoneNumber()));
|
||||
}
|
||||
|
||||
@Timed
|
||||
@GET
|
||||
@Path("/data_report")
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
|
||||
@@ -5,7 +5,6 @@
|
||||
|
||||
package org.whispersystems.textsecuregcm.controllers;
|
||||
|
||||
import com.codahale.metrics.annotation.Timed;
|
||||
import io.dropwizard.auth.Auth;
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
import java.util.UUID;
|
||||
@@ -40,7 +39,6 @@ public class ArtController {
|
||||
this.rateLimiters = rateLimiters;
|
||||
}
|
||||
|
||||
@Timed
|
||||
@GET
|
||||
@Path("/auth")
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
|
||||
-2
@@ -7,7 +7,6 @@ package org.whispersystems.textsecuregcm.controllers;
|
||||
|
||||
import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
|
||||
|
||||
import com.codahale.metrics.annotation.Timed;
|
||||
import com.google.common.net.HttpHeaders;
|
||||
import io.dropwizard.auth.Auth;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
@@ -48,7 +47,6 @@ public class AttachmentControllerV2 {
|
||||
this.policySigner = new PolicySigner(accessSecret, region);
|
||||
}
|
||||
|
||||
@Timed
|
||||
@GET
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@Path("/form/upload")
|
||||
|
||||
-8
@@ -5,17 +5,13 @@
|
||||
|
||||
package org.whispersystems.textsecuregcm.controllers;
|
||||
|
||||
import com.codahale.metrics.annotation.Timed;
|
||||
import io.dropwizard.auth.Auth;
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
import java.io.IOException;
|
||||
import java.security.InvalidKeyException;
|
||||
import java.security.SecureRandom;
|
||||
import java.security.spec.InvalidKeySpecException;
|
||||
import java.time.ZoneOffset;
|
||||
import java.time.ZonedDateTime;
|
||||
import java.util.Base64;
|
||||
import java.util.Map;
|
||||
import javax.annotation.Nonnull;
|
||||
import javax.ws.rs.GET;
|
||||
import javax.ws.rs.Path;
|
||||
@@ -25,9 +21,6 @@ import org.whispersystems.textsecuregcm.attachments.AttachmentGenerator;
|
||||
import org.whispersystems.textsecuregcm.attachments.GcsAttachmentGenerator;
|
||||
import org.whispersystems.textsecuregcm.auth.AuthenticatedAccount;
|
||||
import org.whispersystems.textsecuregcm.entities.AttachmentDescriptorV3;
|
||||
import org.whispersystems.textsecuregcm.gcp.CanonicalRequest;
|
||||
import org.whispersystems.textsecuregcm.gcp.CanonicalRequestGenerator;
|
||||
import org.whispersystems.textsecuregcm.gcp.CanonicalRequestSigner;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimiter;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimiters;
|
||||
|
||||
@@ -51,7 +44,6 @@ public class AttachmentControllerV3 {
|
||||
this.secureRandom = new SecureRandom();
|
||||
}
|
||||
|
||||
@Timed
|
||||
@GET
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@Path("/form/upload")
|
||||
|
||||
-4
@@ -5,13 +5,11 @@
|
||||
|
||||
package org.whispersystems.textsecuregcm.controllers;
|
||||
|
||||
import com.codahale.metrics.annotation.Timed;
|
||||
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.responses.ApiResponse;
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
|
||||
import java.security.SecureRandom;
|
||||
import java.util.Base64;
|
||||
import java.util.Map;
|
||||
@@ -20,7 +18,6 @@ import javax.ws.rs.GET;
|
||||
import javax.ws.rs.Path;
|
||||
import javax.ws.rs.Produces;
|
||||
import javax.ws.rs.core.MediaType;
|
||||
|
||||
import org.whispersystems.textsecuregcm.attachments.AttachmentGenerator;
|
||||
import org.whispersystems.textsecuregcm.attachments.GcsAttachmentGenerator;
|
||||
import org.whispersystems.textsecuregcm.attachments.TusAttachmentGenerator;
|
||||
@@ -62,7 +59,6 @@ public class AttachmentControllerV4 {
|
||||
);
|
||||
}
|
||||
|
||||
@Timed
|
||||
@GET
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@Path("/form/upload")
|
||||
|
||||
+9
-11
@@ -1,9 +1,17 @@
|
||||
package org.whispersystems.textsecuregcm.controllers;
|
||||
|
||||
import com.codahale.metrics.annotation.Timed;
|
||||
import io.dropwizard.auth.Auth;
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
import io.swagger.v3.oas.annotations.responses.ApiResponse;
|
||||
import java.time.Instant;
|
||||
import java.time.temporal.ChronoUnit;
|
||||
import javax.validation.Valid;
|
||||
import javax.validation.constraints.NotNull;
|
||||
import javax.ws.rs.BadRequestException;
|
||||
import javax.ws.rs.POST;
|
||||
import javax.ws.rs.Path;
|
||||
import javax.ws.rs.Produces;
|
||||
import javax.ws.rs.core.MediaType;
|
||||
import org.signal.libsignal.protocol.ServiceId;
|
||||
import org.signal.libsignal.zkgroup.GenericServerSecretParams;
|
||||
import org.signal.libsignal.zkgroup.InvalidInputException;
|
||||
@@ -12,15 +20,6 @@ import org.whispersystems.textsecuregcm.auth.AuthenticatedAccount;
|
||||
import org.whispersystems.textsecuregcm.entities.CreateCallLinkCredential;
|
||||
import org.whispersystems.textsecuregcm.entities.GetCreateCallLinkCredentialsRequest;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimiters;
|
||||
import javax.validation.Valid;
|
||||
import javax.validation.constraints.NotNull;
|
||||
import javax.ws.rs.BadRequestException;
|
||||
import javax.ws.rs.POST;
|
||||
import javax.ws.rs.Path;
|
||||
import javax.ws.rs.Produces;
|
||||
import javax.ws.rs.core.MediaType;
|
||||
import java.time.Instant;
|
||||
import java.time.temporal.ChronoUnit;
|
||||
|
||||
@Path("/v1/call-link")
|
||||
@io.swagger.v3.oas.annotations.tags.Tag(name = "CallLink")
|
||||
@@ -36,7 +35,6 @@ public class CallLinkController {
|
||||
this.genericServerSecretParams = genericServerSecretParams;
|
||||
}
|
||||
|
||||
@Timed
|
||||
@POST
|
||||
@Path("/create-auth")
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
|
||||
+1
-6
@@ -7,7 +7,6 @@ package org.whispersystems.textsecuregcm.controllers;
|
||||
|
||||
import static com.codahale.metrics.MetricRegistry.name;
|
||||
|
||||
import com.codahale.metrics.annotation.Timed;
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import io.dropwizard.auth.Auth;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
@@ -20,7 +19,6 @@ import java.time.temporal.ChronoUnit;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
import java.util.UUID;
|
||||
import javax.annotation.Nonnull;
|
||||
import javax.ws.rs.BadRequestException;
|
||||
import javax.ws.rs.DefaultValue;
|
||||
@@ -31,12 +29,11 @@ import javax.ws.rs.QueryParam;
|
||||
import javax.ws.rs.WebApplicationException;
|
||||
import javax.ws.rs.core.MediaType;
|
||||
import javax.ws.rs.core.Response;
|
||||
|
||||
import org.signal.libsignal.protocol.ServiceId;
|
||||
import org.signal.libsignal.zkgroup.GenericServerSecretParams;
|
||||
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.GenericServerSecretParams;
|
||||
import org.whispersystems.textsecuregcm.auth.AuthenticatedAccount;
|
||||
import org.whispersystems.textsecuregcm.auth.CertificateGenerator;
|
||||
import org.whispersystems.textsecuregcm.entities.DeliveryCertificate;
|
||||
@@ -68,7 +65,6 @@ public class CertificateController {
|
||||
this.clock = Objects.requireNonNull(clock);
|
||||
}
|
||||
|
||||
@Timed
|
||||
@GET
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@Path("/delivery")
|
||||
@@ -87,7 +83,6 @@ public class CertificateController {
|
||||
certificateGenerator.createFor(auth.getAccount(), auth.getAuthenticatedDevice(), includeE164));
|
||||
}
|
||||
|
||||
@Timed
|
||||
@GET
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@Path("/auth/group")
|
||||
|
||||
-4
@@ -7,7 +7,6 @@ package org.whispersystems.textsecuregcm.controllers;
|
||||
|
||||
import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
|
||||
|
||||
import com.codahale.metrics.annotation.Timed;
|
||||
import com.google.common.net.HttpHeaders;
|
||||
import io.dropwizard.auth.Auth;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
@@ -20,7 +19,6 @@ import io.swagger.v3.oas.annotations.parameters.RequestBody;
|
||||
import io.swagger.v3.oas.annotations.responses.ApiResponse;
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
import java.io.IOException;
|
||||
import java.util.Optional;
|
||||
import javax.validation.Valid;
|
||||
import javax.ws.rs.BadRequestException;
|
||||
import javax.ws.rs.Consumes;
|
||||
@@ -53,7 +51,6 @@ public class ChallengeController {
|
||||
this.rateLimitChallengeManager = rateLimitChallengeManager;
|
||||
}
|
||||
|
||||
@Timed
|
||||
@PUT
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@Consumes(MediaType.APPLICATION_JSON)
|
||||
@@ -110,7 +107,6 @@ public class ChallengeController {
|
||||
return Response.status(200).build();
|
||||
}
|
||||
|
||||
@Timed
|
||||
@POST
|
||||
@Path("/push")
|
||||
@Operation(
|
||||
|
||||
+4
-21
@@ -4,7 +4,6 @@
|
||||
*/
|
||||
package org.whispersystems.textsecuregcm.controllers;
|
||||
|
||||
import com.codahale.metrics.annotation.Timed;
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import com.google.common.net.HttpHeaders;
|
||||
import io.dropwizard.auth.Auth;
|
||||
@@ -118,7 +117,6 @@ public class DeviceController {
|
||||
}
|
||||
}
|
||||
|
||||
@Timed
|
||||
@GET
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
public DeviceInfoList getDevices(@Auth AuthenticatedAccount auth) {
|
||||
@@ -132,7 +130,6 @@ public class DeviceController {
|
||||
return new DeviceInfoList(devices);
|
||||
}
|
||||
|
||||
@Timed
|
||||
@DELETE
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@Path("/{device_id}")
|
||||
@@ -145,15 +142,14 @@ public class DeviceController {
|
||||
|
||||
final CompletableFuture<Void> deleteKeysFuture = keys.delete(account.getUuid(), deviceId);
|
||||
|
||||
messages.clear(account.getUuid(), deviceId);
|
||||
messages.clear(account.getUuid(), deviceId).join();
|
||||
account = accounts.update(account, a -> a.removeDevice(deviceId));
|
||||
// ensure any messages that came in after the first clear() are also removed
|
||||
messages.clear(account.getUuid(), deviceId);
|
||||
messages.clear(account.getUuid(), deviceId).join();
|
||||
|
||||
deleteKeysFuture.join();
|
||||
}
|
||||
|
||||
@Timed
|
||||
@GET
|
||||
@Path("/provisioning/code")
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@@ -185,7 +181,6 @@ public class DeviceController {
|
||||
* @deprecated callers should use {@link #linkDevice(BasicAuthorizationHeader, LinkDeviceRequest, ContainerRequest)}
|
||||
* instead
|
||||
*/
|
||||
@Timed
|
||||
@PUT
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@Consumes(MediaType.APPLICATION_JSON)
|
||||
@@ -210,7 +205,6 @@ public class DeviceController {
|
||||
return new DeviceResponse(account.getUuid(), account.getPhoneNumberIdentifier(), device.getId());
|
||||
}
|
||||
|
||||
@Timed
|
||||
@PUT
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@Consumes(MediaType.APPLICATION_JSON)
|
||||
@@ -244,7 +238,6 @@ public class DeviceController {
|
||||
return new DeviceResponse(account.getUuid(), account.getPhoneNumberIdentifier(), device.getId());
|
||||
}
|
||||
|
||||
@Timed
|
||||
@PUT
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@Path("/unauthenticated_delivery")
|
||||
@@ -253,7 +246,6 @@ public class DeviceController {
|
||||
// Deprecated
|
||||
}
|
||||
|
||||
@Timed
|
||||
@PUT
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@Path("/capabilities")
|
||||
@@ -344,16 +336,7 @@ public class DeviceController {
|
||||
}
|
||||
|
||||
static boolean isCapabilityDowngrade(Account account, DeviceCapabilities capabilities) {
|
||||
boolean isDowngrade = false;
|
||||
|
||||
isDowngrade |= account.isStoriesSupported() && !capabilities.isStories();
|
||||
isDowngrade |= account.isPniSupported() && !capabilities.isPni();
|
||||
isDowngrade |= account.isChangeNumberSupported() && !capabilities.isChangeNumber();
|
||||
isDowngrade |= account.isAnnouncementGroupSupported() && !capabilities.isAnnouncementGroup();
|
||||
isDowngrade |= account.isSenderKeySupported() && !capabilities.isSenderKey();
|
||||
isDowngrade |= account.isGiftBadgesSupported() && !capabilities.isGiftBadges();
|
||||
|
||||
return isDowngrade;
|
||||
return account.isPniSupported() && !capabilities.pni();
|
||||
}
|
||||
|
||||
private Pair<Account, Device> createDevice(final String password,
|
||||
@@ -436,7 +419,7 @@ public class DeviceController {
|
||||
keys.delete(a.getUuid(), device.getId()),
|
||||
keys.delete(a.getPhoneNumberIdentifier(), device.getId()));
|
||||
|
||||
messages.clear(a.getUuid(), device.getId());
|
||||
messages.clear(a.getUuid(), device.getId()).join();
|
||||
|
||||
deleteKeysFuture.join();
|
||||
|
||||
|
||||
-2
@@ -4,7 +4,6 @@
|
||||
*/
|
||||
package org.whispersystems.textsecuregcm.controllers;
|
||||
|
||||
import com.codahale.metrics.annotation.Timed;
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import io.dropwizard.auth.Auth;
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
@@ -45,7 +44,6 @@ public class DirectoryV2Controller {
|
||||
this.directoryServiceTokenGenerator = userTokenGenerator;
|
||||
}
|
||||
|
||||
@Timed
|
||||
@GET
|
||||
@Path("/auth")
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
|
||||
-2
@@ -5,7 +5,6 @@
|
||||
|
||||
package org.whispersystems.textsecuregcm.controllers;
|
||||
|
||||
import com.codahale.metrics.annotation.Timed;
|
||||
import io.dropwizard.auth.Auth;
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
import java.time.Clock;
|
||||
@@ -74,7 +73,6 @@ public class DonationController {
|
||||
this.receiptCredentialPresentationFactory = Objects.requireNonNull(receiptCredentialPresentationFactory);
|
||||
}
|
||||
|
||||
@Timed
|
||||
@POST
|
||||
@Path("/redeem-receipt")
|
||||
@Consumes(MediaType.APPLICATION_JSON)
|
||||
|
||||
-3
@@ -7,7 +7,6 @@ package org.whispersystems.textsecuregcm.controllers;
|
||||
|
||||
import static com.codahale.metrics.MetricRegistry.name;
|
||||
|
||||
import com.codahale.metrics.annotation.Timed;
|
||||
import io.dropwizard.auth.Auth;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import io.micrometer.core.instrument.Tags;
|
||||
@@ -40,7 +39,6 @@ public class KeepAliveController {
|
||||
this.clientPresenceManager = clientPresenceManager;
|
||||
}
|
||||
|
||||
@Timed
|
||||
@GET
|
||||
public Response getKeepAlive(@Auth Optional<AuthenticatedAccount> maybeAuth,
|
||||
@WebSocketSession WebSocketSessionContext context) {
|
||||
@@ -63,7 +61,6 @@ public class KeepAliveController {
|
||||
return Response.ok().build();
|
||||
}
|
||||
|
||||
@Timed
|
||||
@GET
|
||||
@Path("/provisioning")
|
||||
public Response getProvisioningKeepAlive() {
|
||||
|
||||
@@ -6,7 +6,6 @@ package org.whispersystems.textsecuregcm.controllers;
|
||||
|
||||
import static com.codahale.metrics.MetricRegistry.name;
|
||||
|
||||
import com.codahale.metrics.annotation.Timed;
|
||||
import com.google.common.net.HttpHeaders;
|
||||
import io.dropwizard.auth.Auth;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
@@ -107,7 +106,6 @@ public class KeysController {
|
||||
return new PreKeyCount(ecCountFuture.join(), pqCountFuture.join());
|
||||
}
|
||||
|
||||
@Timed
|
||||
@PUT
|
||||
@Consumes(MediaType.APPLICATION_JSON)
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@@ -192,7 +190,6 @@ public class KeysController {
|
||||
.join();
|
||||
}
|
||||
|
||||
@Timed
|
||||
@GET
|
||||
@Path("/{identifier}/{device_id}")
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@@ -277,7 +274,6 @@ public class KeysController {
|
||||
return new PreKeyResponse(identityKey, responseItems);
|
||||
}
|
||||
|
||||
@Timed
|
||||
@PUT
|
||||
@Path("/signed")
|
||||
@Consumes(MediaType.APPLICATION_JSON)
|
||||
|
||||
-3
@@ -5,7 +5,6 @@
|
||||
|
||||
package org.whispersystems.textsecuregcm.controllers;
|
||||
|
||||
import com.codahale.metrics.annotation.Timed;
|
||||
import io.dropwizard.auth.Auth;
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
import javax.ws.rs.GET;
|
||||
@@ -40,7 +39,6 @@ public class PaymentsController {
|
||||
this.paymentsServiceCredentialsGenerator = paymentsServiceCredentialsGenerator;
|
||||
}
|
||||
|
||||
@Timed
|
||||
@GET
|
||||
@Path("/auth")
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@@ -48,7 +46,6 @@ public class PaymentsController {
|
||||
return paymentsServiceCredentialsGenerator.generateForUuid(auth.getAccount().getUuid());
|
||||
}
|
||||
|
||||
@Timed
|
||||
@GET
|
||||
@Path("/conversions")
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
|
||||
+35
-88
@@ -7,7 +7,6 @@ package org.whispersystems.textsecuregcm.controllers;
|
||||
|
||||
import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
|
||||
|
||||
import com.codahale.metrics.annotation.Timed;
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import com.google.common.base.Preconditions;
|
||||
import io.dropwizard.auth.Auth;
|
||||
@@ -18,12 +17,9 @@ import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
import io.vavr.Tuple;
|
||||
import java.security.MessageDigest;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import java.security.SecureRandom;
|
||||
import java.time.Clock;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.time.ZoneOffset;
|
||||
import java.time.ZonedDateTime;
|
||||
import java.time.temporal.ChronoUnit;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
@@ -31,17 +27,16 @@ import java.util.Base64;
|
||||
import java.util.Collection;
|
||||
import java.util.Collections;
|
||||
import java.util.HexFormat;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.Map.Entry;
|
||||
import java.util.Objects;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.Executor;
|
||||
import java.util.function.Function;
|
||||
import java.util.stream.Collectors;
|
||||
import javax.annotation.Nullable;
|
||||
import javax.validation.Valid;
|
||||
import javax.validation.constraints.NotNull;
|
||||
import javax.ws.rs.BadRequestException;
|
||||
@@ -88,9 +83,9 @@ import org.whispersystems.textsecuregcm.entities.BatchIdentityCheckResponse;
|
||||
import org.whispersystems.textsecuregcm.entities.CreateProfileRequest;
|
||||
import org.whispersystems.textsecuregcm.entities.CredentialProfileResponse;
|
||||
import org.whispersystems.textsecuregcm.entities.ExpiringProfileKeyCredentialProfileResponse;
|
||||
import org.whispersystems.textsecuregcm.entities.ProfileAvatarUploadAttributes;
|
||||
import org.whispersystems.textsecuregcm.entities.UserCapabilities;
|
||||
import org.whispersystems.textsecuregcm.entities.VersionedProfileResponse;
|
||||
import org.whispersystems.textsecuregcm.grpc.ProfileHelper;
|
||||
import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.identity.PniServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.identity.ServiceIdentifier;
|
||||
@@ -104,7 +99,6 @@ import org.whispersystems.textsecuregcm.storage.AccountsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.DynamicConfigurationManager;
|
||||
import org.whispersystems.textsecuregcm.storage.ProfilesManager;
|
||||
import org.whispersystems.textsecuregcm.storage.VersionedProfile;
|
||||
import org.whispersystems.textsecuregcm.util.Pair;
|
||||
import org.whispersystems.textsecuregcm.util.Util;
|
||||
import software.amazon.awssdk.services.s3.S3Client;
|
||||
import software.amazon.awssdk.services.s3.model.DeleteObjectRequest;
|
||||
@@ -171,7 +165,6 @@ public class ProfileController {
|
||||
this.batchIdentityCheckExecutor = Preconditions.checkNotNull(batchIdentityCheckExecutor);
|
||||
}
|
||||
|
||||
@Timed
|
||||
@PUT
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@Consumes(MediaType.APPLICATION_JSON)
|
||||
@@ -185,31 +178,31 @@ public class ProfileController {
|
||||
dynamicConfigurationManager.getConfiguration().getPaymentsConfiguration().getDisallowedPrefixes().stream()
|
||||
.anyMatch(prefix -> auth.getAccount().getNumber().startsWith(prefix));
|
||||
|
||||
if (hasDisallowedPrefix && currentProfile.map(VersionedProfile::getPaymentAddress).isEmpty()) {
|
||||
if (hasDisallowedPrefix && currentProfile.map(VersionedProfile::paymentAddress).isEmpty()) {
|
||||
return Response.status(Response.Status.FORBIDDEN).build();
|
||||
}
|
||||
}
|
||||
|
||||
Optional<String> currentAvatar = Optional.empty();
|
||||
if (currentProfile.isPresent() && currentProfile.get().getAvatar() != null && currentProfile.get().getAvatar()
|
||||
if (currentProfile.isPresent() && currentProfile.get().avatar() != null && currentProfile.get().avatar()
|
||||
.startsWith("profiles/")) {
|
||||
currentAvatar = Optional.of(currentProfile.get().getAvatar());
|
||||
currentAvatar = Optional.of(currentProfile.get().avatar());
|
||||
}
|
||||
|
||||
final String avatar = switch (request.getAvatarChange()) {
|
||||
case UNCHANGED -> currentAvatar.orElse(null);
|
||||
case CLEAR -> null;
|
||||
case UPDATE -> generateAvatarObjectName();
|
||||
case UPDATE -> ProfileHelper.generateAvatarObjectName();
|
||||
};
|
||||
|
||||
profilesManager.set(auth.getAccount().getUuid(),
|
||||
new VersionedProfile(
|
||||
request.getVersion(),
|
||||
request.getName(),
|
||||
decodeFromBase64(request.getName()),
|
||||
avatar,
|
||||
request.getAboutEmoji(),
|
||||
request.getAbout(),
|
||||
request.getPaymentAddress(),
|
||||
decodeFromBase64(request.getAboutEmoji()),
|
||||
decodeFromBase64(request.getAbout()),
|
||||
decodeFromBase64(request.getPaymentAddress()),
|
||||
request.getCommitment().serialize()));
|
||||
|
||||
if (request.getAvatarChange() != CreateProfileRequest.AvatarChange.UNCHANGED) {
|
||||
@@ -220,7 +213,7 @@ public class ProfileController {
|
||||
}
|
||||
|
||||
final List<AccountBadge> updatedBadges = request.getBadges()
|
||||
.map(badges -> mergeBadgeIdsWithExistingAccountBadges(badges, auth.getAccount().getBadges()))
|
||||
.map(badges -> ProfileHelper.mergeBadgeIdsWithExistingAccountBadges(clock, badgeConfigurationMap, badges, auth.getAccount().getBadges()))
|
||||
.orElseGet(() -> auth.getAccount().getBadges());
|
||||
|
||||
accountsManager.update(auth.getAccount(), a -> {
|
||||
@@ -229,13 +222,12 @@ public class ProfileController {
|
||||
});
|
||||
|
||||
if (request.getAvatarChange() == CreateProfileRequest.AvatarChange.UPDATE) {
|
||||
return Response.ok(generateAvatarUploadForm(avatar)).build();
|
||||
return Response.ok(ProfileHelper.generateAvatarUploadForm(policyGenerator, policySigner, avatar)).build();
|
||||
} else {
|
||||
return Response.ok().build();
|
||||
}
|
||||
}
|
||||
|
||||
@Timed
|
||||
@GET
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@Path("/{identifier}/{version}")
|
||||
@@ -256,7 +248,6 @@ public class ProfileController {
|
||||
containerRequestContext);
|
||||
}
|
||||
|
||||
@Timed
|
||||
@GET
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@Path("/{identifier}/{version}/{credentialRequest}")
|
||||
@@ -288,7 +279,6 @@ public class ProfileController {
|
||||
|
||||
// Although clients should generally be using versioned profiles wherever possible, there are still a few lingering
|
||||
// use cases for getting profiles without a version (e.g. getting a contact's unidentified access key checksum).
|
||||
@Timed
|
||||
@GET
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@Path("/{identifier}")
|
||||
@@ -331,7 +321,6 @@ public class ProfileController {
|
||||
};
|
||||
}
|
||||
|
||||
@Timed
|
||||
@POST
|
||||
@Consumes(MediaType.APPLICATION_JSON)
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@@ -419,16 +408,17 @@ public class ProfileController {
|
||||
VERSION_NOT_FOUND_COUNTER.increment();
|
||||
}
|
||||
|
||||
final String name = maybeProfile.map(VersionedProfile::getName).orElse(null);
|
||||
final String about = maybeProfile.map(VersionedProfile::getAbout).orElse(null);
|
||||
final String aboutEmoji = maybeProfile.map(VersionedProfile::getAboutEmoji).orElse(null);
|
||||
final String avatar = maybeProfile.map(VersionedProfile::getAvatar).orElse(null);
|
||||
final String name = maybeProfile.map(VersionedProfile::name).map(ProfileController::encodeToBase64).orElse(null);
|
||||
final String about = maybeProfile.map(VersionedProfile::about).map(ProfileController::encodeToBase64).orElse(null);
|
||||
final String aboutEmoji = maybeProfile.map(VersionedProfile::aboutEmoji).map(ProfileController::encodeToBase64).orElse(null);
|
||||
final String avatar = maybeProfile.map(VersionedProfile::avatar).orElse(null);
|
||||
|
||||
// Allow requests where either the version matches the latest version on Account or the latest version on Account
|
||||
// is empty to read the payment address.
|
||||
final String paymentAddress = maybeProfile
|
||||
.filter(p -> account.getCurrentProfileVersion().map(v -> v.equals(version)).orElse(true))
|
||||
.map(VersionedProfile::getPaymentAddress)
|
||||
.map(VersionedProfile::paymentAddress)
|
||||
.map(ProfileController::encodeToBase64)
|
||||
.orElse(null);
|
||||
|
||||
return new VersionedProfileResponse(
|
||||
@@ -467,7 +457,7 @@ public class ProfileController {
|
||||
final Instant expiration) {
|
||||
|
||||
try {
|
||||
final ProfileKeyCommitment commitment = new ProfileKeyCommitment(profile.getCommitment());
|
||||
final ProfileKeyCommitment commitment = new ProfileKeyCommitment(profile.commitment());
|
||||
final ProfileKeyCredentialRequest request = new ProfileKeyCredentialRequest(
|
||||
HexFormat.of().parseHex(encodedCredentialRequest));
|
||||
|
||||
@@ -477,23 +467,6 @@ public class ProfileController {
|
||||
}
|
||||
}
|
||||
|
||||
private ProfileAvatarUploadAttributes generateAvatarUploadForm(String objectName) {
|
||||
ZonedDateTime now = ZonedDateTime.now(ZoneOffset.UTC);
|
||||
Pair<String, String> policy = policyGenerator.createFor(now, objectName, 10 * 1024 * 1024);
|
||||
String signature = policySigner.getSignature(now, policy.second());
|
||||
|
||||
return new ProfileAvatarUploadAttributes(objectName, policy.first(), "private", "AWS4-HMAC-SHA256",
|
||||
now.format(PostPolicyGenerator.AWS_DATE_TIME), policy.second(), signature);
|
||||
|
||||
}
|
||||
|
||||
private String generateAvatarObjectName() {
|
||||
byte[] object = new byte[16];
|
||||
new SecureRandom().nextBytes(object);
|
||||
|
||||
return "profiles/" + Base64.getUrlEncoder().encodeToString(object);
|
||||
}
|
||||
|
||||
private List<Locale> getAcceptableLanguagesForRequest(ContainerRequestContext containerRequestContext) {
|
||||
try {
|
||||
return containerRequestContext.getAcceptableLanguages();
|
||||
@@ -509,48 +482,6 @@ public class ProfileController {
|
||||
}
|
||||
}
|
||||
|
||||
private List<AccountBadge> mergeBadgeIdsWithExistingAccountBadges(
|
||||
final List<String> badgeIds,
|
||||
final List<AccountBadge> accountBadges) {
|
||||
LinkedHashMap<String, AccountBadge> existingBadges = new LinkedHashMap<>(accountBadges.size());
|
||||
for (final AccountBadge accountBadge : accountBadges) {
|
||||
existingBadges.putIfAbsent(accountBadge.getId(), accountBadge);
|
||||
}
|
||||
|
||||
LinkedHashMap<String, AccountBadge> result = new LinkedHashMap<>(accountBadges.size());
|
||||
for (final String badgeId : badgeIds) {
|
||||
|
||||
// duplicate in the list, ignore it
|
||||
if (result.containsKey(badgeId)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// This is for testing badges and allows them to be added to an account at any time with an expiration of 1 day
|
||||
// in the future.
|
||||
BadgeConfiguration badgeConfiguration = badgeConfigurationMap.get(badgeId);
|
||||
if (badgeConfiguration != null && badgeConfiguration.isTestBadge()) {
|
||||
result.put(badgeId, new AccountBadge(badgeId, clock.instant().plus(Duration.ofDays(1)), true));
|
||||
continue;
|
||||
}
|
||||
|
||||
// reordering or making visible existing badges
|
||||
if (existingBadges.containsKey(badgeId)) {
|
||||
AccountBadge accountBadge = existingBadges.get(badgeId).withVisibility(true);
|
||||
result.put(badgeId, accountBadge);
|
||||
}
|
||||
}
|
||||
|
||||
// take any remaining account badges and make them invisible
|
||||
for (final Entry<String, AccountBadge> entry : existingBadges.entrySet()) {
|
||||
if (!result.containsKey(entry.getKey())) {
|
||||
AccountBadge accountBadge = entry.getValue().withVisibility(false);
|
||||
result.put(accountBadge.getId(), accountBadge);
|
||||
}
|
||||
}
|
||||
|
||||
return new ArrayList<>(result.values());
|
||||
}
|
||||
|
||||
/**
|
||||
* Verifies that the requester has permission to view the profile of the account identified by the given ACI.
|
||||
*
|
||||
@@ -588,4 +519,20 @@ public class ProfileController {
|
||||
private boolean isSelfProfileRequest(final Optional<Account> maybeRequester, final AciServiceIdentifier targetIdentifier) {
|
||||
return maybeRequester.map(requester -> requester.getUuid().equals(targetIdentifier.uuid())).orElse(false);
|
||||
}
|
||||
|
||||
@Nullable
|
||||
private static byte[] decodeFromBase64(@Nullable final String input) {
|
||||
if (input == null) {
|
||||
return null;
|
||||
}
|
||||
return Base64.getDecoder().decode(input);
|
||||
}
|
||||
|
||||
@Nullable
|
||||
private static String encodeToBase64(@Nullable final byte[] input) {
|
||||
if (input == null) {
|
||||
return null;
|
||||
}
|
||||
return Base64.getEncoder().encodeToString(input);
|
||||
}
|
||||
}
|
||||
-2
@@ -5,7 +5,6 @@
|
||||
|
||||
package org.whispersystems.textsecuregcm.controllers;
|
||||
|
||||
import com.codahale.metrics.annotation.Timed;
|
||||
import io.dropwizard.auth.Auth;
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
import java.util.Base64;
|
||||
@@ -37,7 +36,6 @@ public class ProvisioningController {
|
||||
this.provisioningManager = provisioningManager;
|
||||
}
|
||||
|
||||
@Timed
|
||||
@Path("/{destination}")
|
||||
@PUT
|
||||
@Consumes(MediaType.APPLICATION_JSON)
|
||||
|
||||
-6
@@ -7,7 +7,6 @@ package org.whispersystems.textsecuregcm.controllers;
|
||||
|
||||
import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
|
||||
|
||||
import com.codahale.metrics.annotation.Timed;
|
||||
import com.google.common.net.HttpHeaders;
|
||||
import io.micrometer.core.instrument.DistributionSummary;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
@@ -34,8 +33,6 @@ import javax.ws.rs.Produces;
|
||||
import javax.ws.rs.WebApplicationException;
|
||||
import javax.ws.rs.core.MediaType;
|
||||
import javax.ws.rs.core.Response;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.auth.BasicAuthorizationHeader;
|
||||
import org.whispersystems.textsecuregcm.auth.PhoneVerificationTokenManager;
|
||||
import org.whispersystems.textsecuregcm.auth.RegistrationLockVerificationManager;
|
||||
@@ -57,8 +54,6 @@ import org.whispersystems.textsecuregcm.util.Util;
|
||||
@io.swagger.v3.oas.annotations.tags.Tag(name = "Registration")
|
||||
public class RegistrationController {
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(RegistrationController.class);
|
||||
|
||||
private static final DistributionSummary REREGISTRATION_IDLE_DAYS_DISTRIBUTION = DistributionSummary
|
||||
.builder(name(RegistrationController.class, "reregistrationIdleDays"))
|
||||
.publishPercentiles(0.75, 0.95, 0.99, 0.999)
|
||||
@@ -90,7 +85,6 @@ public class RegistrationController {
|
||||
this.rateLimiters = rateLimiters;
|
||||
}
|
||||
|
||||
@Timed
|
||||
@POST
|
||||
@Consumes(MediaType.APPLICATION_JSON)
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
|
||||
-4
@@ -5,7 +5,6 @@
|
||||
|
||||
package org.whispersystems.textsecuregcm.controllers;
|
||||
|
||||
import com.codahale.metrics.annotation.Timed;
|
||||
import com.google.api.client.googleapis.auth.oauth2.GoogleIdToken;
|
||||
import com.google.api.client.googleapis.auth.oauth2.GoogleIdTokenVerifier;
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
@@ -76,7 +75,6 @@ public class RemoteConfigController {
|
||||
this.googleIdTokenVerifier = googleIdTokenVerifierBuilder.setAudience(audience).build();
|
||||
}
|
||||
|
||||
@Timed
|
||||
@GET
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
public UserRemoteConfigList getAll(@Auth AuthenticatedAccount auth) {
|
||||
@@ -98,7 +96,6 @@ public class RemoteConfigController {
|
||||
}
|
||||
}
|
||||
|
||||
@Timed
|
||||
@PUT
|
||||
@Consumes(MediaType.APPLICATION_JSON)
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@@ -123,7 +120,6 @@ public class RemoteConfigController {
|
||||
remoteConfigsManager.set(config);
|
||||
}
|
||||
|
||||
@Timed
|
||||
@DELETE
|
||||
@Path("/{name}")
|
||||
public void delete(@HeaderParam("Config-Token") String configToken, @PathParam("name") String name) {
|
||||
|
||||
-3
@@ -7,7 +7,6 @@ package org.whispersystems.textsecuregcm.controllers;
|
||||
|
||||
import static java.util.Objects.requireNonNull;
|
||||
|
||||
import com.codahale.metrics.annotation.Timed;
|
||||
import io.dropwizard.auth.Auth;
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
import io.swagger.v3.oas.annotations.responses.ApiResponse;
|
||||
@@ -69,7 +68,6 @@ public class SecureBackupController {
|
||||
this.accountsManager = requireNonNull(accountsManager);
|
||||
}
|
||||
|
||||
@Timed
|
||||
@GET
|
||||
@Path("/auth")
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@@ -86,7 +84,6 @@ public class SecureBackupController {
|
||||
return credentialsGenerator.generateForUuid(auth.getAccount().getUuid());
|
||||
}
|
||||
|
||||
@Timed
|
||||
@POST
|
||||
@Path("/auth/check")
|
||||
@Consumes(MediaType.APPLICATION_JSON)
|
||||
|
||||
-2
@@ -5,7 +5,6 @@
|
||||
|
||||
package org.whispersystems.textsecuregcm.controllers;
|
||||
|
||||
import com.codahale.metrics.annotation.Timed;
|
||||
import io.dropwizard.auth.Auth;
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
import javax.ws.rs.GET;
|
||||
@@ -34,7 +33,6 @@ public class SecureStorageController {
|
||||
this.storageServiceCredentialsGenerator = storageServiceCredentialsGenerator;
|
||||
}
|
||||
|
||||
@Timed
|
||||
@GET
|
||||
@Path("/auth")
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
|
||||
-3
@@ -5,7 +5,6 @@
|
||||
|
||||
package org.whispersystems.textsecuregcm.controllers;
|
||||
|
||||
import com.codahale.metrics.annotation.Timed;
|
||||
import io.dropwizard.auth.Auth;
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
import io.swagger.v3.oas.annotations.responses.ApiResponse;
|
||||
@@ -66,7 +65,6 @@ public class SecureValueRecovery2Controller {
|
||||
this.accountsManager = accountsManager;
|
||||
}
|
||||
|
||||
@Timed
|
||||
@GET
|
||||
@Path("/auth")
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@@ -84,7 +82,6 @@ public class SecureValueRecovery2Controller {
|
||||
}
|
||||
|
||||
|
||||
@Timed
|
||||
@POST
|
||||
@Path("/auth/check")
|
||||
@Consumes(MediaType.APPLICATION_JSON)
|
||||
|
||||
-19
@@ -7,7 +7,6 @@ package org.whispersystems.textsecuregcm.controllers;
|
||||
|
||||
import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
|
||||
|
||||
import com.codahale.metrics.annotation.Timed;
|
||||
import com.fasterxml.jackson.annotation.JsonCreator;
|
||||
import com.fasterxml.jackson.annotation.JsonInclude;
|
||||
import com.fasterxml.jackson.annotation.JsonInclude.Include;
|
||||
@@ -220,7 +219,6 @@ public class SubscriptionController {
|
||||
return new GetSubscriptionConfigurationResponse(currencyConfiguration, levels);
|
||||
}
|
||||
|
||||
@Timed
|
||||
@DELETE
|
||||
@Path("/{subscriberId}")
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@@ -242,7 +240,6 @@ public class SubscriptionController {
|
||||
.thenApply(unused -> Response.ok().build());
|
||||
}
|
||||
|
||||
@Timed
|
||||
@PUT
|
||||
@Path("/{subscriberId}")
|
||||
@Consumes(MediaType.APPLICATION_JSON)
|
||||
@@ -277,7 +274,6 @@ public class SubscriptionController {
|
||||
|
||||
}
|
||||
|
||||
@Timed
|
||||
@POST
|
||||
@Path("/{subscriberId}/create_payment_method")
|
||||
@Consumes(MediaType.APPLICATION_JSON)
|
||||
@@ -332,7 +328,6 @@ public class SubscriptionController {
|
||||
|
||||
}
|
||||
|
||||
@Timed
|
||||
@POST
|
||||
@Path("/{subscriberId}/create_payment_method/paypal")
|
||||
@Consumes(MediaType.APPLICATION_JSON)
|
||||
@@ -396,7 +391,6 @@ public class SubscriptionController {
|
||||
};
|
||||
}
|
||||
|
||||
@Timed
|
||||
@POST
|
||||
@Path("/{subscriberId}/default_payment_method/{paymentMethodId}")
|
||||
@Consumes(MediaType.APPLICATION_JSON)
|
||||
@@ -414,7 +408,6 @@ public class SubscriptionController {
|
||||
.thenApply(customer -> Response.ok().build());
|
||||
}
|
||||
|
||||
@Timed
|
||||
@POST
|
||||
@Path("/{subscriberId}/default_payment_method/{processor}/{paymentMethodToken}")
|
||||
@Consumes(MediaType.APPLICATION_JSON)
|
||||
@@ -497,7 +490,6 @@ public class SubscriptionController {
|
||||
}
|
||||
}
|
||||
|
||||
@Timed
|
||||
@PUT
|
||||
@Path("/{subscriberId}/level/{level}/{currency}/{idempotencyKey}")
|
||||
@Consumes(MediaType.APPLICATION_JSON)
|
||||
@@ -655,7 +647,6 @@ public class SubscriptionController {
|
||||
|
||||
}
|
||||
|
||||
@Timed
|
||||
@GET
|
||||
@Path("/configuration")
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@@ -666,7 +657,6 @@ public class SubscriptionController {
|
||||
});
|
||||
}
|
||||
|
||||
@Timed
|
||||
@GET
|
||||
@Path("/levels")
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@@ -714,7 +704,6 @@ public class SubscriptionController {
|
||||
}
|
||||
}
|
||||
|
||||
@Timed
|
||||
@GET
|
||||
@Path("/boost/badges")
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@@ -737,7 +726,6 @@ public class SubscriptionController {
|
||||
});
|
||||
}
|
||||
|
||||
@Timed
|
||||
@GET
|
||||
@Path("/boost/amounts")
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@@ -749,7 +737,6 @@ public class SubscriptionController {
|
||||
.build());
|
||||
}
|
||||
|
||||
@Timed
|
||||
@GET
|
||||
@Path("/boost/amounts/gift")
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@@ -801,7 +788,6 @@ public class SubscriptionController {
|
||||
/**
|
||||
* Creates a Stripe PaymentIntent with the requested amount and currency
|
||||
*/
|
||||
@Timed
|
||||
@POST
|
||||
@Path("/boost/create")
|
||||
@Consumes(MediaType.APPLICATION_JSON)
|
||||
@@ -855,7 +841,6 @@ public class SubscriptionController {
|
||||
}
|
||||
}
|
||||
|
||||
@Timed
|
||||
@POST
|
||||
@Path("/boost/paypal/create")
|
||||
@Consumes(MediaType.APPLICATION_JSON)
|
||||
@@ -898,7 +883,6 @@ public class SubscriptionController {
|
||||
|
||||
}
|
||||
|
||||
@Timed
|
||||
@POST
|
||||
@Path("/boost/paypal/confirm")
|
||||
@Consumes(MediaType.APPLICATION_JSON)
|
||||
@@ -945,7 +929,6 @@ public class SubscriptionController {
|
||||
}
|
||||
}
|
||||
|
||||
@Timed
|
||||
@POST
|
||||
@Path("/boost/receipt_credentials")
|
||||
@Consumes(MediaType.APPLICATION_JSON)
|
||||
@@ -1158,7 +1141,6 @@ public class SubscriptionController {
|
||||
}
|
||||
}
|
||||
|
||||
@Timed
|
||||
@GET
|
||||
@Path("/{subscriberId}")
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@@ -1236,7 +1218,6 @@ public class SubscriptionController {
|
||||
}
|
||||
}
|
||||
|
||||
@Timed
|
||||
@POST
|
||||
@Path("/{subscriberId}/receipt_credentials")
|
||||
@Consumes(MediaType.APPLICATION_JSON)
|
||||
|
||||
+1
-7
@@ -7,7 +7,6 @@ package org.whispersystems.textsecuregcm.controllers;
|
||||
|
||||
import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
|
||||
|
||||
import com.codahale.metrics.annotation.Timed;
|
||||
import com.google.i18n.phonenumbers.NumberParseException;
|
||||
import com.google.i18n.phonenumbers.PhoneNumberUtil;
|
||||
import com.google.i18n.phonenumbers.Phonenumber;
|
||||
@@ -78,8 +77,8 @@ import org.whispersystems.textsecuregcm.registration.TransportNotAllowedExceptio
|
||||
import org.whispersystems.textsecuregcm.registration.VerificationSession;
|
||||
import org.whispersystems.textsecuregcm.spam.Extract;
|
||||
import org.whispersystems.textsecuregcm.spam.FilterSpam;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountsManager;
|
||||
import org.whispersystems.textsecuregcm.spam.ScoreThreshold;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.RegistrationRecoveryPasswordsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.VerificationSessionManager;
|
||||
import org.whispersystems.textsecuregcm.util.ExceptionUtils;
|
||||
@@ -137,7 +136,6 @@ public class VerificationController {
|
||||
this.clock = clock;
|
||||
}
|
||||
|
||||
@Timed
|
||||
@POST
|
||||
@Path("/session")
|
||||
@Consumes(MediaType.APPLICATION_JSON)
|
||||
@@ -188,7 +186,6 @@ public class VerificationController {
|
||||
return buildResponse(registrationServiceSession, verificationSession);
|
||||
}
|
||||
|
||||
@Timed
|
||||
@FilterSpam
|
||||
@PATCH
|
||||
@Path("/session/{sessionId}")
|
||||
@@ -411,7 +408,6 @@ public class VerificationController {
|
||||
return verificationSession;
|
||||
}
|
||||
|
||||
@Timed
|
||||
@GET
|
||||
@Path("/session/{sessionId}")
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@@ -423,7 +419,6 @@ public class VerificationController {
|
||||
return buildResponse(registrationServiceSession, verificationSession);
|
||||
}
|
||||
|
||||
@Timed
|
||||
@POST
|
||||
@Path("/session/{sessionId}/code")
|
||||
@Consumes(MediaType.APPLICATION_JSON)
|
||||
@@ -518,7 +513,6 @@ public class VerificationController {
|
||||
return buildResponse(resultSession, verificationSession);
|
||||
}
|
||||
|
||||
@Timed
|
||||
@PUT
|
||||
@Path("/session/{sessionId}/code")
|
||||
@Consumes(MediaType.APPLICATION_JSON)
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
package org.whispersystems.textsecuregcm.entities;
|
||||
|
||||
public enum AvatarChange {
|
||||
AVATAR_CHANGE_UNCHANGED,
|
||||
AVATAR_CHANGE_CLEAR,
|
||||
AVATAR_CHANGE_UPDATE
|
||||
}
|
||||
+18
-6
@@ -9,11 +9,23 @@ import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
|
||||
public record UserCapabilities(
|
||||
@JsonProperty("gv1-migration") boolean gv1Migration,
|
||||
@Deprecated(forRemoval = true)
|
||||
@JsonProperty("gv1-migration")
|
||||
boolean gv1Migration,
|
||||
|
||||
@Deprecated(forRemoval = true)
|
||||
boolean senderKey,
|
||||
|
||||
@Deprecated(forRemoval = true)
|
||||
boolean announcementGroup,
|
||||
|
||||
@Deprecated(forRemoval = true)
|
||||
boolean changeNumber,
|
||||
|
||||
@Deprecated(forRemoval = true)
|
||||
boolean stories,
|
||||
|
||||
@Deprecated(forRemoval = true)
|
||||
boolean giftBadges,
|
||||
boolean paymentActivation,
|
||||
boolean pni) {
|
||||
@@ -21,11 +33,11 @@ public record UserCapabilities(
|
||||
public static UserCapabilities createForAccount(Account account) {
|
||||
return new UserCapabilities(
|
||||
true,
|
||||
account.isSenderKeySupported(),
|
||||
account.isAnnouncementGroupSupported(),
|
||||
account.isChangeNumberSupported(),
|
||||
account.isStoriesSupported(),
|
||||
account.isGiftBadgesSupported(),
|
||||
true,
|
||||
true,
|
||||
true,
|
||||
true,
|
||||
true,
|
||||
|
||||
// Hardcode payment activation flag to false until all clients support the flow
|
||||
false,
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
package org.whispersystems.textsecuregcm.grpc;
|
||||
|
||||
import io.grpc.Status;
|
||||
import org.whispersystems.textsecuregcm.entities.AvatarChange;
|
||||
|
||||
public class AvatarChangeUtil {
|
||||
public static AvatarChange fromGrpcAvatarChange(final org.signal.chat.profile.SetProfileRequest.AvatarChange avatarChangeType) {
|
||||
return switch (avatarChangeType) {
|
||||
case AVATAR_CHANGE_UNCHANGED -> AvatarChange.AVATAR_CHANGE_UNCHANGED;
|
||||
case AVATAR_CHANGE_CLEAR -> AvatarChange.AVATAR_CHANGE_CLEAR;
|
||||
case AVATAR_CHANGE_UPDATE -> AvatarChange.AVATAR_CHANGE_UPDATE;
|
||||
case UNRECOGNIZED -> throw Status.INVALID_ARGUMENT.withDescription("Invalid avatar change value").asRuntimeException();
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
/*
|
||||
* Copyright 2023 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.grpc;
|
||||
|
||||
import org.signal.chat.calling.GetTurnCredentialsRequest;
|
||||
import org.signal.chat.calling.GetTurnCredentialsResponse;
|
||||
import org.signal.chat.calling.ReactorCallingGrpc;
|
||||
import org.whispersystems.textsecuregcm.auth.TurnTokenGenerator;
|
||||
import org.whispersystems.textsecuregcm.auth.grpc.AuthenticatedDevice;
|
||||
import org.whispersystems.textsecuregcm.auth.grpc.AuthenticationUtil;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimiters;
|
||||
import reactor.core.publisher.Mono;
|
||||
|
||||
public class CallingGrpcService extends ReactorCallingGrpc.CallingImplBase {
|
||||
|
||||
private final TurnTokenGenerator turnTokenGenerator;
|
||||
private final RateLimiters rateLimiters;
|
||||
|
||||
public CallingGrpcService(final TurnTokenGenerator turnTokenGenerator, final RateLimiters rateLimiters) {
|
||||
this.turnTokenGenerator = turnTokenGenerator;
|
||||
this.rateLimiters = rateLimiters;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected Throwable onErrorMap(final Throwable throwable) {
|
||||
return RateLimitUtil.mapRateLimitExceededException(throwable);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Mono<GetTurnCredentialsResponse> getTurnCredentials(final GetTurnCredentialsRequest request) {
|
||||
final AuthenticatedDevice authenticatedDevice = AuthenticationUtil.requireAuthenticatedDevice();
|
||||
|
||||
return rateLimiters.getTurnLimiter().validateReactive(authenticatedDevice.accountIdentifier())
|
||||
.then(Mono.fromSupplier(() -> turnTokenGenerator.generate(authenticatedDevice.accountIdentifier())))
|
||||
.map(turnToken -> GetTurnCredentialsResponse.newBuilder()
|
||||
.setUsername(turnToken.username())
|
||||
.setPassword(turnToken.password())
|
||||
.addAllUrls(turnToken.urls())
|
||||
.build());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,165 @@
|
||||
package org.whispersystems.textsecuregcm.grpc;
|
||||
|
||||
import com.google.protobuf.ByteString;
|
||||
import io.grpc.Status;
|
||||
import org.signal.chat.profile.SetProfileRequest.AvatarChange;
|
||||
import org.signal.chat.profile.ProfileAvatarUploadAttributes;
|
||||
import org.signal.chat.profile.ReactorProfileGrpc;
|
||||
import org.signal.chat.profile.SetProfileRequest;
|
||||
import org.signal.chat.profile.SetProfileResponse;
|
||||
import org.whispersystems.textsecuregcm.auth.grpc.AuthenticationUtil;
|
||||
import org.whispersystems.textsecuregcm.configuration.BadgeConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.BadgesConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
|
||||
import org.whispersystems.textsecuregcm.s3.PolicySigner;
|
||||
import org.whispersystems.textsecuregcm.s3.PostPolicyGenerator;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountBadge;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.DynamicConfigurationManager;
|
||||
import org.whispersystems.textsecuregcm.storage.ProfilesManager;
|
||||
import org.whispersystems.textsecuregcm.storage.VersionedProfile;
|
||||
import reactor.core.publisher.Flux;
|
||||
import reactor.core.publisher.Mono;
|
||||
import software.amazon.awssdk.services.s3.S3AsyncClient;
|
||||
import software.amazon.awssdk.services.s3.model.DeleteObjectRequest;
|
||||
import java.time.Clock;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.function.Function;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
public class ProfileGrpcService extends ReactorProfileGrpc.ProfileImplBase {
|
||||
private final Clock clock;
|
||||
|
||||
private final ProfilesManager profilesManager;
|
||||
private final AccountsManager accountsManager;
|
||||
private final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager;
|
||||
private final Map<String, BadgeConfiguration> badgeConfigurationMap;
|
||||
private final PolicySigner policySigner;
|
||||
private final PostPolicyGenerator policyGenerator;
|
||||
|
||||
private final S3AsyncClient asyncS3client;
|
||||
private final String bucket;
|
||||
|
||||
private record AvatarData(Optional<String> currentAvatar,
|
||||
Optional<String> finalAvatar,
|
||||
Optional<ProfileAvatarUploadAttributes> uploadAttributes) {}
|
||||
|
||||
public ProfileGrpcService(
|
||||
Clock clock,
|
||||
AccountsManager accountsManager,
|
||||
ProfilesManager profilesManager,
|
||||
DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager,
|
||||
BadgesConfiguration badgesConfiguration,
|
||||
S3AsyncClient asyncS3client,
|
||||
PostPolicyGenerator policyGenerator,
|
||||
PolicySigner policySigner,
|
||||
String bucket) {
|
||||
this.clock = clock;
|
||||
this.accountsManager = accountsManager;
|
||||
this.profilesManager = profilesManager;
|
||||
this.dynamicConfigurationManager = dynamicConfigurationManager;
|
||||
this.badgeConfigurationMap = badgesConfiguration.getBadges().stream().collect(Collectors.toMap(
|
||||
BadgeConfiguration::getId, Function.identity()));
|
||||
this.bucket = bucket;
|
||||
this.asyncS3client = asyncS3client;
|
||||
this.policyGenerator = policyGenerator;
|
||||
this.policySigner = policySigner;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Mono<SetProfileResponse> setProfile(SetProfileRequest request) {
|
||||
validateRequest(request);
|
||||
return Mono.fromSupplier(AuthenticationUtil::requireAuthenticatedDevice)
|
||||
.flatMap(authenticatedDevice -> Mono.zip(
|
||||
Mono.fromFuture(accountsManager.getByAccountIdentifierAsync(authenticatedDevice.accountIdentifier()))
|
||||
.map(maybeAccount -> maybeAccount.orElseThrow(Status.UNAUTHENTICATED::asRuntimeException)),
|
||||
Mono.fromFuture(profilesManager.getAsync(authenticatedDevice.accountIdentifier(), request.getVersion()))
|
||||
))
|
||||
.doOnNext(accountAndMaybeProfile -> {
|
||||
if (!request.getPaymentAddress().isEmpty()) {
|
||||
final boolean hasDisallowedPrefix =
|
||||
dynamicConfigurationManager.getConfiguration().getPaymentsConfiguration().getDisallowedPrefixes().stream()
|
||||
.anyMatch(prefix -> accountAndMaybeProfile.getT1().getNumber().startsWith(prefix));
|
||||
if (hasDisallowedPrefix && accountAndMaybeProfile.getT2().map(VersionedProfile::paymentAddress).isEmpty()) {
|
||||
throw Status.PERMISSION_DENIED.asRuntimeException();
|
||||
}
|
||||
}
|
||||
})
|
||||
.flatMap(accountAndMaybeProfile -> {
|
||||
final Account account = accountAndMaybeProfile.getT1();
|
||||
final Optional<String> currentAvatar = accountAndMaybeProfile.getT2().map(VersionedProfile::avatar)
|
||||
.filter(avatar -> avatar.startsWith("profiles/"));
|
||||
final AvatarData avatarData = switch (AvatarChangeUtil.fromGrpcAvatarChange(request.getAvatarChange())) {
|
||||
case AVATAR_CHANGE_UNCHANGED -> new AvatarData(currentAvatar, currentAvatar, Optional.empty());
|
||||
case AVATAR_CHANGE_CLEAR -> new AvatarData(currentAvatar, Optional.empty(), Optional.empty());
|
||||
case AVATAR_CHANGE_UPDATE -> {
|
||||
final String updateAvatarObjectName = ProfileHelper.generateAvatarObjectName();
|
||||
yield new AvatarData(currentAvatar, Optional.of(updateAvatarObjectName),
|
||||
Optional.of(ProfileHelper.generateAvatarUploadFormGrpc(policyGenerator, policySigner, updateAvatarObjectName)));
|
||||
}
|
||||
};
|
||||
|
||||
final Mono<Void> profileSetMono = Mono.fromFuture(profilesManager.setAsync(account.getUuid(),
|
||||
new VersionedProfile(
|
||||
request.getVersion(),
|
||||
request.getName().toByteArray(),
|
||||
avatarData.finalAvatar().orElse(null),
|
||||
request.getAboutEmoji().toByteArray(),
|
||||
request.getAbout().toByteArray(),
|
||||
request.getPaymentAddress().toByteArray(),
|
||||
request.getCommitment().toByteArray())));
|
||||
|
||||
final List<Mono<?>> updates = new ArrayList<>(2);
|
||||
final List<AccountBadge> updatedBadges = Optional.of(request.getBadgeIdsList())
|
||||
.map(badges -> ProfileHelper.mergeBadgeIdsWithExistingAccountBadges(clock, badgeConfigurationMap, badges, account.getBadges()))
|
||||
.orElseGet(account::getBadges);
|
||||
|
||||
updates.add(Mono.fromFuture(accountsManager.updateAsync(account, a -> {
|
||||
a.setBadges(clock, updatedBadges);
|
||||
a.setCurrentProfileVersion(request.getVersion());
|
||||
})));
|
||||
if (request.getAvatarChange() != AvatarChange.AVATAR_CHANGE_UNCHANGED && avatarData.currentAvatar().isPresent()) {
|
||||
updates.add(Mono.fromFuture(asyncS3client.deleteObject(DeleteObjectRequest.builder()
|
||||
.bucket(bucket)
|
||||
.key(avatarData.currentAvatar().get())
|
||||
.build())));
|
||||
}
|
||||
return profileSetMono.thenMany(Flux.merge(updates)).then(Mono.just(avatarData));
|
||||
})
|
||||
.map(avatarData -> avatarData.uploadAttributes()
|
||||
.map(avatarUploadAttributes -> SetProfileResponse.newBuilder().setAttributes(avatarUploadAttributes).build())
|
||||
.orElse(SetProfileResponse.newBuilder().build())
|
||||
);
|
||||
}
|
||||
|
||||
private void validateRequest(SetProfileRequest request) {
|
||||
if (request.getVersion().isEmpty()) {
|
||||
throw Status.INVALID_ARGUMENT.withDescription("Missing version").asRuntimeException();
|
||||
}
|
||||
|
||||
if (request.getCommitment().isEmpty()) {
|
||||
throw Status.INVALID_ARGUMENT.withDescription("Missing profile commitment").asRuntimeException();
|
||||
}
|
||||
|
||||
checkByteStringLength(request.getName(), "Invalid name length", List.of(81, 285));
|
||||
checkByteStringLength(request.getAboutEmoji(), "Invalid about emoji length", List.of(0, 60));
|
||||
checkByteStringLength(request.getAbout(), "Invalid about length", List.of(0, 156, 282, 540));
|
||||
checkByteStringLength(request.getPaymentAddress(), "Invalid mobile coin address length", List.of(0, 582));
|
||||
}
|
||||
|
||||
private static void checkByteStringLength(final ByteString byteString, final String errorMessage, final List<Integer> allowedLengths) {
|
||||
final int byteStringLength = byteString.toByteArray().length;
|
||||
|
||||
for (int allowedLength : allowedLengths) {
|
||||
if (byteStringLength == allowedLength) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
throw Status.INVALID_ARGUMENT.withDescription(errorMessage).asRuntimeException();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
package org.whispersystems.textsecuregcm.grpc;
|
||||
|
||||
import com.google.protobuf.ByteString;
|
||||
import java.security.SecureRandom;
|
||||
import java.time.Clock;
|
||||
import java.time.Duration;
|
||||
import java.time.ZoneOffset;
|
||||
import java.time.ZonedDateTime;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Base64;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import org.signal.chat.profile.ProfileAvatarUploadAttributes;
|
||||
import org.whispersystems.textsecuregcm.configuration.BadgeConfiguration;
|
||||
import org.whispersystems.textsecuregcm.s3.PolicySigner;
|
||||
import org.whispersystems.textsecuregcm.s3.PostPolicyGenerator;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountBadge;
|
||||
import org.whispersystems.textsecuregcm.util.Pair;
|
||||
|
||||
public class ProfileHelper {
|
||||
public static List<AccountBadge> mergeBadgeIdsWithExistingAccountBadges(
|
||||
final Clock clock,
|
||||
final Map<String, BadgeConfiguration> badgeConfigurationMap,
|
||||
final List<String> badgeIds,
|
||||
final List<AccountBadge> accountBadges) {
|
||||
LinkedHashMap<String, AccountBadge> existingBadges = new LinkedHashMap<>(accountBadges.size());
|
||||
for (final AccountBadge accountBadge : accountBadges) {
|
||||
existingBadges.putIfAbsent(accountBadge.getId(), accountBadge);
|
||||
}
|
||||
|
||||
LinkedHashMap<String, AccountBadge> result = new LinkedHashMap<>(accountBadges.size());
|
||||
for (final String badgeId : badgeIds) {
|
||||
|
||||
// duplicate in the list, ignore it
|
||||
if (result.containsKey(badgeId)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// This is for testing badges and allows them to be added to an account at any time with an expiration of 1 day
|
||||
// in the future.
|
||||
BadgeConfiguration badgeConfiguration = badgeConfigurationMap.get(badgeId);
|
||||
if (badgeConfiguration != null && badgeConfiguration.isTestBadge()) {
|
||||
result.put(badgeId, new AccountBadge(badgeId, clock.instant().plus(Duration.ofDays(1)), true));
|
||||
continue;
|
||||
}
|
||||
|
||||
// reordering or making visible existing badges
|
||||
if (existingBadges.containsKey(badgeId)) {
|
||||
AccountBadge accountBadge = existingBadges.get(badgeId).withVisibility(true);
|
||||
result.put(badgeId, accountBadge);
|
||||
}
|
||||
}
|
||||
|
||||
// take any remaining account badges and make them invisible
|
||||
for (final Map.Entry<String, AccountBadge> entry : existingBadges.entrySet()) {
|
||||
if (!result.containsKey(entry.getKey())) {
|
||||
AccountBadge accountBadge = entry.getValue().withVisibility(false);
|
||||
result.put(accountBadge.getId(), accountBadge);
|
||||
}
|
||||
}
|
||||
|
||||
return new ArrayList<>(result.values());
|
||||
}
|
||||
|
||||
public static String generateAvatarObjectName() {
|
||||
byte[] object = new byte[16];
|
||||
new SecureRandom().nextBytes(object);
|
||||
|
||||
return "profiles/" + Base64.getUrlEncoder().encodeToString(object);
|
||||
}
|
||||
|
||||
public static org.signal.chat.profile.ProfileAvatarUploadAttributes generateAvatarUploadFormGrpc(
|
||||
final PostPolicyGenerator policyGenerator,
|
||||
final PolicySigner policySigner,
|
||||
final String objectName) {
|
||||
final ZonedDateTime now = ZonedDateTime.now(ZoneOffset.UTC);
|
||||
final Pair<String, String> policy = policyGenerator.createFor(now, objectName, 10 * 1024 * 1024);
|
||||
final String signature = policySigner.getSignature(now, policy.second());
|
||||
|
||||
return org.signal.chat.profile.ProfileAvatarUploadAttributes.newBuilder()
|
||||
.setPath(objectName)
|
||||
.setCredential(policy.first())
|
||||
.setAcl("private")
|
||||
.setAlgorithm("AWS4-HMAC-SHA256")
|
||||
.setDate(now.format(PostPolicyGenerator.AWS_DATE_TIME))
|
||||
.setPolicy(policy.second())
|
||||
.setSignature(ByteString.copyFrom(signature.getBytes()))
|
||||
.build();
|
||||
}
|
||||
|
||||
public static org.whispersystems.textsecuregcm.entities.ProfileAvatarUploadAttributes generateAvatarUploadForm(
|
||||
final PostPolicyGenerator policyGenerator,
|
||||
final PolicySigner policySigner,
|
||||
final String objectName) {
|
||||
ZonedDateTime now = ZonedDateTime.now(ZoneOffset.UTC);
|
||||
Pair<String, String> policy = policyGenerator.createFor(now, objectName, 10 * 1024 * 1024);
|
||||
String signature = policySigner.getSignature(now, policy.second());
|
||||
|
||||
return new org.whispersystems.textsecuregcm.entities.ProfileAvatarUploadAttributes(objectName, policy.first(), "private", "AWS4-HMAC-SHA256",
|
||||
now.format(PostPolicyGenerator.AWS_DATE_TIME), policy.second(), signature);
|
||||
|
||||
}
|
||||
}
|
||||
@@ -58,6 +58,10 @@ public interface RateLimiter {
|
||||
return Mono.fromFuture(validateAsync(key).toCompletableFuture());
|
||||
}
|
||||
|
||||
default Mono<Void> validateReactive(final UUID accountUuid) {
|
||||
return validateReactive(accountUuid.toString());
|
||||
}
|
||||
|
||||
default boolean hasAvailablePermits(final UUID accountUuid, final int permits) {
|
||||
return hasAvailablePermits(accountUuid.toString(), permits);
|
||||
}
|
||||
|
||||
+3
-1
@@ -12,9 +12,11 @@ import org.whispersystems.textsecuregcm.registration.RegistrationServiceSenderEx
|
||||
|
||||
public class RegistrationServiceSenderExceptionMapper implements ExceptionMapper<RegistrationServiceSenderException> {
|
||||
|
||||
public static int REMOTE_SERVICE_REJECTED_REQUEST_STATUS = 440;
|
||||
|
||||
@Override
|
||||
public Response toResponse(final RegistrationServiceSenderException exception) {
|
||||
return Response.status(Response.Status.BAD_GATEWAY)
|
||||
return Response.status(REMOTE_SERVICE_REJECTED_REQUEST_STATUS)
|
||||
.entity(new SendVerificationCodeFailureResponse(exception.getReason(), exception.isPermanent()))
|
||||
.build();
|
||||
}
|
||||
|
||||
@@ -6,8 +6,10 @@
|
||||
package org.whispersystems.textsecuregcm.metrics;
|
||||
|
||||
import com.codahale.metrics.SharedMetricRegistries;
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import io.dropwizard.setup.Environment;
|
||||
import io.micrometer.core.instrument.Meter;
|
||||
import io.micrometer.core.instrument.MeterRegistry;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import io.micrometer.core.instrument.Tags;
|
||||
import io.micrometer.core.instrument.config.MeterFilter;
|
||||
@@ -42,42 +44,17 @@ public class MetricsUtil {
|
||||
public static void configureRegistries(final WhisperServerConfiguration config, final Environment environment) {
|
||||
SharedMetricRegistries.add(Constants.METRICS_NAME, environment.metrics());
|
||||
|
||||
final DistributionStatisticConfig defaultDistributionStatisticConfig = DistributionStatisticConfig.builder()
|
||||
.percentiles(.75, .95, .99, .999)
|
||||
.build();
|
||||
|
||||
{
|
||||
final DatadogMeterRegistry datadogMeterRegistry = new DatadogMeterRegistry(
|
||||
config.getDatadogConfiguration(), io.micrometer.core.instrument.Clock.SYSTEM);
|
||||
|
||||
datadogMeterRegistry.config().commonTags(
|
||||
Tags.of(
|
||||
"service", "chat",
|
||||
"host", HostnameUtil.getLocalHostname(),
|
||||
"version", WhisperServerVersion.getServerVersion(),
|
||||
"env", config.getDatadogConfiguration().getEnvironment()))
|
||||
.meterFilter(new MeterFilter() {
|
||||
@Override
|
||||
public DistributionStatisticConfig configure(final Meter.Id id, final DistributionStatisticConfig config) {
|
||||
return defaultDistributionStatisticConfig.merge(config);
|
||||
}
|
||||
});
|
||||
|
||||
// Remove high-cardinality `command` tags from Lettuce metrics and prepend "chat." to meter names
|
||||
datadogMeterRegistry.config().meterFilter(new MeterFilter() {
|
||||
@Override
|
||||
public Meter.Id map(final Meter.Id id) {
|
||||
if (id.getName().startsWith("lettuce")) {
|
||||
return id.withName(PREFIX + "." + id.getName())
|
||||
.replaceTags(id.getTags().stream()
|
||||
.filter(tag -> !"command".equals(tag.getKey()))
|
||||
.toList());
|
||||
}
|
||||
|
||||
return MeterFilter.super.map(id);
|
||||
}
|
||||
});
|
||||
|
||||
Tags.of(
|
||||
"service", "chat",
|
||||
"host", HostnameUtil.getLocalHostname(),
|
||||
"version", WhisperServerVersion.getServerVersion(),
|
||||
"env", config.getDatadogConfiguration().getEnvironment()));
|
||||
configureMeterFilters(datadogMeterRegistry.config());
|
||||
Metrics.addRegistry(datadogMeterRegistry);
|
||||
}
|
||||
|
||||
@@ -85,6 +62,40 @@ public class MetricsUtil {
|
||||
environment.lifecycle().manage(new ApplicationShutdownMonitor(Metrics.globalRegistry));
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
static MeterRegistry.Config configureMeterFilters(MeterRegistry.Config config) {
|
||||
final DistributionStatisticConfig defaultDistributionStatisticConfig = DistributionStatisticConfig.builder()
|
||||
.percentiles(.75, .95, .99, .999)
|
||||
.build();
|
||||
|
||||
return config
|
||||
.meterFilter(new MeterFilter() {
|
||||
@Override
|
||||
public DistributionStatisticConfig configure(final Meter.Id id, final DistributionStatisticConfig config) {
|
||||
return defaultDistributionStatisticConfig.merge(config);
|
||||
}
|
||||
})
|
||||
// Remove high-cardinality `command` tags from Lettuce metrics and prepend "chat." to meter names
|
||||
.meterFilter(new MeterFilter() {
|
||||
@Override
|
||||
public Meter.Id map(final Meter.Id id) {
|
||||
if (id.getName().startsWith("lettuce")) {
|
||||
return id.withName(PREFIX + "." + id.getName())
|
||||
.replaceTags(id.getTags().stream()
|
||||
.filter(tag -> !"command".equals(tag.getKey()))
|
||||
.toList());
|
||||
}
|
||||
|
||||
return MeterFilter.super.map(id);
|
||||
}
|
||||
})
|
||||
// Deny lettuce metrics, but leave command.completions.max. Note that regardless of configured order, accept
|
||||
// filters are applied after map filters.
|
||||
.meterFilter(MeterFilter.deny(id ->
|
||||
id.getName().startsWith(PREFIX + ".lettuce") && !id.getName().contains("command.completion.max")
|
||||
));
|
||||
}
|
||||
|
||||
public static void registerSystemResourceMetrics(final Environment environment) {
|
||||
environment.metrics().register(name(CpuUsageGauge.class, "cpu"), new CpuUsageGauge(3, TimeUnit.SECONDS));
|
||||
environment.metrics().register(name(FreeMemoryGauge.class, "free_memory"), new FreeMemoryGauge());
|
||||
|
||||
@@ -247,45 +247,21 @@ public class Account {
|
||||
public boolean isStorageSupported() {
|
||||
requireNotStale();
|
||||
|
||||
return devices.stream().anyMatch(device -> device.getCapabilities() != null && device.getCapabilities().isStorage());
|
||||
return devices.stream().anyMatch(device -> device.getCapabilities() != null && device.getCapabilities().storage());
|
||||
}
|
||||
|
||||
public boolean isTransferSupported() {
|
||||
requireNotStale();
|
||||
|
||||
return getMasterDevice().map(Device::getCapabilities).map(Device.DeviceCapabilities::isTransfer).orElse(false);
|
||||
}
|
||||
|
||||
public boolean isSenderKeySupported() {
|
||||
return allEnabledDevicesHaveCapability(DeviceCapabilities::isSenderKey);
|
||||
}
|
||||
|
||||
public boolean isAnnouncementGroupSupported() {
|
||||
return allEnabledDevicesHaveCapability(DeviceCapabilities::isAnnouncementGroup);
|
||||
}
|
||||
|
||||
public boolean isChangeNumberSupported() {
|
||||
return allEnabledDevicesHaveCapability(DeviceCapabilities::isChangeNumber);
|
||||
return getMasterDevice().map(Device::getCapabilities).map(Device.DeviceCapabilities::transfer).orElse(false);
|
||||
}
|
||||
|
||||
public boolean isPniSupported() {
|
||||
return allEnabledDevicesHaveCapability(DeviceCapabilities::isPni);
|
||||
}
|
||||
|
||||
public boolean isStoriesSupported() {
|
||||
requireNotStale();
|
||||
|
||||
return devices.stream()
|
||||
.filter(Device::isEnabled)
|
||||
.allMatch(device -> device.getCapabilities() != null && device.getCapabilities().isStories());
|
||||
}
|
||||
|
||||
public boolean isGiftBadgesSupported() {
|
||||
return allEnabledDevicesHaveCapability(DeviceCapabilities::isGiftBadges);
|
||||
return allEnabledDevicesHaveCapability(DeviceCapabilities::pni);
|
||||
}
|
||||
|
||||
public boolean isPaymentActivationSupported() {
|
||||
return allEnabledDevicesHaveCapability(DeviceCapabilities::isPaymentActivation);
|
||||
return allEnabledDevicesHaveCapability(DeviceCapabilities::paymentActivation);
|
||||
}
|
||||
|
||||
private boolean allEnabledDevicesHaveCapability(final Predicate<DeviceCapabilities> predicate) {
|
||||
|
||||
@@ -235,7 +235,7 @@ public class AccountsManager {
|
||||
keysManager.delete(actualUuid),
|
||||
keysManager.delete(account.getPhoneNumberIdentifier()));
|
||||
|
||||
messagesManager.clear(actualUuid);
|
||||
messagesManager.clear(actualUuid).join();
|
||||
profilesManager.deleteAll(actualUuid);
|
||||
|
||||
deleteKeysFuture.join();
|
||||
@@ -877,12 +877,15 @@ public class AccountsManager {
|
||||
keysManager.delete(account.getUuid()),
|
||||
keysManager.delete(account.getPhoneNumberIdentifier()));
|
||||
|
||||
final CompletableFuture<Void> deleteMessagesFuture = CompletableFuture.allOf(
|
||||
messagesManager.clear(account.getUuid()),
|
||||
messagesManager.clear(account.getPhoneNumberIdentifier()));
|
||||
|
||||
profilesManager.deleteAll(account.getUuid());
|
||||
messagesManager.clear(account.getUuid());
|
||||
messagesManager.clear(account.getPhoneNumberIdentifier());
|
||||
registrationRecoveryPasswordsManager.removeForNumber(account.getNumber());
|
||||
|
||||
deleteKeysFuture.join();
|
||||
deleteMessagesFuture.join();
|
||||
deleteStorageServiceDataFuture.join();
|
||||
deleteBackupServiceDataFuture.join();
|
||||
deleteSecureValueRecoveryServiceDataFuture.join();
|
||||
|
||||
@@ -274,85 +274,6 @@ public class Device {
|
||||
return this.userAgent;
|
||||
}
|
||||
|
||||
public static class DeviceCapabilities {
|
||||
@JsonProperty
|
||||
private boolean storage;
|
||||
|
||||
@JsonProperty
|
||||
private boolean transfer;
|
||||
|
||||
@JsonProperty
|
||||
private boolean senderKey;
|
||||
|
||||
@JsonProperty
|
||||
private boolean announcementGroup;
|
||||
|
||||
@JsonProperty
|
||||
private boolean changeNumber;
|
||||
|
||||
@JsonProperty
|
||||
private boolean pni;
|
||||
|
||||
@JsonProperty
|
||||
private boolean stories;
|
||||
|
||||
@JsonProperty
|
||||
private boolean giftBadges;
|
||||
|
||||
@JsonProperty
|
||||
private boolean paymentActivation;
|
||||
|
||||
public DeviceCapabilities() {
|
||||
}
|
||||
|
||||
public DeviceCapabilities(boolean storage, boolean transfer,
|
||||
final boolean senderKey, final boolean announcementGroup, final boolean changeNumber,
|
||||
final boolean pni, final boolean stories, final boolean giftBadges, final boolean paymentActivation) {
|
||||
this.storage = storage;
|
||||
this.transfer = transfer;
|
||||
this.senderKey = senderKey;
|
||||
this.announcementGroup = announcementGroup;
|
||||
this.changeNumber = changeNumber;
|
||||
this.pni = pni;
|
||||
this.stories = stories;
|
||||
this.giftBadges = giftBadges;
|
||||
this.paymentActivation = paymentActivation;
|
||||
}
|
||||
|
||||
public boolean isStorage() {
|
||||
return storage;
|
||||
}
|
||||
|
||||
public boolean isTransfer() {
|
||||
return transfer;
|
||||
}
|
||||
|
||||
public boolean isSenderKey() {
|
||||
return senderKey;
|
||||
}
|
||||
|
||||
public boolean isAnnouncementGroup() {
|
||||
return announcementGroup;
|
||||
}
|
||||
|
||||
public boolean isChangeNumber() {
|
||||
return changeNumber;
|
||||
}
|
||||
|
||||
public boolean isPni() {
|
||||
return pni;
|
||||
}
|
||||
|
||||
public boolean isStories() {
|
||||
return stories;
|
||||
}
|
||||
|
||||
public boolean isGiftBadges() {
|
||||
return giftBadges;
|
||||
}
|
||||
|
||||
public boolean isPaymentActivation() {
|
||||
return paymentActivation;
|
||||
}
|
||||
public record DeviceCapabilities(boolean storage, boolean transfer, boolean pni, boolean paymentActivation) {
|
||||
}
|
||||
}
|
||||
@@ -329,21 +329,24 @@ public class MessagesCache extends RedisClusterPubSubAdapter<String, String> imp
|
||||
});
|
||||
}
|
||||
|
||||
public void clear(final UUID destinationUuid) {
|
||||
// TODO Remove null check in a fully UUID-based world
|
||||
if (destinationUuid != null) {
|
||||
for (int i = 1; i < Device.MAXIMUM_DEVICE_ID; i++) {
|
||||
clear(destinationUuid, i);
|
||||
}
|
||||
public CompletableFuture<Void> clear(final UUID destinationUuid) {
|
||||
final CompletableFuture<?>[] clearFutures = new CompletableFuture[Device.MAXIMUM_DEVICE_ID];
|
||||
|
||||
for (int deviceId = 0; deviceId < Device.MAXIMUM_DEVICE_ID; deviceId++) {
|
||||
clearFutures[deviceId] = clear(destinationUuid, deviceId);
|
||||
}
|
||||
|
||||
return CompletableFuture.allOf(clearFutures);
|
||||
}
|
||||
|
||||
public void clear(final UUID destinationUuid, final long deviceId) {
|
||||
clearQueueTimer.record(() ->
|
||||
removeQueueScript.executeBinary(List.of(getMessageQueueKey(destinationUuid, deviceId),
|
||||
public CompletableFuture<Void> clear(final UUID destinationUuid, final long deviceId) {
|
||||
final Timer.Sample sample = Timer.start();
|
||||
|
||||
return removeQueueScript.executeBinaryAsync(List.of(getMessageQueueKey(destinationUuid, deviceId),
|
||||
getMessageQueueMetadataKey(destinationUuid, deviceId),
|
||||
getQueueIndexKey(destinationUuid, deviceId)),
|
||||
Collections.emptyList()));
|
||||
Collections.emptyList())
|
||||
.thenRun(() -> sample.stop(clearQueueTimer));
|
||||
}
|
||||
|
||||
int getNextSlotToPersist() {
|
||||
|
||||
+49
-46
@@ -37,7 +37,6 @@ import software.amazon.awssdk.services.dynamodb.DynamoDbAsyncClient;
|
||||
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
|
||||
import software.amazon.awssdk.services.dynamodb.model.AttributeValue;
|
||||
import software.amazon.awssdk.services.dynamodb.model.DeleteItemRequest;
|
||||
import software.amazon.awssdk.services.dynamodb.model.DeleteRequest;
|
||||
import software.amazon.awssdk.services.dynamodb.model.PutRequest;
|
||||
import software.amazon.awssdk.services.dynamodb.model.QueryRequest;
|
||||
import software.amazon.awssdk.services.dynamodb.model.ReturnValue;
|
||||
@@ -215,38 +214,57 @@ public class MessagesDynamoDb extends AbstractDynamoDbStore {
|
||||
}, messageDeletionExecutor);
|
||||
}
|
||||
|
||||
public void deleteAllMessagesForAccount(final UUID destinationAccountUuid) {
|
||||
deleteByAccount.record(() -> {
|
||||
final AttributeValue partitionKey = convertPartitionKey(destinationAccountUuid);
|
||||
final QueryRequest queryRequest = QueryRequest.builder()
|
||||
.tableName(tableName)
|
||||
.projectionExpression(KEY_SORT)
|
||||
.consistentRead(true)
|
||||
.keyConditionExpression("#part = :part")
|
||||
.expressionAttributeNames(Map.of("#part", KEY_PARTITION))
|
||||
.expressionAttributeValues(Map.of(":part", partitionKey))
|
||||
.build();
|
||||
deleteRowsMatchingQuery(partitionKey, queryRequest);
|
||||
});
|
||||
public CompletableFuture<Void> deleteAllMessagesForAccount(final UUID destinationAccountUuid) {
|
||||
final Timer.Sample sample = Timer.start();
|
||||
|
||||
final AttributeValue partitionKey = convertPartitionKey(destinationAccountUuid);
|
||||
|
||||
return Flux.from(dbAsyncClient.queryPaginator(QueryRequest.builder()
|
||||
.tableName(tableName)
|
||||
.projectionExpression(KEY_SORT)
|
||||
.consistentRead(true)
|
||||
.keyConditionExpression("#part = :part")
|
||||
.expressionAttributeNames(Map.of("#part", KEY_PARTITION))
|
||||
.expressionAttributeValues(Map.of(":part", partitionKey))
|
||||
.build())
|
||||
.items())
|
||||
.flatMap(item -> Mono.fromFuture(dbAsyncClient.deleteItem(DeleteItemRequest.builder()
|
||||
.tableName(tableName)
|
||||
.key(Map.of(
|
||||
KEY_PARTITION, partitionKey,
|
||||
KEY_SORT, item.get(KEY_SORT)))
|
||||
.build())))
|
||||
.doOnComplete(() -> sample.stop(deleteByAccount))
|
||||
.then()
|
||||
.toFuture();
|
||||
}
|
||||
|
||||
public void deleteAllMessagesForDevice(final UUID destinationAccountUuid, final long destinationDeviceId) {
|
||||
deleteByDevice.record(() -> {
|
||||
final AttributeValue partitionKey = convertPartitionKey(destinationAccountUuid);
|
||||
final QueryRequest queryRequest = QueryRequest.builder()
|
||||
.tableName(tableName)
|
||||
.keyConditionExpression("#part = :part AND begins_with ( #sort , :sortprefix )")
|
||||
.expressionAttributeNames(Map.of(
|
||||
"#part", KEY_PARTITION,
|
||||
"#sort", KEY_SORT))
|
||||
.expressionAttributeValues(Map.of(
|
||||
":part", partitionKey,
|
||||
":sortprefix", convertDestinationDeviceIdToSortKeyPrefix(destinationDeviceId)))
|
||||
.projectionExpression(KEY_SORT)
|
||||
.consistentRead(true)
|
||||
.build();
|
||||
deleteRowsMatchingQuery(partitionKey, queryRequest);
|
||||
});
|
||||
public CompletableFuture<Void> deleteAllMessagesForDevice(final UUID destinationAccountUuid, final long destinationDeviceId) {
|
||||
final Timer.Sample sample = Timer.start();
|
||||
final AttributeValue partitionKey = convertPartitionKey(destinationAccountUuid);
|
||||
|
||||
return Flux.from(dbAsyncClient.queryPaginator(QueryRequest.builder()
|
||||
.tableName(tableName)
|
||||
.keyConditionExpression("#part = :part AND begins_with ( #sort , :sortprefix )")
|
||||
.expressionAttributeNames(Map.of(
|
||||
"#part", KEY_PARTITION,
|
||||
"#sort", KEY_SORT))
|
||||
.expressionAttributeValues(Map.of(
|
||||
":part", partitionKey,
|
||||
":sortprefix", convertDestinationDeviceIdToSortKeyPrefix(destinationDeviceId)))
|
||||
.projectionExpression(KEY_SORT)
|
||||
.consistentRead(true)
|
||||
.build())
|
||||
.items())
|
||||
.flatMap(item -> Mono.fromFuture(dbAsyncClient.deleteItem(DeleteItemRequest.builder()
|
||||
.tableName(tableName)
|
||||
.key(Map.of(
|
||||
KEY_PARTITION, partitionKey,
|
||||
KEY_SORT, item.get(KEY_SORT)))
|
||||
.build())))
|
||||
.doOnComplete(() -> sample.stop(deleteByDevice))
|
||||
.then()
|
||||
.toFuture();
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
@@ -256,21 +274,6 @@ public class MessagesDynamoDb extends AbstractDynamoDbStore {
|
||||
return MessageProtos.Envelope.parseFrom(item.get(KEY_ENVELOPE_BYTES).b().asByteArray());
|
||||
}
|
||||
|
||||
private void deleteRowsMatchingQuery(AttributeValue partitionKey, QueryRequest querySpec) {
|
||||
writeInBatches(db().queryPaginator(querySpec).items(), itemBatch -> deleteItems(partitionKey, itemBatch));
|
||||
}
|
||||
|
||||
private void deleteItems(AttributeValue partitionKey, List<Map<String, AttributeValue>> items) {
|
||||
List<WriteRequest> deletes = items.stream()
|
||||
.map(item -> WriteRequest.builder()
|
||||
.deleteRequest(DeleteRequest.builder().key(Map.of(
|
||||
KEY_PARTITION, partitionKey,
|
||||
KEY_SORT, item.get(KEY_SORT))).build())
|
||||
.build())
|
||||
.toList();
|
||||
executeTableWriteItemsUntilComplete(Map.of(tableName, deletes));
|
||||
}
|
||||
|
||||
private long getTtlForMessage(MessageProtos.Envelope message) {
|
||||
return message.getServerTimestamp() / 1000 + timeToLive.getSeconds();
|
||||
}
|
||||
|
||||
@@ -102,14 +102,16 @@ public class MessagesManager {
|
||||
.tap(Micrometer.metrics(Metrics.globalRegistry));
|
||||
}
|
||||
|
||||
public void clear(UUID destinationUuid) {
|
||||
messagesCache.clear(destinationUuid);
|
||||
messagesDynamoDb.deleteAllMessagesForAccount(destinationUuid);
|
||||
public CompletableFuture<Void> clear(UUID destinationUuid) {
|
||||
return CompletableFuture.allOf(
|
||||
messagesCache.clear(destinationUuid),
|
||||
messagesDynamoDb.deleteAllMessagesForAccount(destinationUuid));
|
||||
}
|
||||
|
||||
public void clear(UUID destinationUuid, long deviceId) {
|
||||
messagesCache.clear(destinationUuid, deviceId);
|
||||
messagesDynamoDb.deleteAllMessagesForDevice(destinationUuid, deviceId);
|
||||
public CompletableFuture<Void> clear(UUID destinationUuid, long deviceId) {
|
||||
return CompletableFuture.allOf(
|
||||
messagesCache.clear(destinationUuid, deviceId),
|
||||
messagesDynamoDb.deleteAllMessagesForDevice(destinationUuid, deviceId));
|
||||
}
|
||||
|
||||
public CompletableFuture<Optional<Envelope>> delete(UUID destinationUuid, long destinationDeviceId, UUID guid,
|
||||
|
||||
@@ -46,19 +46,19 @@ public class Profiles {
|
||||
@VisibleForTesting
|
||||
static final String ATTR_VERSION = "V";
|
||||
|
||||
// User's name; string
|
||||
// User's name; byte array
|
||||
private static final String ATTR_NAME = "N";
|
||||
|
||||
// Avatar path/filename; string
|
||||
private static final String ATTR_AVATAR = "A";
|
||||
|
||||
// Bio/about text; string
|
||||
// Bio/about text; byte array
|
||||
private static final String ATTR_ABOUT = "B";
|
||||
|
||||
// Bio/about emoji; string
|
||||
// Bio/about emoji; byte array
|
||||
private static final String ATTR_EMOJI = "E";
|
||||
|
||||
// Payment address; string
|
||||
// Payment address; byte array
|
||||
private static final String ATTR_PAYMENT_ADDRESS = "P";
|
||||
|
||||
// Commitment; byte array
|
||||
@@ -75,6 +75,7 @@ public class Profiles {
|
||||
private static final Timer SET_PROFILES_TIMER = Metrics.timer(name(Profiles.class, "set"));
|
||||
private static final Timer GET_PROFILE_TIMER = Metrics.timer(name(Profiles.class, "get"));
|
||||
private static final Timer DELETE_PROFILES_TIMER = Metrics.timer(name(Profiles.class, "delete"));
|
||||
private static final String PARSE_BYTE_ARRAY_COUNTER_NAME = name(Profiles.class, "parseByteArray");
|
||||
|
||||
public Profiles(final DynamoDbClient dynamoDbClient,
|
||||
final DynamoDbAsyncClient dynamoDbAsyncClient,
|
||||
@@ -89,7 +90,7 @@ public class Profiles {
|
||||
SET_PROFILES_TIMER.record(() -> {
|
||||
dynamoDbClient.updateItem(UpdateItemRequest.builder()
|
||||
.tableName(tableName)
|
||||
.key(buildPrimaryKey(uuid, profile.getVersion()))
|
||||
.key(buildPrimaryKey(uuid, profile.version()))
|
||||
.updateExpression(buildUpdateExpression(profile))
|
||||
.expressionAttributeNames(UPDATE_EXPRESSION_ATTRIBUTE_NAMES)
|
||||
.expressionAttributeValues(buildUpdateExpressionAttributeValues(profile))
|
||||
@@ -100,7 +101,7 @@ public class Profiles {
|
||||
public CompletableFuture<Void> setAsync(final UUID uuid, final VersionedProfile profile) {
|
||||
return AsyncTimerUtil.record(SET_PROFILES_TIMER, () -> dynamoDbAsyncClient.updateItem(UpdateItemRequest.builder()
|
||||
.tableName(tableName)
|
||||
.key(buildPrimaryKey(uuid, profile.getVersion()))
|
||||
.key(buildPrimaryKey(uuid, profile.version()))
|
||||
.updateExpression(buildUpdateExpression(profile))
|
||||
.expressionAttributeNames(UPDATE_EXPRESSION_ATTRIBUTE_NAMES)
|
||||
.expressionAttributeValues(buildUpdateExpressionAttributeValues(profile))
|
||||
@@ -120,31 +121,31 @@ public class Profiles {
|
||||
final List<String> updatedAttributes = new ArrayList<>(5);
|
||||
final List<String> deletedAttributes = new ArrayList<>(5);
|
||||
|
||||
if (StringUtils.isNotBlank(profile.getName())) {
|
||||
if (profile.name() != null) {
|
||||
updatedAttributes.add("name");
|
||||
} else {
|
||||
deletedAttributes.add("name");
|
||||
}
|
||||
|
||||
if (StringUtils.isNotBlank(profile.getAvatar())) {
|
||||
if (StringUtils.isNotBlank(profile.avatar())) {
|
||||
updatedAttributes.add("avatar");
|
||||
} else {
|
||||
deletedAttributes.add("avatar");
|
||||
}
|
||||
|
||||
if (StringUtils.isNotBlank(profile.getAbout())) {
|
||||
if (profile.about() != null) {
|
||||
updatedAttributes.add("about");
|
||||
} else {
|
||||
deletedAttributes.add("about");
|
||||
}
|
||||
|
||||
if (StringUtils.isNotBlank(profile.getAboutEmoji())) {
|
||||
if (profile.aboutEmoji() != null) {
|
||||
updatedAttributes.add("aboutEmoji");
|
||||
} else {
|
||||
deletedAttributes.add("aboutEmoji");
|
||||
}
|
||||
|
||||
if (StringUtils.isNotBlank(profile.getPaymentAddress())) {
|
||||
if (profile.paymentAddress() != null) {
|
||||
updatedAttributes.add("paymentAddress");
|
||||
} else {
|
||||
deletedAttributes.add("paymentAddress");
|
||||
@@ -175,26 +176,26 @@ public class Profiles {
|
||||
static Map<String, AttributeValue> buildUpdateExpressionAttributeValues(final VersionedProfile profile) {
|
||||
final Map<String, AttributeValue> expressionValues = new HashMap<>();
|
||||
|
||||
expressionValues.put(":commitment", AttributeValues.fromByteArray(profile.getCommitment()));
|
||||
expressionValues.put(":commitment", AttributeValues.fromByteArray(profile.commitment()));
|
||||
|
||||
if (StringUtils.isNotBlank(profile.getName())) {
|
||||
expressionValues.put(":name", AttributeValues.fromString(profile.getName()));
|
||||
if (profile.name() != null) {
|
||||
expressionValues.put(":name", AttributeValues.fromByteArray(profile.name()));
|
||||
}
|
||||
|
||||
if (StringUtils.isNotBlank(profile.getAvatar())) {
|
||||
expressionValues.put(":avatar", AttributeValues.fromString(profile.getAvatar()));
|
||||
if (StringUtils.isNotBlank(profile.avatar())) {
|
||||
expressionValues.put(":avatar", AttributeValues.fromString(profile.avatar()));
|
||||
}
|
||||
|
||||
if (StringUtils.isNotBlank(profile.getAbout())) {
|
||||
expressionValues.put(":about", AttributeValues.fromString(profile.getAbout()));
|
||||
if (profile.about() != null) {
|
||||
expressionValues.put(":about", AttributeValues.fromByteArray(profile.about()));
|
||||
}
|
||||
|
||||
if (StringUtils.isNotBlank(profile.getAboutEmoji())) {
|
||||
expressionValues.put(":aboutEmoji", AttributeValues.fromString(profile.getAboutEmoji()));
|
||||
if (profile.aboutEmoji() != null) {
|
||||
expressionValues.put(":aboutEmoji", AttributeValues.fromByteArray(profile.aboutEmoji()));
|
||||
}
|
||||
|
||||
if (StringUtils.isNotBlank(profile.getPaymentAddress())) {
|
||||
expressionValues.put(":paymentAddress", AttributeValues.fromString(profile.getPaymentAddress()));
|
||||
if (profile.paymentAddress() != null) {
|
||||
expressionValues.put(":paymentAddress", AttributeValues.fromByteArray(profile.paymentAddress()));
|
||||
}
|
||||
|
||||
return expressionValues;
|
||||
@@ -226,14 +227,23 @@ public class Profiles {
|
||||
private static VersionedProfile fromItem(final Map<String, AttributeValue> item) {
|
||||
return new VersionedProfile(
|
||||
AttributeValues.getString(item, ATTR_VERSION, null),
|
||||
AttributeValues.getString(item, ATTR_NAME, null),
|
||||
getBytes(item, ATTR_NAME),
|
||||
AttributeValues.getString(item, ATTR_AVATAR, null),
|
||||
AttributeValues.getString(item, ATTR_EMOJI, null),
|
||||
AttributeValues.getString(item, ATTR_ABOUT, null),
|
||||
AttributeValues.getString(item, ATTR_PAYMENT_ADDRESS, null),
|
||||
getBytes(item, ATTR_EMOJI),
|
||||
getBytes(item, ATTR_ABOUT),
|
||||
getBytes(item, ATTR_PAYMENT_ADDRESS),
|
||||
AttributeValues.getByteArray(item, ATTR_COMMITMENT, null));
|
||||
}
|
||||
|
||||
private static byte[] getBytes(final Map<String, AttributeValue> item, final String attributeName) {
|
||||
final AttributeValue attributeValue = item.get(attributeName);
|
||||
|
||||
if (attributeValue == null) {
|
||||
return null;
|
||||
}
|
||||
return AttributeValues.extractByteArray(attributeValue, PARSE_BYTE_ARRAY_COUNTER_NAME);
|
||||
}
|
||||
|
||||
public void deleteAll(final UUID uuid) {
|
||||
DELETE_PROFILES_TIMER.record(() -> {
|
||||
final AttributeValue uuidAttributeValue = AttributeValues.fromUUID(uuid);
|
||||
|
||||
@@ -77,7 +77,7 @@ public class ProfilesManager {
|
||||
try {
|
||||
final String profileJson = mapper.writeValueAsString(profile);
|
||||
|
||||
cacheCluster.useCluster(connection -> connection.sync().hset(getCacheKey(uuid), profile.getVersion(), profileJson));
|
||||
cacheCluster.useCluster(connection -> connection.sync().hset(getCacheKey(uuid), profile.version(), profileJson));
|
||||
} catch (JsonProcessingException e) {
|
||||
throw new IllegalArgumentException(e);
|
||||
}
|
||||
@@ -93,7 +93,7 @@ public class ProfilesManager {
|
||||
}
|
||||
|
||||
return cacheCluster.withCluster(connection ->
|
||||
connection.async().hset(getCacheKey(uuid), profile.getVersion(), profileJson))
|
||||
connection.async().hset(getCacheKey(uuid), profile.version(), profileJson))
|
||||
.thenRun(Util.NOOP)
|
||||
.toCompletableFuture();
|
||||
}
|
||||
|
||||
+4
-1
@@ -14,7 +14,10 @@ import software.amazon.awssdk.services.dynamodb.model.AttributeValue;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
|
||||
import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
|
||||
|
||||
public class SingleUseECPreKeyStore extends SingleUsePreKeyStore<ECPreKey> {
|
||||
private static final String PARSE_BYTE_ARRAY_COUNTER_NAME = name(SingleUseECPreKeyStore.class, "parseByteArray");
|
||||
|
||||
protected SingleUseECPreKeyStore(final DynamoDbAsyncClient dynamoDbAsyncClient, final String tableName) {
|
||||
super(dynamoDbAsyncClient, tableName);
|
||||
@@ -31,7 +34,7 @@ public class SingleUseECPreKeyStore extends SingleUsePreKeyStore<ECPreKey> {
|
||||
@Override
|
||||
protected ECPreKey getPreKeyFromItem(final Map<String, AttributeValue> item) {
|
||||
final long keyId = item.get(KEY_DEVICE_ID_KEY_ID).b().asByteBuffer().getLong(8);
|
||||
final byte[] publicKey = extractByteArray(item.get(ATTR_PUBLIC_KEY));
|
||||
final byte[] publicKey = AttributeValues.extractByteArray(item.get(ATTR_PUBLIC_KEY), PARSE_BYTE_ARRAY_COUNTER_NAME);
|
||||
|
||||
try {
|
||||
return new ECPreKey(keyId, new ECPublicKey(publicKey));
|
||||
|
||||
-23
@@ -73,9 +73,6 @@ public abstract class SingleUsePreKeyStore<K extends PreKey<?>> {
|
||||
private final String takeKeyTimerName = name(getClass(), "takeKey");
|
||||
private static final String KEY_PRESENT_TAG_NAME = "keyPresent";
|
||||
|
||||
private final Counter parseBytesFromStringCounter = Metrics.counter(name(getClass(), "parseByteArray"), "format", "string");
|
||||
private final Counter readBytesFromByteArrayCounter = Metrics.counter(name(getClass(), "parseByteArray"), "format", "bytes");
|
||||
|
||||
static final String KEY_ACCOUNT_UUID = "U";
|
||||
static final String KEY_DEVICE_ID_KEY_ID = "DK";
|
||||
static final String ATTR_PUBLIC_KEY = "P";
|
||||
@@ -289,24 +286,4 @@ public abstract class SingleUsePreKeyStore<K extends PreKey<?>> {
|
||||
final K preKey);
|
||||
|
||||
protected abstract K getPreKeyFromItem(final Map<String, AttributeValue> item);
|
||||
|
||||
/**
|
||||
* Extracts a byte array from an {@link AttributeValue} that may be either a byte array or a base64-encoded string.
|
||||
*
|
||||
* @param attributeValue the {@code AttributeValue} from which to extract a byte array
|
||||
*
|
||||
* @return the byte array represented by the given {@code AttributeValue}
|
||||
*/
|
||||
@VisibleForTesting
|
||||
byte[] extractByteArray(final AttributeValue attributeValue) {
|
||||
if (attributeValue.b() != null) {
|
||||
readBytesFromByteArrayCounter.increment();
|
||||
return attributeValue.b().asByteArray();
|
||||
} else if (StringUtils.isNotBlank(attributeValue.s())) {
|
||||
parseBytesFromStringCounter.increment();
|
||||
return Base64.getDecoder().decode(attributeValue.s());
|
||||
}
|
||||
|
||||
throw new IllegalArgumentException("Attribute value has neither a byte array nor a string value");
|
||||
}
|
||||
}
|
||||
+18
-73
@@ -10,84 +10,29 @@ import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
|
||||
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
|
||||
import org.whispersystems.textsecuregcm.util.ByteArrayAdapter;
|
||||
import org.whispersystems.textsecuregcm.util.ByteArrayBase64WithPaddingAdapter;
|
||||
import java.util.Arrays;
|
||||
import java.util.Objects;
|
||||
|
||||
public class VersionedProfile {
|
||||
public record VersionedProfile (String version,
|
||||
@JsonSerialize(using = ByteArrayBase64WithPaddingAdapter.Serializing.class)
|
||||
@JsonDeserialize(using = ByteArrayBase64WithPaddingAdapter.Deserializing.class)
|
||||
byte[] name,
|
||||
|
||||
private final String version;
|
||||
private final String name;
|
||||
private final String avatar;
|
||||
private final String aboutEmoji;
|
||||
private final String about;
|
||||
private final String paymentAddress;
|
||||
String avatar,
|
||||
|
||||
@JsonSerialize(using = ByteArrayAdapter.Serializing.class)
|
||||
@JsonDeserialize(using = ByteArrayAdapter.Deserializing.class)
|
||||
private byte[] commitment;
|
||||
@JsonSerialize(using = ByteArrayBase64WithPaddingAdapter.Serializing.class)
|
||||
@JsonDeserialize(using = ByteArrayBase64WithPaddingAdapter.Deserializing.class)
|
||||
byte[] aboutEmoji,
|
||||
|
||||
@JsonCreator
|
||||
public VersionedProfile(
|
||||
@JsonProperty("version") final String version,
|
||||
@JsonProperty("name") final String name,
|
||||
@JsonProperty("avatar") final String avatar,
|
||||
@JsonProperty("aboutEmoji") final String aboutEmoji,
|
||||
@JsonProperty("about") final String about,
|
||||
@JsonProperty("paymentAddress") final String paymentAddress,
|
||||
@JsonProperty("commitment") final byte[] commitment) {
|
||||
this.version = version;
|
||||
this.name = name;
|
||||
this.avatar = avatar;
|
||||
this.aboutEmoji = aboutEmoji;
|
||||
this.about = about;
|
||||
this.paymentAddress = paymentAddress;
|
||||
this.commitment = commitment;
|
||||
}
|
||||
@JsonSerialize(using = ByteArrayBase64WithPaddingAdapter.Serializing.class)
|
||||
@JsonDeserialize(using = ByteArrayBase64WithPaddingAdapter.Deserializing.class)
|
||||
byte[] about,
|
||||
|
||||
public String getVersion() {
|
||||
return version;
|
||||
}
|
||||
@JsonSerialize(using = ByteArrayBase64WithPaddingAdapter.Serializing.class)
|
||||
@JsonDeserialize(using = ByteArrayBase64WithPaddingAdapter.Deserializing.class)
|
||||
byte[] paymentAddress,
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public String getAvatar() {
|
||||
return avatar;
|
||||
}
|
||||
|
||||
public String getAboutEmoji() {
|
||||
return aboutEmoji;
|
||||
}
|
||||
|
||||
public String getAbout() {
|
||||
return about;
|
||||
}
|
||||
|
||||
public String getPaymentAddress() {
|
||||
return paymentAddress;
|
||||
}
|
||||
|
||||
public byte[] getCommitment() {
|
||||
return commitment;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(final Object o) {
|
||||
if (this == o)
|
||||
return true;
|
||||
if (o == null || getClass() != o.getClass())
|
||||
return false;
|
||||
final VersionedProfile that = (VersionedProfile) o;
|
||||
return Objects.equals(version, that.version) && Objects.equals(name, that.name) && Objects.equals(avatar,
|
||||
that.avatar) && Objects.equals(aboutEmoji, that.aboutEmoji) && Objects.equals(about, that.about)
|
||||
&& Objects.equals(paymentAddress, that.paymentAddress) && Arrays.equals(commitment, that.commitment);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
int result = Objects.hash(version, name, avatar, aboutEmoji, about, paymentAddress);
|
||||
result = 31 * result + Arrays.hashCode(commitment);
|
||||
return result;
|
||||
}
|
||||
}
|
||||
@JsonSerialize(using = ByteArrayAdapter.Serializing.class)
|
||||
@JsonDeserialize(using = ByteArrayAdapter.Deserializing.class)
|
||||
byte[] commitment) {}
|
||||
@@ -6,9 +6,13 @@
|
||||
package org.whispersystems.textsecuregcm.util;
|
||||
|
||||
import java.nio.ByteBuffer;
|
||||
import java.util.Base64;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import software.amazon.awssdk.core.SdkBytes;
|
||||
import software.amazon.awssdk.services.dynamodb.model.AttributeValue;
|
||||
|
||||
@@ -124,4 +128,24 @@ public class AttributeValues {
|
||||
public static UUID getUUID(Map<String, AttributeValue> item, String key, UUID defaultValue) {
|
||||
return AttributeValues.get(item, key).filter(av -> av.b() != null).map(AttributeValues::toUUID).orElse(defaultValue);
|
||||
}
|
||||
|
||||
/**
|
||||
* Extracts a byte array from an {@link AttributeValue} that may be either a byte array or a base64-encoded string.
|
||||
*
|
||||
* @param attributeValue the {@code AttributeValue} from which to extract a byte array
|
||||
*
|
||||
* @return the byte array represented by the given {@code AttributeValue}
|
||||
*/
|
||||
@VisibleForTesting
|
||||
public static byte[] extractByteArray(final AttributeValue attributeValue, final String counterName) {
|
||||
if (attributeValue.b() != null) {
|
||||
Metrics.counter(counterName, "format", "bytes").increment();
|
||||
return attributeValue.b().asByteArray();
|
||||
} else if (StringUtils.isNotBlank(attributeValue.s())) {
|
||||
Metrics.counter(counterName, "format", "string").increment();
|
||||
return Base64.getDecoder().decode(attributeValue.s());
|
||||
}
|
||||
|
||||
throw new IllegalArgumentException("Attribute value has neither a byte array nor a string value");
|
||||
}
|
||||
}
|
||||
+27
@@ -0,0 +1,27 @@
|
||||
package org.whispersystems.textsecuregcm.util;
|
||||
|
||||
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;
|
||||
|
||||
public class ByteArrayBase64WithPaddingAdapter {
|
||||
public static class Serializing extends JsonSerializer<byte[]> {
|
||||
@Override
|
||||
public void serialize(byte[] bytes, JsonGenerator jsonGenerator, SerializerProvider serializerProvider)
|
||||
throws IOException {
|
||||
jsonGenerator.writeString(Base64.getEncoder().encodeToString(bytes));
|
||||
}
|
||||
}
|
||||
|
||||
public static class Deserializing extends JsonDeserializer<byte[]> {
|
||||
@Override
|
||||
public byte[] deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException {
|
||||
return Base64.getDecoder().decode(jsonParser.getValueAsString());
|
||||
}
|
||||
}
|
||||
}
|
||||
-102
@@ -1,102 +0,0 @@
|
||||
/*
|
||||
* Copyright 2023 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.workers;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.Device;
|
||||
import reactor.core.publisher.Flux;
|
||||
import reactor.core.publisher.ParallelFlux;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.concurrent.atomic.AtomicLong;
|
||||
|
||||
public class AnalyzeDeviceCapabilitiesCommand extends AbstractSinglePassCrawlAccountsCommand {
|
||||
|
||||
private static final Duration MAX_DEVICE_IDLE_DURATION = Duration.ofDays(90);
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(AnalyzeDeviceCapabilitiesCommand.class);
|
||||
|
||||
public AnalyzeDeviceCapabilitiesCommand() {
|
||||
super("analyze-device-capabilities", "Analyze capability adoption among active devices");
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void crawlAccounts(final ParallelFlux<Account> accounts) {
|
||||
final AtomicLong senderKey = new AtomicLong(0);
|
||||
final AtomicLong announcementGroup = new AtomicLong(0);
|
||||
final AtomicLong changeNumber = new AtomicLong(0);
|
||||
final AtomicLong pni = new AtomicLong(0);
|
||||
final AtomicLong stories = new AtomicLong(0);
|
||||
final AtomicLong giftBadges = new AtomicLong(0);
|
||||
final AtomicLong paymentActivation = new AtomicLong(0);
|
||||
|
||||
final long devicesAnalyzed = accounts
|
||||
.flatMap(account -> Flux.fromIterable(account.getDevices()))
|
||||
.filter(device -> {
|
||||
final Instant lastSeen = Instant.ofEpochMilli(device.getLastSeen());
|
||||
final Duration durationSinceLastSeen = Duration.between(lastSeen, Instant.now());
|
||||
|
||||
return device.isEnabled() && durationSinceLastSeen.compareTo(MAX_DEVICE_IDLE_DURATION) <= 0;
|
||||
})
|
||||
.sequential()
|
||||
.mapNotNull(Device::getCapabilities)
|
||||
.doOnNext(deviceCapabilities -> {
|
||||
if (deviceCapabilities.isSenderKey()) {
|
||||
senderKey.incrementAndGet();
|
||||
}
|
||||
|
||||
if (deviceCapabilities.isAnnouncementGroup()) {
|
||||
announcementGroup.incrementAndGet();
|
||||
}
|
||||
|
||||
if (deviceCapabilities.isChangeNumber()) {
|
||||
changeNumber.incrementAndGet();
|
||||
}
|
||||
|
||||
if (deviceCapabilities.isPni()) {
|
||||
pni.incrementAndGet();
|
||||
}
|
||||
|
||||
if (deviceCapabilities.isStories()) {
|
||||
stories.incrementAndGet();
|
||||
}
|
||||
|
||||
if (deviceCapabilities.isGiftBadges()) {
|
||||
giftBadges.incrementAndGet();
|
||||
}
|
||||
|
||||
if (deviceCapabilities.isPaymentActivation()) {
|
||||
paymentActivation.incrementAndGet();
|
||||
}
|
||||
})
|
||||
.count()
|
||||
.blockOptional()
|
||||
.orElse(0L);
|
||||
|
||||
logger.info("""
|
||||
Analyzed devices: {}
|
||||
----
|
||||
Sender key: {} ({}%)
|
||||
Announcement group: {} ({}%)
|
||||
Change number: {} ({}%)
|
||||
PNI: {} ({}%)
|
||||
Stories: {} ({}%)
|
||||
Gift badges: {} ({}%)
|
||||
Payment activation: {} ({}%)
|
||||
""",
|
||||
devicesAnalyzed,
|
||||
senderKey.get(), 100 * ((double) senderKey.get()) / ((double) devicesAnalyzed),
|
||||
announcementGroup.get(), 100 * ((double) announcementGroup.get()) / ((double) devicesAnalyzed),
|
||||
changeNumber.get(), 100 * ((double) changeNumber.get()) / ((double) devicesAnalyzed),
|
||||
pni.get(), 100 * ((double) pni.get()) / ((double) devicesAnalyzed),
|
||||
stories.get(), 100 * ((double) stories.get()) / ((double) devicesAnalyzed),
|
||||
giftBadges.get(), 100 * ((double) giftBadges.get()) / ((double) devicesAnalyzed),
|
||||
paymentActivation.get(), 100 * ((double) paymentActivation.get()) / ((double) devicesAnalyzed));
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -39,7 +39,7 @@ public class CommandStopListener implements Managed {
|
||||
writer.write("stopped");
|
||||
}
|
||||
} catch (final IOException e) {
|
||||
logger.error("Failed to open file {}", path);
|
||||
logger.error("Failed to open file {}", path, e);
|
||||
}
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -68,7 +68,7 @@ public class UnlinkDeviceCommand extends EnvironmentCommand<WhisperServerConfigu
|
||||
deps.keysManager().delete(account.getUuid(), deviceId).join();
|
||||
|
||||
System.out.format("Clearing additional messages for %s::%d\n", aci, deviceId);
|
||||
deps.messagesManager().clear(account.getUuid(), deviceId);
|
||||
deps.messagesManager().clear(account.getUuid(), deviceId).join();
|
||||
|
||||
System.out.format("Clearing presence state for %s::%d\n", aci, deviceId);
|
||||
deps.clientPresenceManager().disconnectPresence(aci, deviceId);
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
syntax = "proto3";
|
||||
|
||||
option java_multiple_files = true;
|
||||
|
||||
package org.signal.chat.calling;
|
||||
|
||||
/**
|
||||
* Provides methods for getting credentials for one-on-one and group calls.
|
||||
*/
|
||||
service Calling {
|
||||
|
||||
/**
|
||||
* Generates and returns TURN credentials for the caller.
|
||||
*
|
||||
* This RPC may fail with a `RESOURCE_EXHAUSTED` status if a rate limit for
|
||||
* generating TURN credentials has been exceeded, in which case a
|
||||
* `retry-after` header containing an ISO 8601 duration string will be present
|
||||
* in the response trailers.
|
||||
*/
|
||||
rpc GetTurnCredentials(GetTurnCredentialsRequest) returns (GetTurnCredentialsResponse) {}
|
||||
}
|
||||
|
||||
message GetTurnCredentialsRequest {}
|
||||
|
||||
message GetTurnCredentialsResponse {
|
||||
/**
|
||||
* A username that can be presented to authenticate with a TURN server.
|
||||
*/
|
||||
string username = 1;
|
||||
|
||||
/**
|
||||
* A password that can be presented to authenticate with a TURN server.
|
||||
*/
|
||||
string password = 2;
|
||||
|
||||
/**
|
||||
* A list of TURN (or TURNS or STUN) servers where the provided credentials
|
||||
* may be used.
|
||||
*/
|
||||
repeated string urls = 3;
|
||||
}
|
||||
@@ -0,0 +1,406 @@
|
||||
syntax = "proto3";
|
||||
|
||||
option java_multiple_files = true;
|
||||
|
||||
package org.signal.chat.profile;
|
||||
|
||||
import "org/signal/chat/common.proto";
|
||||
|
||||
/**
|
||||
* Provides methods for working with profiles and profile-related data.
|
||||
*/
|
||||
service Profile {
|
||||
/**
|
||||
* Sets profile data and if needed, returns S3 credentials used by clients to upload an avatar.
|
||||
*
|
||||
* This RPC may fail with `PERMISSION_DENIED` if it attempts to set the MobileCoin wallet ID
|
||||
* on an account whose profile does not currently have a MobileCoin wallet ID and
|
||||
* whose phone number contains a disallowed country prefix.
|
||||
*/
|
||||
rpc SetProfile(SetProfileRequest) returns (SetProfileResponse) {}
|
||||
|
||||
/**
|
||||
* Retrieves versioned profile data. Callers with an unidentified access key for the account
|
||||
* should use the version of this method in `ProfileAnonymous` instead.
|
||||
*
|
||||
* This RPC may fail with a `NOT_FOUND` status if the target account was not
|
||||
* found. It may fail with a `RESOURCE_EXHAUSTED` if a rate limit for fetching profiles has been
|
||||
* exceeded, in which case a `retry-after` header containing an ISO 8601
|
||||
* duration string will be present in the response trailers.
|
||||
*/
|
||||
rpc GetVersionedProfile(GetVersionedProfileRequest) returns (GetVersionedProfileResponse) {}
|
||||
|
||||
/**
|
||||
* Retrieves unversioned profile data. Callers with an unidentified access key for the account
|
||||
* should use the version of this method in `ProfileAnonymous` instead.
|
||||
*
|
||||
* This RPC may fail with a `NOT_FOUND` status if the target account was not
|
||||
* found. It may fail with a `RESOURCE_EXHAUSTED` if a rate limit for fetching profiles has been
|
||||
* exceeded, in which case a `retry-after` header containing an ISO 8601
|
||||
* duration string will be present in the response trailers.
|
||||
*/
|
||||
rpc GetUnversionedProfile(GetUnversionedProfileRequest) returns (GetUnversionedProfileResponse) {}
|
||||
|
||||
/**
|
||||
* Retrieves a profile key credential.
|
||||
* Callers with an unidentified access key for the account
|
||||
* should use the version of this method in `ProfileAnonymous` instead.
|
||||
*
|
||||
* This RPC may fail with a `NOT_FOUND` status if the target account was not
|
||||
* found. It may fail with a `RESOURCE_EXHAUSTED` if a rate limit for fetching profiles has been
|
||||
* exceeded, in which case a `retry-after` header containing an ISO 8601
|
||||
* duration string will be present in the response trailers. It may also fail with an
|
||||
* `INVALID_ARGUMENT` status if the given credential type is invalid.
|
||||
*/
|
||||
rpc GetExpiringProfileKeyCredential(GetExpiringProfileKeyCredentialRequest) returns (GetExpiringProfileKeyCredentialResponse) {}
|
||||
}
|
||||
|
||||
/**
|
||||
* Provides methods for working with profiles and profile-related data using "unidentified access"
|
||||
* credentials. Callers must not submit any self-identifying credentials
|
||||
* when calling methods in this service and must instead present the targeted account's
|
||||
* unidentified access key as an anonymous authentication mechanism. Callers
|
||||
* without an unidentified access key should use the equivalent, authenticated
|
||||
* methods in `Profile` instead.
|
||||
*/
|
||||
service ProfileAnonymous {
|
||||
/**
|
||||
* Retrieves versioned profile data.
|
||||
*
|
||||
* This RPC may fail with a `NOT_FOUND` status if the target account was not
|
||||
* found. It may also fail with an `UNAUTHENTICATED` status if the given
|
||||
* unidentified access key did not match the target account's unidentified
|
||||
* access key.
|
||||
*/
|
||||
rpc GetVersionedProfile(GetVersionedProfileAnonymousRequest) returns (GetVersionedProfileResponse) {}
|
||||
/**
|
||||
* Retrieves unversioned profile data.
|
||||
*
|
||||
* This RPC may fail with a `NOT_FOUND` status if the target account was not
|
||||
* found. It may also fail with an `UNAUTHENTICATED` status if the given
|
||||
* unidentified access key did not match the target account's unidentified
|
||||
* access key.
|
||||
*/
|
||||
rpc GetUnversionedProfile(GetUnversionedProfileAnonymousRequest) returns (GetUnversionedProfileResponse) {}
|
||||
/**
|
||||
* Retrieves a profile key credential.
|
||||
*
|
||||
* This RPC may fail with a `NOT_FOUND` status if the target account was not
|
||||
* found. It may also fail with an `UNAUTHENTICATED` status if the given
|
||||
* unidentified access key did not match the target account's unidentified
|
||||
* access key, or an `INVALID_ARGUMENT` status if the given credential type is invalid.
|
||||
*/
|
||||
rpc GetExpiringProfileKeyCredential(GetExpiringProfileKeyCredentialAnonymousRequest) returns (GetExpiringProfileKeyCredentialResponse) {}
|
||||
|
||||
/**
|
||||
* Checks identity key fingerprints of the target accounts.
|
||||
*
|
||||
* Returns a stream of elements, each one representing an account that had a mismatched
|
||||
* identity key fingerprint with the server and the corresponding identity key stored by the server.
|
||||
*/
|
||||
rpc CheckIdentityKeys(stream CheckIdentityKeysRequest) returns (stream CheckIdentityKeysResponse) {}
|
||||
}
|
||||
|
||||
message SetProfileRequest {
|
||||
enum AvatarChange {
|
||||
AVATAR_CHANGE_UNCHANGED = 0;
|
||||
AVATAR_CHANGE_CLEAR = 1;
|
||||
AVATAR_CHANGE_UPDATE = 2;
|
||||
}
|
||||
/**
|
||||
* The profile version. Must be set.
|
||||
*/
|
||||
string version = 1;
|
||||
/**
|
||||
* The ciphertext of a name that users must set on the profile.
|
||||
*/
|
||||
bytes name = 2;
|
||||
/**
|
||||
* An enum to indicate what change, if any, is made to the avatar with this request.
|
||||
*/
|
||||
AvatarChange avatarChange = 3;
|
||||
/**
|
||||
* The ciphertext of an emoji that users can set on their profile.
|
||||
*/
|
||||
bytes about_emoji = 4;
|
||||
/**
|
||||
* The ciphertext of a description that users can set on their profile.
|
||||
*/
|
||||
bytes about = 5;
|
||||
/**
|
||||
* The ciphertext of the MobileCoin wallet ID on the profile.
|
||||
*/
|
||||
bytes payment_address = 6;
|
||||
/**
|
||||
* A list of badge IDs associated with the profile.
|
||||
*/
|
||||
repeated string badge_ids = 7;
|
||||
/**
|
||||
* The profile key commitment. Used to issue a profile key credential response.
|
||||
* Must be set on the request.
|
||||
*/
|
||||
bytes commitment = 9;
|
||||
}
|
||||
|
||||
message SetProfileResponse {
|
||||
/**
|
||||
* The policy and credential used by clients to upload an avatar to S3.
|
||||
*/
|
||||
ProfileAvatarUploadAttributes attributes = 1;
|
||||
}
|
||||
|
||||
message GetVersionedProfileRequest {
|
||||
/**
|
||||
* The ACI of the account for which to get profile data.
|
||||
*/
|
||||
common.ServiceIdentifier accountIdentifier = 1;
|
||||
/**
|
||||
* The profile version to retrieve.
|
||||
*/
|
||||
bytes version = 2;
|
||||
}
|
||||
|
||||
message GetVersionedProfileAnonymousRequest {
|
||||
/**
|
||||
* Contains the data necessary to request a versioned profile.
|
||||
*/
|
||||
GetVersionedProfileRequest request = 1;
|
||||
/**
|
||||
* The unidentified access key for the targeted account.
|
||||
*/
|
||||
bytes unidentified_access_key = 2;
|
||||
}
|
||||
|
||||
message GetVersionedProfileResponse {
|
||||
/**
|
||||
* The ciphertext of the name on the profile.
|
||||
*/
|
||||
bytes name = 1;
|
||||
/**
|
||||
* The ciphertext of the description on the profile.
|
||||
*/
|
||||
bytes about = 2;
|
||||
/**
|
||||
* The ciphertext of the emoji on the profile.
|
||||
*/
|
||||
bytes about_emoji = 3;
|
||||
/**
|
||||
* The S3 path of the avatar on the profile.
|
||||
*/
|
||||
string avatar = 4;
|
||||
/**
|
||||
* The ciphertext of the MobileCoin wallet ID on the profile.
|
||||
*/
|
||||
bytes payment_address = 5;
|
||||
}
|
||||
|
||||
message GetUnversionedProfileRequest {
|
||||
/**
|
||||
* The service identifier of the account for which to get profile data.
|
||||
*/
|
||||
common.ServiceIdentifier serviceIdentifier = 1;
|
||||
}
|
||||
|
||||
message GetUnversionedProfileAnonymousRequest {
|
||||
/**
|
||||
* Contains the data necessary to request an unversioned profile.
|
||||
*/
|
||||
GetUnversionedProfileRequest request = 1;
|
||||
/**
|
||||
* The unidentified access key for the targeted account.
|
||||
*/
|
||||
bytes unidentified_access_key = 2;
|
||||
}
|
||||
|
||||
message GetUnversionedProfileResponse {
|
||||
/**
|
||||
* The identity key of the targeted account/identity type.
|
||||
*/
|
||||
bytes identity_key = 1;
|
||||
/**
|
||||
* A checksum of the unidentified access key for the targeted account.
|
||||
*/
|
||||
bytes unidentified_access = 2;
|
||||
/**
|
||||
* Whether the account has enabled sealed sender from anyone.
|
||||
*/
|
||||
bool unrestricted_unidentified_access = 3;
|
||||
/**
|
||||
* A list of capabilities enabled on the account.
|
||||
*/
|
||||
UserCapabilities capabilities = 4;
|
||||
/**
|
||||
* A list of badges associated with the account.
|
||||
*/
|
||||
repeated Badge badges = 5;
|
||||
}
|
||||
|
||||
message GetExpiringProfileKeyCredentialRequest {
|
||||
/**
|
||||
* The ACI of the account for which to get a profile key credential.
|
||||
*/
|
||||
common.ServiceIdentifier accountIdentifier = 1;
|
||||
/**
|
||||
* A zkgroup request for a profile key credential.
|
||||
*/
|
||||
bytes credential_request = 2;
|
||||
/**
|
||||
* The type of credential being requested.
|
||||
*/
|
||||
CredentialType credential_type = 3;
|
||||
}
|
||||
|
||||
message GetExpiringProfileKeyCredentialAnonymousRequest {
|
||||
/**
|
||||
* Contains the data necessary to request an expiring profile key credential.
|
||||
*/
|
||||
GetExpiringProfileKeyCredentialRequest request = 1;
|
||||
/**
|
||||
* The unidentified access key for the targeted account.
|
||||
*/
|
||||
bytes unidentified_access_key = 2;
|
||||
}
|
||||
|
||||
message GetExpiringProfileKeyCredentialResponse {
|
||||
/**
|
||||
* A zkgroup credential used by a client to prove that it has the profile key
|
||||
* of a targeted account.
|
||||
*/
|
||||
bytes profileKeyCredential = 2;
|
||||
}
|
||||
|
||||
message CheckIdentityKeysRequest {
|
||||
/**
|
||||
* The service identifier of the account for which we want to check the associated identity key fingerprint.
|
||||
*/
|
||||
common.ServiceIdentifier target_identifier = 1;
|
||||
/**
|
||||
* The most significant 4 bytes of the SHA-256 hash of the identity key associated with the target account/identity type.
|
||||
*/
|
||||
bytes fingerprint = 2;
|
||||
}
|
||||
|
||||
message CheckIdentityKeysResponse {
|
||||
/**
|
||||
* The service identifier of the account for which there is a mismatch between the client and server identity key fingerprints.
|
||||
*/
|
||||
common.ServiceIdentifier target_identifier = 1;
|
||||
/**
|
||||
* The identity key that is stored by the server for the target account/identity type.
|
||||
*/
|
||||
bytes identity_key = 2;
|
||||
}
|
||||
|
||||
message ProfileAvatarUploadAttributes {
|
||||
/**
|
||||
* The S3 upload path for the profile's avatar.
|
||||
*/
|
||||
string path = 1;
|
||||
/**
|
||||
* A scoped credential. Includes the AWS access key, date, region targeted, and AWS service.
|
||||
*/
|
||||
string credential = 2;
|
||||
/**
|
||||
* The type of access control for the avatar object.
|
||||
*/
|
||||
string acl = 3;
|
||||
/**
|
||||
* The algorithm used to calculate a signature on the S3 policy.
|
||||
*/
|
||||
string algorithm = 4;
|
||||
/**
|
||||
* The timestamp at which the S3 policy and signature were generated.
|
||||
*/
|
||||
string date = 5;
|
||||
/**
|
||||
* The S3 policy used to upload the avatar object.
|
||||
*/
|
||||
string policy = 6;
|
||||
/**
|
||||
* A digital signature on the S3 policy.
|
||||
*/
|
||||
bytes signature = 7;
|
||||
}
|
||||
|
||||
message UserCapabilities {
|
||||
/**
|
||||
* Whether all devices linked to the account support the groups v1 migration.
|
||||
*/
|
||||
bool gv1_migration = 1;
|
||||
/**
|
||||
* Whether all devices linked to the account support sender keys.
|
||||
*/
|
||||
bool sender_key = 2;
|
||||
/**
|
||||
* Whether all devices linked to the account support announcement groups
|
||||
* (groups where only the admin can send messages or start calls).
|
||||
*/
|
||||
bool announcement_group = 3;
|
||||
/**
|
||||
* Whether all devices linked to the account support changing phone number.
|
||||
*/
|
||||
bool change_number = 4;
|
||||
/**
|
||||
* Whether all devices linked to the account support stories.
|
||||
*/
|
||||
bool stories = 5;
|
||||
/**
|
||||
* Whether all devices linked to the account support gift badges.
|
||||
*/
|
||||
bool gift_badges = 6;
|
||||
/**
|
||||
* Whether all devices linked to the account support MobileCoin payments.
|
||||
*/
|
||||
bool payment_activation = 7;
|
||||
/**
|
||||
* Whether all devices linked to the account support phone number privacy.
|
||||
*/
|
||||
bool pni = 8;
|
||||
}
|
||||
|
||||
message Badge {
|
||||
/**
|
||||
* An ID that uniquely identifies the badge.
|
||||
*/
|
||||
string id = 1;
|
||||
/**
|
||||
* The category the badge falls in ("donor" or "other").
|
||||
*/
|
||||
string category = 2;
|
||||
/**
|
||||
* The badge name.
|
||||
*/
|
||||
string name = 3;
|
||||
/**
|
||||
* The badge description.
|
||||
*/
|
||||
string description = 4;
|
||||
/**
|
||||
* Different size badge SVG files.
|
||||
*/
|
||||
repeated string sprites6 = 5;
|
||||
/**
|
||||
* File name of the scalable vector graphic representing this badge.
|
||||
*/
|
||||
string svg = 6;
|
||||
/**
|
||||
* Pairs of light/dark SVG files designed for display at different sizes.
|
||||
*/
|
||||
repeated BadgeSvg svgs = 7;
|
||||
}
|
||||
|
||||
message BadgeSvg {
|
||||
/**
|
||||
* File name of the scalable vector graphic for light mode.
|
||||
*/
|
||||
string light = 1;
|
||||
/**
|
||||
* File name of the scalable vector graphic for dark mode.
|
||||
*/
|
||||
string dark = 2;
|
||||
}
|
||||
|
||||
enum CredentialType {
|
||||
CREDENTIAL_TYPE_UNSPECIFIED = 0;
|
||||
CREDENTIAL_TYPE_EXPIRING_PROFILE_KEY = 1;
|
||||
}
|
||||
+11
-10
@@ -7,6 +7,7 @@ import org.whispersystems.textsecuregcm.storage.DynamicConfigurationManager;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
@@ -46,9 +47,9 @@ public class TurnTokenGeneratorTest {
|
||||
final long COUNT = 1000;
|
||||
|
||||
final Map<String, Long> urlCounts = Stream
|
||||
.generate(() -> turnTokenGenerator.generate(""))
|
||||
.generate(() -> turnTokenGenerator.generate(UUID.randomUUID()))
|
||||
.limit(COUNT)
|
||||
.flatMap(token -> token.getUrls().stream())
|
||||
.flatMap(token -> token.urls().stream())
|
||||
.collect(Collectors.groupingBy(i -> i, Collectors.counting()));
|
||||
|
||||
assertThat(urlCounts.get("always1.org")).isEqualTo(COUNT);
|
||||
@@ -87,9 +88,9 @@ public class TurnTokenGeneratorTest {
|
||||
final long COUNT = 1000;
|
||||
|
||||
final Map<String, Long> urlCounts = Stream
|
||||
.generate(() -> turnTokenGenerator.generate(""))
|
||||
.generate(() -> turnTokenGenerator.generate(UUID.randomUUID()))
|
||||
.limit(COUNT)
|
||||
.flatMap(token -> token.getUrls().stream())
|
||||
.flatMap(token -> token.urls().stream())
|
||||
.collect(Collectors.groupingBy(i -> i, Collectors.counting()));
|
||||
|
||||
assertThat(urlCounts.get("always.org")).isEqualTo(COUNT);
|
||||
@@ -108,8 +109,8 @@ public class TurnTokenGeneratorTest {
|
||||
- uris:
|
||||
- enrolled.org
|
||||
weight: 0
|
||||
enrolledNumbers:
|
||||
- +15555555555
|
||||
enrolledAcis:
|
||||
- 732506d7-d04f-43a4-b1d7-8a3a91ebe8a6
|
||||
- uris:
|
||||
- unenrolled.org
|
||||
weight: 1
|
||||
@@ -127,10 +128,10 @@ public class TurnTokenGeneratorTest {
|
||||
final TurnTokenGenerator turnTokenGenerator =
|
||||
new TurnTokenGenerator(mockDynamicConfigManager, "bloop".getBytes(StandardCharsets.UTF_8));
|
||||
|
||||
TurnToken token = turnTokenGenerator.generate("+15555555555");
|
||||
assertThat(token.getUrls().get(0)).isEqualTo("enrolled.org");
|
||||
token = turnTokenGenerator.generate("+15555555556");
|
||||
assertThat(token.getUrls().get(0)).isEqualTo("unenrolled.org");
|
||||
TurnToken token = turnTokenGenerator.generate(UUID.fromString("732506d7-d04f-43a4-b1d7-8a3a91ebe8a6"));
|
||||
assertThat(token.urls().get(0)).isEqualTo("enrolled.org");
|
||||
token = turnTokenGenerator.generate(UUID.randomUUID());
|
||||
assertThat(token.urls().get(0)).isEqualTo("unenrolled.org");
|
||||
|
||||
}
|
||||
|
||||
|
||||
+16
-4
@@ -18,6 +18,7 @@ import static org.whispersystems.textsecuregcm.captcha.CaptchaChecker.SEPARATOR;
|
||||
import java.io.IOException;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.stream.Stream;
|
||||
import javax.ws.rs.BadRequestException;
|
||||
import org.junit.jupiter.api.Test;
|
||||
@@ -77,7 +78,7 @@ public class CaptchaCheckerTest {
|
||||
final String siteKey,
|
||||
final Action expectedAction) throws IOException {
|
||||
final CaptchaClient captchaClient = mockClient(PREFIX);
|
||||
new CaptchaChecker(List.of(captchaClient)).verify(expectedAction, input, null);
|
||||
new CaptchaChecker(null, List.of(captchaClient)).verify(expectedAction, input, null);
|
||||
verify(captchaClient, times(1)).verify(eq(siteKey), eq(expectedAction), eq(expectedToken), any());
|
||||
}
|
||||
|
||||
@@ -105,10 +106,10 @@ public class CaptchaCheckerTest {
|
||||
final CaptchaClient a = mockClient(PREFIX_A);
|
||||
final CaptchaClient b = mockClient(PREFIX_B);
|
||||
|
||||
new CaptchaChecker(List.of(a, b)).verify(Action.CHALLENGE, ainput, null);
|
||||
new CaptchaChecker(null, List.of(a, b)).verify(Action.CHALLENGE, ainput, null);
|
||||
verify(a, times(1)).verify(any(), any(), any(), any());
|
||||
|
||||
new CaptchaChecker(List.of(a, b)).verify(Action.CHALLENGE, binput, null);
|
||||
new CaptchaChecker(null, List.of(a, b)).verify(Action.CHALLENGE, binput, null);
|
||||
verify(b, times(1)).verify(any(), any(), any(), any());
|
||||
}
|
||||
|
||||
@@ -130,7 +131,18 @@ public class CaptchaCheckerTest {
|
||||
public void badArgs(final String input) throws IOException {
|
||||
final CaptchaClient cc = mockClient(PREFIX);
|
||||
assertThrows(BadRequestException.class,
|
||||
() -> new CaptchaChecker(List.of(cc)).verify(Action.CHALLENGE, input, null));
|
||||
() -> new CaptchaChecker(null, List.of(cc)).verify(Action.CHALLENGE, input, null));
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testShortened() throws IOException {
|
||||
final CaptchaClient captchaClient = mockClient(PREFIX);
|
||||
final ShortCodeExpander retriever = mock(ShortCodeExpander.class);
|
||||
when(retriever.retrieve("abc")).thenReturn(Optional.of(TOKEN));
|
||||
final String input = String.join(SEPARATOR, PREFIX + "-short", REG_SITE_KEY, "registration", "abc");
|
||||
new CaptchaChecker(retriever, List.of(captchaClient)).verify(Action.REGISTRATION, input, null);
|
||||
verify(captchaClient, times(1)).verify(eq(REG_SITE_KEY), eq(Action.REGISTRATION), eq(TOKEN), any());
|
||||
|
||||
}
|
||||
}
|
||||
+72
@@ -0,0 +1,72 @@
|
||||
/*
|
||||
* Copyright 2023 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.captcha;
|
||||
|
||||
import com.google.api.Http;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.ArgumentMatchers;
|
||||
import javax.net.ssl.SSLSession;
|
||||
import java.io.IOException;
|
||||
import java.net.URI;
|
||||
import java.net.http.HttpClient;
|
||||
import java.net.http.HttpHeaders;
|
||||
import java.net.http.HttpRequest;
|
||||
import java.net.http.HttpResponse;
|
||||
import java.util.Optional;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.argThat;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
public class ShortCodeExpanderTest {
|
||||
|
||||
@Test
|
||||
public void testUriResolution() throws IOException, InterruptedException {
|
||||
final HttpClient httpClient = mock(HttpClient.class);
|
||||
final ShortCodeExpander expander = new ShortCodeExpander(httpClient, "https://www.example.org/shortener/");
|
||||
when(httpClient
|
||||
.send(argThat(req -> req.uri().toString().equals("https://www.example.org/shortener/shorturl")), any()))
|
||||
.thenReturn(new FakeResponse(200, "longurl"));
|
||||
assertThat(expander.retrieve("shorturl").get()).isEqualTo("longurl");
|
||||
}
|
||||
|
||||
private record FakeResponse(int statusCode, String body) implements HttpResponse<Object> {
|
||||
|
||||
@Override
|
||||
public HttpRequest request() {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Optional<HttpResponse<Object>> previousResponse() {
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
@Override
|
||||
public HttpHeaders headers() {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Optional<SSLSession> sslSession() {
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
@Override
|
||||
public URI uri() {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public HttpClient.Version version() {
|
||||
return null;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
+4
-3
@@ -336,8 +336,8 @@ class DynamicConfigurationTest {
|
||||
- uris:
|
||||
- turn:test2.org
|
||||
weight: 2
|
||||
enrolledNumbers:
|
||||
- +15555555555
|
||||
enrolledAcis:
|
||||
- 732506d7-d04f-43a4-b1d7-8a3a91ebe8a6
|
||||
""");
|
||||
DynamicTurnConfiguration turnConfiguration = DynamicConfigurationManager
|
||||
.parseConfiguration(config, DynamicConfiguration.class)
|
||||
@@ -347,7 +347,8 @@ class DynamicConfigurationTest {
|
||||
assertThat(turnConfiguration.getUriConfigs().get(1).getUris()).hasSize(1);
|
||||
assertThat(turnConfiguration.getUriConfigs().get(0).getWeight()).isEqualTo(1);
|
||||
assertThat(turnConfiguration.getUriConfigs().get(1).getWeight()).isEqualTo(2);
|
||||
assertThat(turnConfiguration.getUriConfigs().get(1).getEnrolledNumbers()).containsExactly("+15555555555");
|
||||
assertThat(turnConfiguration.getUriConfigs().get(1).getEnrolledAcis())
|
||||
.containsExactly(UUID.fromString("732506d7-d04f-43a4-b1d7-8a3a91ebe8a6"));
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
+7
-163
@@ -117,12 +117,7 @@ class DeviceControllerTest {
|
||||
when(account.getUuid()).thenReturn(AuthHelper.VALID_UUID);
|
||||
when(account.getPhoneNumberIdentifier()).thenReturn(AuthHelper.VALID_PNI);
|
||||
when(account.isEnabled()).thenReturn(false);
|
||||
when(account.isSenderKeySupported()).thenReturn(true);
|
||||
when(account.isAnnouncementGroupSupported()).thenReturn(true);
|
||||
when(account.isChangeNumberSupported()).thenReturn(true);
|
||||
when(account.isPniSupported()).thenReturn(true);
|
||||
when(account.isStoriesSupported()).thenReturn(true);
|
||||
when(account.isGiftBadgesSupported()).thenReturn(true);
|
||||
when(account.isPaymentActivationSupported()).thenReturn(false);
|
||||
|
||||
when(accountsManager.getByAccountIdentifier(AuthHelper.VALID_UUID)).thenReturn(Optional.of(account));
|
||||
@@ -133,6 +128,8 @@ class DeviceControllerTest {
|
||||
|
||||
when(keysManager.storePqLastResort(any(), any())).thenReturn(CompletableFuture.completedFuture(null));
|
||||
when(keysManager.delete(any(), anyLong())).thenReturn(CompletableFuture.completedFuture(null));
|
||||
|
||||
when(messagesManager.clear(any(), anyLong())).thenReturn(CompletableFuture.completedFuture(null));
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
@@ -638,102 +635,10 @@ class DeviceControllerTest {
|
||||
verifyNoMoreInteractions(messagesManager);
|
||||
}
|
||||
|
||||
@Test
|
||||
void deviceDowngradeSenderKeyTest() {
|
||||
DeviceCapabilities deviceCapabilities = new DeviceCapabilities(true, true, false, true,
|
||||
true, true, true, true, true);
|
||||
AccountAttributes accountAttributes =
|
||||
new AccountAttributes(false, 1234, null, null, true, deviceCapabilities);
|
||||
|
||||
final String verificationToken = deviceController.generateVerificationToken(AuthHelper.VALID_UUID);
|
||||
|
||||
Response response = resources
|
||||
.getJerseyTest()
|
||||
.target("/v1/devices/" + verificationToken)
|
||||
.request()
|
||||
.header("Authorization", AuthHelper.getProvisioningAuthHeader(AuthHelper.VALID_NUMBER, AuthHelper.VALID_PASSWORD))
|
||||
.header(HttpHeaders.USER_AGENT, "Signal-Android/5.42.8675309 Android/30")
|
||||
.put(Entity.entity(accountAttributes, MediaType.APPLICATION_JSON_TYPE));
|
||||
assertThat(response.getStatus()).isEqualTo(409);
|
||||
|
||||
deviceCapabilities = new DeviceCapabilities(true, true, true, true, true, true, true, true, true);
|
||||
accountAttributes = new AccountAttributes(false, 1234, null, null, true, deviceCapabilities);
|
||||
response = resources
|
||||
.getJerseyTest()
|
||||
.target("/v1/devices/" + verificationToken)
|
||||
.request()
|
||||
.header("Authorization", AuthHelper.getProvisioningAuthHeader(AuthHelper.VALID_NUMBER, AuthHelper.VALID_PASSWORD))
|
||||
.header(HttpHeaders.USER_AGENT, "Signal-Android/5.42.8675309 Android/30")
|
||||
.put(Entity.entity(accountAttributes, MediaType.APPLICATION_JSON_TYPE));
|
||||
assertThat(response.getStatus()).isEqualTo(200);
|
||||
}
|
||||
|
||||
@Test
|
||||
void deviceDowngradeAnnouncementGroupTest() {
|
||||
DeviceCapabilities deviceCapabilities = new DeviceCapabilities(true, true, true, false,
|
||||
true, true, true, true, true);
|
||||
AccountAttributes accountAttributes =
|
||||
new AccountAttributes(false, 1234, null, null, true, deviceCapabilities);
|
||||
|
||||
final String verificationToken = deviceController.generateVerificationToken(AuthHelper.VALID_UUID);
|
||||
|
||||
Response response = resources
|
||||
.getJerseyTest()
|
||||
.target("/v1/devices/" + verificationToken)
|
||||
.request()
|
||||
.header("Authorization", AuthHelper.getProvisioningAuthHeader(AuthHelper.VALID_NUMBER, AuthHelper.VALID_PASSWORD))
|
||||
.header(HttpHeaders.USER_AGENT, "Signal-Android/5.42.8675309 Android/30")
|
||||
.put(Entity.entity(accountAttributes, MediaType.APPLICATION_JSON_TYPE));
|
||||
assertThat(response.getStatus()).isEqualTo(409);
|
||||
|
||||
deviceCapabilities = new DeviceCapabilities(true, true, true, true, true, true, true, true, true);
|
||||
accountAttributes = new AccountAttributes(false, 1234, null, null, true, deviceCapabilities);
|
||||
response = resources
|
||||
.getJerseyTest()
|
||||
.target("/v1/devices/" + verificationToken)
|
||||
.request()
|
||||
.header("Authorization", AuthHelper.getProvisioningAuthHeader(AuthHelper.VALID_NUMBER, AuthHelper.VALID_PASSWORD))
|
||||
.header(HttpHeaders.USER_AGENT, "Signal-Android/5.42.8675309 Android/30")
|
||||
.put(Entity.entity(accountAttributes, MediaType.APPLICATION_JSON_TYPE));
|
||||
assertThat(response.getStatus()).isEqualTo(200);
|
||||
}
|
||||
|
||||
@Test
|
||||
void deviceDowngradeChangeNumberTest() {
|
||||
DeviceCapabilities deviceCapabilities = new DeviceCapabilities(true, true, true, true,
|
||||
false, true, true, true, true);
|
||||
AccountAttributes accountAttributes =
|
||||
new AccountAttributes(false, 1234, null, null, true, deviceCapabilities);
|
||||
|
||||
final String verificationToken = deviceController.generateVerificationToken(AuthHelper.VALID_UUID);
|
||||
|
||||
Response response = resources
|
||||
.getJerseyTest()
|
||||
.target("/v1/devices/" + verificationToken)
|
||||
.request()
|
||||
.header("Authorization",
|
||||
AuthHelper.getProvisioningAuthHeader(AuthHelper.VALID_NUMBER, AuthHelper.VALID_PASSWORD))
|
||||
.header(HttpHeaders.USER_AGENT, "Signal-Android/5.42.8675309 Android/30")
|
||||
.put(Entity.entity(accountAttributes, MediaType.APPLICATION_JSON_TYPE));
|
||||
assertThat(response.getStatus()).isEqualTo(409);
|
||||
|
||||
deviceCapabilities = new DeviceCapabilities(true, true, true, true, true, true, true, true, true);
|
||||
accountAttributes = new AccountAttributes(false, 1234, null, null, true, deviceCapabilities);
|
||||
response = resources
|
||||
.getJerseyTest()
|
||||
.target("/v1/devices/" + verificationToken)
|
||||
.request()
|
||||
.header("Authorization",
|
||||
AuthHelper.getProvisioningAuthHeader(AuthHelper.VALID_NUMBER, AuthHelper.VALID_PASSWORD))
|
||||
.header(HttpHeaders.USER_AGENT, "Signal-Android/5.42.8675309 Android/30")
|
||||
.put(Entity.entity(accountAttributes, MediaType.APPLICATION_JSON_TYPE));
|
||||
assertThat(response.getStatus()).isEqualTo(200);
|
||||
}
|
||||
|
||||
@Test
|
||||
void deviceDowngradePniTest() {
|
||||
DeviceCapabilities deviceCapabilities = new DeviceCapabilities(true, true, true, true, true,
|
||||
false, true, true, true);
|
||||
DeviceCapabilities deviceCapabilities = new DeviceCapabilities(true, true,
|
||||
false, true);
|
||||
AccountAttributes accountAttributes =
|
||||
new AccountAttributes(false, 1234, null, null, true, deviceCapabilities);
|
||||
|
||||
@@ -748,68 +653,7 @@ class DeviceControllerTest {
|
||||
.put(Entity.entity(accountAttributes, MediaType.APPLICATION_JSON_TYPE));
|
||||
assertThat(response.getStatus()).isEqualTo(409);
|
||||
|
||||
deviceCapabilities = new DeviceCapabilities(true, true, true, true, true, true, true, true, true);
|
||||
accountAttributes = new AccountAttributes(false, 1234, null, null, true, deviceCapabilities);
|
||||
response = resources
|
||||
.getJerseyTest()
|
||||
.target("/v1/devices/" + verificationToken)
|
||||
.request()
|
||||
.header("Authorization",
|
||||
AuthHelper.getProvisioningAuthHeader(AuthHelper.VALID_NUMBER, AuthHelper.VALID_PASSWORD))
|
||||
.header(HttpHeaders.USER_AGENT, "Signal-Android/5.42.8675309 Android/30")
|
||||
.put(Entity.entity(accountAttributes, MediaType.APPLICATION_JSON_TYPE));
|
||||
assertThat(response.getStatus()).isEqualTo(200);
|
||||
}
|
||||
|
||||
@Test
|
||||
void deviceDowngradeStoriesTest() {
|
||||
DeviceCapabilities deviceCapabilities = new DeviceCapabilities(true, true, true, true, true,
|
||||
true, false, true, true);
|
||||
AccountAttributes accountAttributes =
|
||||
new AccountAttributes(false, 1234, null, null, true, deviceCapabilities);
|
||||
|
||||
final String verificationToken = deviceController.generateVerificationToken(AuthHelper.VALID_UUID);
|
||||
|
||||
Response response = resources
|
||||
.getJerseyTest()
|
||||
.target("/v1/devices/" + verificationToken)
|
||||
.request()
|
||||
.header("Authorization",
|
||||
AuthHelper.getProvisioningAuthHeader(AuthHelper.VALID_NUMBER, AuthHelper.VALID_PASSWORD))
|
||||
.header(HttpHeaders.USER_AGENT, "Signal-Android/5.42.8675309 Android/30")
|
||||
.put(Entity.entity(accountAttributes, MediaType.APPLICATION_JSON_TYPE));
|
||||
assertThat(response.getStatus()).isEqualTo(409);
|
||||
|
||||
deviceCapabilities = new DeviceCapabilities(true, true, true, true, true, true, true, true, true);
|
||||
accountAttributes = new AccountAttributes(false, 1234, null, null, true, deviceCapabilities);
|
||||
response = resources
|
||||
.getJerseyTest()
|
||||
.target("/v1/devices/" + verificationToken)
|
||||
.request()
|
||||
.header("Authorization",
|
||||
AuthHelper.getProvisioningAuthHeader(AuthHelper.VALID_NUMBER, AuthHelper.VALID_PASSWORD))
|
||||
.header(HttpHeaders.USER_AGENT, "Signal-Android/5.42.8675309 Android/30")
|
||||
.put(Entity.entity(accountAttributes, MediaType.APPLICATION_JSON_TYPE));
|
||||
assertThat(response.getStatus()).isEqualTo(200);
|
||||
}
|
||||
|
||||
@Test
|
||||
void deviceDowngradeGiftBadgesTest() {
|
||||
DeviceCapabilities deviceCapabilities = new DeviceCapabilities(true, true, true, true, true, true, true, false, true);
|
||||
AccountAttributes accountAttributes = new AccountAttributes(false, 1234, null, null, true, deviceCapabilities);
|
||||
|
||||
final String verificationToken = deviceController.generateVerificationToken(AuthHelper.VALID_UUID);
|
||||
|
||||
Response response = resources
|
||||
.getJerseyTest()
|
||||
.target("/v1/devices/" + verificationToken)
|
||||
.request()
|
||||
.header("Authorization", AuthHelper.getProvisioningAuthHeader(AuthHelper.VALID_NUMBER, AuthHelper.VALID_PASSWORD))
|
||||
.header(HttpHeaders.USER_AGENT, "Signal-Android/5.42.8675309 Android/30")
|
||||
.put(Entity.entity(accountAttributes, MediaType.APPLICATION_JSON_TYPE));
|
||||
assertThat(response.getStatus()).isEqualTo(409);
|
||||
|
||||
deviceCapabilities = new DeviceCapabilities(true, true, true, true, true, true, true, true, true);
|
||||
deviceCapabilities = new DeviceCapabilities(true, true, true, true);
|
||||
accountAttributes = new AccountAttributes(false, 1234, null, null, true, deviceCapabilities);
|
||||
response = resources
|
||||
.getJerseyTest()
|
||||
@@ -824,7 +668,7 @@ class DeviceControllerTest {
|
||||
|
||||
@Test
|
||||
void putCapabilitiesSuccessTest() {
|
||||
final DeviceCapabilities deviceCapabilities = new DeviceCapabilities(true, true, true, true, true, true, true, true, true);
|
||||
final DeviceCapabilities deviceCapabilities = new DeviceCapabilities(true, true, true, true);
|
||||
final Response response = resources
|
||||
.getJerseyTest()
|
||||
.target("/v1/devices/capabilities")
|
||||
@@ -852,7 +696,7 @@ class DeviceControllerTest {
|
||||
@ValueSource(booleans = {true, false})
|
||||
void deviceDowngradePaymentActivationTest(boolean paymentActivation) {
|
||||
// Update when we start returning true value of capability & restricting downgrades
|
||||
DeviceCapabilities deviceCapabilities = new DeviceCapabilities(true, true, true, true, true, true, true, true, paymentActivation);
|
||||
DeviceCapabilities deviceCapabilities = new DeviceCapabilities(true, true, true, paymentActivation);
|
||||
AccountAttributes accountAttributes = new AccountAttributes(false, 1234, null, null, true, deviceCapabilities);
|
||||
|
||||
final String verificationToken = deviceController.generateVerificationToken(AuthHelper.VALID_UUID);
|
||||
|
||||
+148
-150
@@ -48,7 +48,6 @@ import javax.ws.rs.core.MediaType;
|
||||
import javax.ws.rs.core.MultivaluedHashMap;
|
||||
import javax.ws.rs.core.MultivaluedMap;
|
||||
import javax.ws.rs.core.Response;
|
||||
import org.apache.commons.lang3.RandomStringUtils;
|
||||
import org.assertj.core.api.Condition;
|
||||
import org.glassfish.jersey.server.ServerProperties;
|
||||
import org.glassfish.jersey.test.grizzly.GrizzlyWebTestContainerFactory;
|
||||
@@ -108,6 +107,7 @@ import org.whispersystems.textsecuregcm.storage.ProfilesManager;
|
||||
import org.whispersystems.textsecuregcm.storage.VersionedProfile;
|
||||
import org.whispersystems.textsecuregcm.tests.util.AccountsHelper;
|
||||
import org.whispersystems.textsecuregcm.tests.util.AuthHelper;
|
||||
import org.whispersystems.textsecuregcm.tests.util.ProfileHelper;
|
||||
import org.whispersystems.textsecuregcm.util.SystemMapper;
|
||||
import org.whispersystems.textsecuregcm.util.TestClock;
|
||||
import org.whispersystems.textsecuregcm.util.Util;
|
||||
@@ -200,9 +200,6 @@ class ProfileControllerTest {
|
||||
when(profileAccount.getUuid()).thenReturn(AuthHelper.VALID_UUID_TWO);
|
||||
when(profileAccount.getPhoneNumberIdentifier()).thenReturn(AuthHelper.VALID_PNI_TWO);
|
||||
when(profileAccount.isEnabled()).thenReturn(true);
|
||||
when(profileAccount.isSenderKeySupported()).thenReturn(false);
|
||||
when(profileAccount.isAnnouncementGroupSupported()).thenReturn(false);
|
||||
when(profileAccount.isChangeNumberSupported()).thenReturn(false);
|
||||
when(profileAccount.getCurrentProfileVersion()).thenReturn(Optional.empty());
|
||||
when(profileAccount.getUsernameHash()).thenReturn(Optional.of(USERNAME_HASH));
|
||||
when(profileAccount.getUnidentifiedAccessKey()).thenReturn(Optional.of("1337".getBytes()));
|
||||
@@ -215,9 +212,6 @@ class ProfileControllerTest {
|
||||
when(capabilitiesAccount.getPhoneNumberIdentityKey()).thenReturn(ACCOUNT_PHONE_NUMBER_IDENTITY_KEY);
|
||||
when(capabilitiesAccount.getIdentityKey(IdentityType.PNI)).thenReturn(ACCOUNT_PHONE_NUMBER_IDENTITY_KEY);
|
||||
when(capabilitiesAccount.isEnabled()).thenReturn(true);
|
||||
when(capabilitiesAccount.isSenderKeySupported()).thenReturn(true);
|
||||
when(capabilitiesAccount.isAnnouncementGroupSupported()).thenReturn(true);
|
||||
when(capabilitiesAccount.isChangeNumberSupported()).thenReturn(true);
|
||||
|
||||
when(accountsManager.getByServiceIdentifier(any())).thenReturn(Optional.empty());
|
||||
|
||||
@@ -232,9 +226,13 @@ class ProfileControllerTest {
|
||||
when(accountsManager.getByAccountIdentifier(AuthHelper.VALID_UUID)).thenReturn(Optional.of(capabilitiesAccount));
|
||||
when(accountsManager.getByServiceIdentifier(new AciServiceIdentifier(AuthHelper.VALID_UUID))).thenReturn(Optional.of(capabilitiesAccount));
|
||||
|
||||
final byte[] name = ProfileHelper.generateRandomByteArray(81);
|
||||
final byte[] emoji = ProfileHelper.generateRandomByteArray(60);
|
||||
final byte[] about = ProfileHelper.generateRandomByteArray(156);
|
||||
|
||||
when(profilesManager.get(eq(AuthHelper.VALID_UUID), eq("someversion"))).thenReturn(Optional.empty());
|
||||
when(profilesManager.get(eq(AuthHelper.VALID_UUID_TWO), eq("validversion"))).thenReturn(Optional.of(new VersionedProfile(
|
||||
"validversion", "validname", "profiles/validavatar", "emoji", "about", null, "validcommitmnet".getBytes())));
|
||||
"validversion", name, "profiles/validavatar", emoji, about, null, "validcommitmnet".getBytes())));
|
||||
|
||||
clearInvocations(rateLimiter);
|
||||
clearInvocations(accountsManager);
|
||||
@@ -401,42 +399,28 @@ class ProfileControllerTest {
|
||||
|
||||
@Test
|
||||
void testProfileCapabilities() {
|
||||
{
|
||||
final BaseProfileResponse profile = resources.getJerseyTest()
|
||||
.target("/v1/profile/" + AuthHelper.VALID_UUID)
|
||||
.request()
|
||||
.header("Authorization", AuthHelper.getAuthHeader(AuthHelper.VALID_UUID, AuthHelper.VALID_PASSWORD))
|
||||
.get(BaseProfileResponse.class);
|
||||
final BaseProfileResponse profile = resources.getJerseyTest()
|
||||
.target("/v1/profile/" + AuthHelper.VALID_UUID)
|
||||
.request()
|
||||
.header("Authorization", AuthHelper.getAuthHeader(AuthHelper.VALID_UUID, AuthHelper.VALID_PASSWORD))
|
||||
.get(BaseProfileResponse.class);
|
||||
|
||||
assertThat(profile.getCapabilities().gv1Migration()).isTrue();
|
||||
assertThat(profile.getCapabilities().senderKey()).isTrue();
|
||||
assertThat(profile.getCapabilities().announcementGroup()).isTrue();
|
||||
}
|
||||
|
||||
{
|
||||
final BaseProfileResponse profile = resources.getJerseyTest()
|
||||
.target("/v1/profile/" + AuthHelper.VALID_UUID_TWO)
|
||||
.request()
|
||||
.header("Authorization", AuthHelper.getAuthHeader(AuthHelper.VALID_UUID_TWO, AuthHelper.VALID_PASSWORD_TWO))
|
||||
.get(BaseProfileResponse.class);
|
||||
|
||||
assertThat(profile.getCapabilities().gv1Migration()).isTrue();
|
||||
assertThat(profile.getCapabilities().senderKey()).isFalse();
|
||||
assertThat(profile.getCapabilities().announcementGroup()).isFalse();
|
||||
}
|
||||
assertThat(profile.getCapabilities().gv1Migration()).isTrue();
|
||||
assertThat(profile.getCapabilities().senderKey()).isTrue();
|
||||
assertThat(profile.getCapabilities().announcementGroup()).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
void testSetProfileWantAvatarUpload() throws InvalidInputException {
|
||||
final ProfileKeyCommitment commitment = new ProfileKey(new byte[32]).getCommitment(new ServiceId.Aci(AuthHelper.VALID_UUID));
|
||||
final byte[] name = ProfileHelper.generateRandomByteArray(81);
|
||||
|
||||
final ProfileAvatarUploadAttributes uploadAttributes = resources.getJerseyTest()
|
||||
.target("/v1/profile/")
|
||||
.request()
|
||||
.header("Authorization", AuthHelper.getAuthHeader(AuthHelper.VALID_UUID, AuthHelper.VALID_PASSWORD))
|
||||
.put(Entity.entity(new CreateProfileRequest(commitment, "someversion",
|
||||
"123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678",
|
||||
null, null,
|
||||
ProfileHelper.encodeToBase64(name), null, null,
|
||||
null, true, false, List.of()), MediaType.APPLICATION_JSON_TYPE), ProfileAvatarUploadAttributes.class);
|
||||
|
||||
final ArgumentCaptor<VersionedProfile> profileArgumentCaptor = ArgumentCaptor.forClass(VersionedProfile.class);
|
||||
@@ -446,24 +430,24 @@ class ProfileControllerTest {
|
||||
|
||||
verifyNoMoreInteractions(s3client);
|
||||
|
||||
assertThat(profileArgumentCaptor.getValue().getCommitment()).isEqualTo(commitment.serialize());
|
||||
assertThat(profileArgumentCaptor.getValue().getAvatar()).isEqualTo(uploadAttributes.getKey());
|
||||
assertThat(profileArgumentCaptor.getValue().getVersion()).isEqualTo("someversion");
|
||||
assertThat(profileArgumentCaptor.getValue().getName()).isEqualTo("123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678");
|
||||
assertThat(profileArgumentCaptor.getValue().getAboutEmoji()).isNull();
|
||||
assertThat(profileArgumentCaptor.getValue().getAbout()).isNull();
|
||||
assertThat(profileArgumentCaptor.getValue().commitment()).isEqualTo(commitment.serialize());
|
||||
assertThat(profileArgumentCaptor.getValue().avatar()).isEqualTo(uploadAttributes.getKey());
|
||||
assertThat(profileArgumentCaptor.getValue().version()).isEqualTo("someversion");
|
||||
assertThat(profileArgumentCaptor.getValue().name()).isEqualTo(name);
|
||||
assertThat(profileArgumentCaptor.getValue().aboutEmoji()).isNull();
|
||||
assertThat(profileArgumentCaptor.getValue().about()).isNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
void testSetProfileWantAvatarUploadWithBadProfileSize() throws InvalidInputException {
|
||||
final ProfileKeyCommitment commitment = new ProfileKey(new byte[32]).getCommitment(new ServiceId.Aci(AuthHelper.VALID_UUID));
|
||||
final String name = ProfileHelper.generateRandomBase64FromByteArray(82);
|
||||
|
||||
try (final Response response = resources.getJerseyTest()
|
||||
.target("/v1/profile/")
|
||||
.request()
|
||||
.header("Authorization", AuthHelper.getAuthHeader(AuthHelper.VALID_UUID, AuthHelper.VALID_PASSWORD))
|
||||
.put(Entity.entity(new CreateProfileRequest(commitment, "someversion",
|
||||
"1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890",
|
||||
.put(Entity.entity(new CreateProfileRequest(commitment, "someversion", name,
|
||||
null, null, null, true, false, List.of()), MediaType.APPLICATION_JSON_TYPE))) {
|
||||
|
||||
assertThat(response.getStatus()).isEqualTo(422);
|
||||
@@ -473,6 +457,7 @@ class ProfileControllerTest {
|
||||
@Test
|
||||
void testSetProfileWithoutAvatarUpload() throws InvalidInputException {
|
||||
final ProfileKeyCommitment commitment = new ProfileKey(new byte[32]).getCommitment(new ServiceId.Aci(AuthHelper.VALID_UUID));
|
||||
final byte[] name = ProfileHelper.generateRandomByteArray(81);
|
||||
|
||||
clearInvocations(AuthHelper.VALID_ACCOUNT_TWO);
|
||||
|
||||
@@ -480,7 +465,7 @@ class ProfileControllerTest {
|
||||
.target("/v1/profile/")
|
||||
.request()
|
||||
.header("Authorization", AuthHelper.getAuthHeader(AuthHelper.VALID_UUID_TWO, AuthHelper.VALID_PASSWORD_TWO))
|
||||
.put(Entity.entity(new CreateProfileRequest(commitment, "anotherversion", "123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678", null, null,
|
||||
.put(Entity.entity(new CreateProfileRequest(commitment, "anotherversion", ProfileHelper.encodeToBase64(name), null, null,
|
||||
null, false, false, List.of()), MediaType.APPLICATION_JSON_TYPE))) {
|
||||
|
||||
assertThat(response.getStatus()).isEqualTo(200);
|
||||
@@ -493,26 +478,26 @@ class ProfileControllerTest {
|
||||
|
||||
verifyNoMoreInteractions(s3client);
|
||||
|
||||
assertThat(profileArgumentCaptor.getValue().getCommitment()).isEqualTo(commitment.serialize());
|
||||
assertThat(profileArgumentCaptor.getValue().getAvatar()).isNull();
|
||||
assertThat(profileArgumentCaptor.getValue().getVersion()).isEqualTo("anotherversion");
|
||||
assertThat(profileArgumentCaptor.getValue().getName()).isEqualTo("123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678");
|
||||
assertThat(profileArgumentCaptor.getValue().getAboutEmoji()).isNull();
|
||||
assertThat(profileArgumentCaptor.getValue().getAbout()).isNull();
|
||||
assertThat(profileArgumentCaptor.getValue().commitment()).isEqualTo(commitment.serialize());
|
||||
assertThat(profileArgumentCaptor.getValue().avatar()).isNull();
|
||||
assertThat(profileArgumentCaptor.getValue().version()).isEqualTo("anotherversion");
|
||||
assertThat(profileArgumentCaptor.getValue().name()).isEqualTo(name);
|
||||
assertThat(profileArgumentCaptor.getValue().aboutEmoji()).isNull();
|
||||
assertThat(profileArgumentCaptor.getValue().about()).isNull();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void testSetProfileWithAvatarUploadAndPreviousAvatar() throws InvalidInputException {
|
||||
final ProfileKeyCommitment commitment = new ProfileKey(new byte[32]).getCommitment(new ServiceId.Aci(AuthHelper.VALID_UUID_TWO));
|
||||
final byte[] name = ProfileHelper.generateRandomByteArray(81);
|
||||
|
||||
resources.getJerseyTest()
|
||||
.target("/v1/profile/")
|
||||
.request()
|
||||
.header("Authorization", AuthHelper.getAuthHeader(AuthHelper.VALID_UUID_TWO, AuthHelper.VALID_PASSWORD_TWO))
|
||||
.put(Entity.entity(new CreateProfileRequest(commitment, "validversion",
|
||||
"123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678",
|
||||
null, null,
|
||||
ProfileHelper.encodeToBase64(name), null, null,
|
||||
null, true, false, List.of()), MediaType.APPLICATION_JSON_TYPE), ProfileAvatarUploadAttributes.class);
|
||||
|
||||
final ArgumentCaptor<VersionedProfile> profileArgumentCaptor = ArgumentCaptor.forClass(VersionedProfile.class);
|
||||
@@ -521,24 +506,24 @@ class ProfileControllerTest {
|
||||
verify(profilesManager, times(1)).set(eq(AuthHelper.VALID_UUID_TWO), profileArgumentCaptor.capture());
|
||||
verify(s3client, times(1)).deleteObject(eq(DeleteObjectRequest.builder().bucket("profilesBucket").key("profiles/validavatar").build()));
|
||||
|
||||
assertThat(profileArgumentCaptor.getValue().getCommitment()).isEqualTo(commitment.serialize());
|
||||
assertThat(profileArgumentCaptor.getValue().getAvatar()).startsWith("profiles/");
|
||||
assertThat(profileArgumentCaptor.getValue().getVersion()).isEqualTo("validversion");
|
||||
assertThat(profileArgumentCaptor.getValue().getName()).isEqualTo("123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678");
|
||||
assertThat(profileArgumentCaptor.getValue().getAboutEmoji()).isNull();
|
||||
assertThat(profileArgumentCaptor.getValue().getAbout()).isNull();
|
||||
assertThat(profileArgumentCaptor.getValue().commitment()).isEqualTo(commitment.serialize());
|
||||
assertThat(profileArgumentCaptor.getValue().avatar()).startsWith("profiles/");
|
||||
assertThat(profileArgumentCaptor.getValue().version()).isEqualTo("validversion");
|
||||
assertThat(profileArgumentCaptor.getValue().name()).isEqualTo(name);
|
||||
assertThat(profileArgumentCaptor.getValue().aboutEmoji()).isNull();
|
||||
assertThat(profileArgumentCaptor.getValue().about()).isNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
void testSetProfileClearPreviousAvatar() throws InvalidInputException {
|
||||
final ProfileKeyCommitment commitment = new ProfileKey(new byte[32]).getCommitment(new ServiceId.Aci(AuthHelper.VALID_UUID_TWO));
|
||||
final byte[] name = ProfileHelper.generateRandomByteArray(81);
|
||||
|
||||
try (final Response response = resources.getJerseyTest()
|
||||
.target("/v1/profile/")
|
||||
.request()
|
||||
.header("Authorization", AuthHelper.getAuthHeader(AuthHelper.VALID_UUID_TWO, AuthHelper.VALID_PASSWORD_TWO))
|
||||
.put(Entity.entity(new CreateProfileRequest(commitment, "validversion",
|
||||
"123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678",
|
||||
.put(Entity.entity(new CreateProfileRequest(commitment, "validversion", ProfileHelper.encodeToBase64(name),
|
||||
null, null, null, false, false, List.of()), MediaType.APPLICATION_JSON_TYPE))) {
|
||||
|
||||
assertThat(response.getStatus()).isEqualTo(200);
|
||||
@@ -550,25 +535,25 @@ class ProfileControllerTest {
|
||||
verify(profilesManager, times(1)).set(eq(AuthHelper.VALID_UUID_TWO), profileArgumentCaptor.capture());
|
||||
verify(s3client, times(1)).deleteObject(eq(DeleteObjectRequest.builder().bucket("profilesBucket").key("profiles/validavatar").build()));
|
||||
|
||||
assertThat(profileArgumentCaptor.getValue().getCommitment()).isEqualTo(commitment.serialize());
|
||||
assertThat(profileArgumentCaptor.getValue().getAvatar()).isNull();
|
||||
assertThat(profileArgumentCaptor.getValue().getVersion()).isEqualTo("validversion");
|
||||
assertThat(profileArgumentCaptor.getValue().getName()).isEqualTo("123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678");
|
||||
assertThat(profileArgumentCaptor.getValue().getAboutEmoji()).isNull();
|
||||
assertThat(profileArgumentCaptor.getValue().getAbout()).isNull();
|
||||
assertThat(profileArgumentCaptor.getValue().commitment()).isEqualTo(commitment.serialize());
|
||||
assertThat(profileArgumentCaptor.getValue().avatar()).isNull();
|
||||
assertThat(profileArgumentCaptor.getValue().version()).isEqualTo("validversion");
|
||||
assertThat(profileArgumentCaptor.getValue().name()).isEqualTo(name);
|
||||
assertThat(profileArgumentCaptor.getValue().aboutEmoji()).isNull();
|
||||
assertThat(profileArgumentCaptor.getValue().about()).isNull();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void testSetProfileWithSameAvatar() throws InvalidInputException {
|
||||
final ProfileKeyCommitment commitment = new ProfileKey(new byte[32]).getCommitment(new ServiceId.Aci(AuthHelper.VALID_UUID_TWO));
|
||||
final byte[] name = ProfileHelper.generateRandomByteArray(81);
|
||||
|
||||
try (final Response response = resources.getJerseyTest()
|
||||
.target("/v1/profile/")
|
||||
.request()
|
||||
.header("Authorization", AuthHelper.getAuthHeader(AuthHelper.VALID_UUID_TWO, AuthHelper.VALID_PASSWORD_TWO))
|
||||
.put(Entity.entity(new CreateProfileRequest(commitment, "validversion",
|
||||
"123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678",
|
||||
.put(Entity.entity(new CreateProfileRequest(commitment, "validversion", ProfileHelper.encodeToBase64(name),
|
||||
null, null, null, true, true, List.of()), MediaType.APPLICATION_JSON_TYPE))) {
|
||||
|
||||
assertThat(response.getStatus()).isEqualTo(200);
|
||||
@@ -580,25 +565,25 @@ class ProfileControllerTest {
|
||||
verify(profilesManager, times(1)).set(eq(AuthHelper.VALID_UUID_TWO), profileArgumentCaptor.capture());
|
||||
verify(s3client, never()).deleteObject(any(DeleteObjectRequest.class));
|
||||
|
||||
assertThat(profileArgumentCaptor.getValue().getCommitment()).isEqualTo(commitment.serialize());
|
||||
assertThat(profileArgumentCaptor.getValue().getAvatar()).isEqualTo("profiles/validavatar");
|
||||
assertThat(profileArgumentCaptor.getValue().getVersion()).isEqualTo("validversion");
|
||||
assertThat(profileArgumentCaptor.getValue().getName()).isEqualTo("123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678");
|
||||
assertThat(profileArgumentCaptor.getValue().getAboutEmoji()).isNull();
|
||||
assertThat(profileArgumentCaptor.getValue().getAbout()).isNull();
|
||||
assertThat(profileArgumentCaptor.getValue().commitment()).isEqualTo(commitment.serialize());
|
||||
assertThat(profileArgumentCaptor.getValue().avatar()).isEqualTo("profiles/validavatar");
|
||||
assertThat(profileArgumentCaptor.getValue().version()).isEqualTo("validversion");
|
||||
assertThat(profileArgumentCaptor.getValue().name()).isEqualTo(name);
|
||||
assertThat(profileArgumentCaptor.getValue().aboutEmoji()).isNull();
|
||||
assertThat(profileArgumentCaptor.getValue().about()).isNull();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void testSetProfileClearPreviousAvatarDespiteSameAvatarFlagSet() throws InvalidInputException {
|
||||
final ProfileKeyCommitment commitment = new ProfileKey(new byte[32]).getCommitment(new ServiceId.Aci(AuthHelper.VALID_UUID_TWO));
|
||||
final byte[] name = ProfileHelper.generateRandomByteArray(81);
|
||||
|
||||
try (final Response ignored = resources.getJerseyTest()
|
||||
.target("/v1/profile/")
|
||||
.request()
|
||||
.header("Authorization", AuthHelper.getAuthHeader(AuthHelper.VALID_UUID_TWO, AuthHelper.VALID_PASSWORD_TWO))
|
||||
.put(Entity.entity(new CreateProfileRequest(commitment, "validversion",
|
||||
"123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678",
|
||||
.put(Entity.entity(new CreateProfileRequest(commitment, "validversion", ProfileHelper.encodeToBase64(name),
|
||||
null, null,
|
||||
null, false, true, List.of()), MediaType.APPLICATION_JSON_TYPE))) {
|
||||
|
||||
@@ -608,25 +593,25 @@ class ProfileControllerTest {
|
||||
verify(profilesManager, times(1)).set(eq(AuthHelper.VALID_UUID_TWO), profileArgumentCaptor.capture());
|
||||
verify(s3client, times(1)).deleteObject(eq(DeleteObjectRequest.builder().bucket("profilesBucket").key("profiles/validavatar").build()));
|
||||
|
||||
assertThat(profileArgumentCaptor.getValue().getCommitment()).isEqualTo(commitment.serialize());
|
||||
assertThat(profileArgumentCaptor.getValue().getAvatar()).isNull();
|
||||
assertThat(profileArgumentCaptor.getValue().getVersion()).isEqualTo("validversion");
|
||||
assertThat(profileArgumentCaptor.getValue().getName()).isEqualTo("123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678");
|
||||
assertThat(profileArgumentCaptor.getValue().getAboutEmoji()).isNull();
|
||||
assertThat(profileArgumentCaptor.getValue().getAbout()).isNull();
|
||||
assertThat(profileArgumentCaptor.getValue().commitment()).isEqualTo(commitment.serialize());
|
||||
assertThat(profileArgumentCaptor.getValue().avatar()).isNull();
|
||||
assertThat(profileArgumentCaptor.getValue().version()).isEqualTo("validversion");
|
||||
assertThat(profileArgumentCaptor.getValue().name()).isEqualTo(name);
|
||||
assertThat(profileArgumentCaptor.getValue().aboutEmoji()).isNull();
|
||||
assertThat(profileArgumentCaptor.getValue().about()).isNull();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void testSetProfileWithSameAvatarDespiteNoPreviousAvatar() throws InvalidInputException {
|
||||
final ProfileKeyCommitment commitment = new ProfileKey(new byte[32]).getCommitment(new ServiceId.Aci(AuthHelper.VALID_UUID));
|
||||
final byte[] name = ProfileHelper.generateRandomByteArray(81);
|
||||
|
||||
try (final Response response = resources.getJerseyTest()
|
||||
.target("/v1/profile/")
|
||||
.request()
|
||||
.header("Authorization", AuthHelper.getAuthHeader(AuthHelper.VALID_UUID, AuthHelper.VALID_PASSWORD))
|
||||
.put(Entity.entity(new CreateProfileRequest(commitment, "validversion",
|
||||
"123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678",
|
||||
.put(Entity.entity(new CreateProfileRequest(commitment, "validversion", ProfileHelper.encodeToBase64(name),
|
||||
null, null, null, true, true, List.of()), MediaType.APPLICATION_JSON_TYPE))) {
|
||||
|
||||
assertThat(response.getStatus()).isEqualTo(200);
|
||||
@@ -638,12 +623,12 @@ class ProfileControllerTest {
|
||||
verify(profilesManager, times(1)).set(eq(AuthHelper.VALID_UUID), profileArgumentCaptor.capture());
|
||||
verify(s3client, never()).deleteObject(any(DeleteObjectRequest.class));
|
||||
|
||||
assertThat(profileArgumentCaptor.getValue().getCommitment()).isEqualTo(commitment.serialize());
|
||||
assertThat(profileArgumentCaptor.getValue().getAvatar()).isNull();
|
||||
assertThat(profileArgumentCaptor.getValue().getVersion()).isEqualTo("validversion");
|
||||
assertThat(profileArgumentCaptor.getValue().getName()).isEqualTo("123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678");
|
||||
assertThat(profileArgumentCaptor.getValue().getAboutEmoji()).isNull();
|
||||
assertThat(profileArgumentCaptor.getValue().getAbout()).isNull();
|
||||
assertThat(profileArgumentCaptor.getValue().commitment()).isEqualTo(commitment.serialize());
|
||||
assertThat(profileArgumentCaptor.getValue().avatar()).isNull();
|
||||
assertThat(profileArgumentCaptor.getValue().version()).isEqualTo("validversion");
|
||||
assertThat(profileArgumentCaptor.getValue().name()).isEqualTo(name);
|
||||
assertThat(profileArgumentCaptor.getValue().aboutEmoji()).isNull();
|
||||
assertThat(profileArgumentCaptor.getValue().about()).isNull();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -651,14 +636,15 @@ class ProfileControllerTest {
|
||||
void testSetProfileExtendedName() throws InvalidInputException {
|
||||
final ProfileKeyCommitment commitment = new ProfileKey(new byte[32]).getCommitment(new ServiceId.Aci(AuthHelper.VALID_UUID_TWO));
|
||||
|
||||
final String name = RandomStringUtils.randomAlphabetic(380);
|
||||
final byte[] name = ProfileHelper.generateRandomByteArray(285);
|
||||
|
||||
resources.getJerseyTest()
|
||||
.target("/v1/profile/")
|
||||
.request()
|
||||
.header("Authorization", AuthHelper.getAuthHeader(AuthHelper.VALID_UUID_TWO, AuthHelper.VALID_PASSWORD_TWO))
|
||||
.put(Entity.entity(
|
||||
new CreateProfileRequest(commitment, "validversion", name, null, null, null, true, false, List.of()),
|
||||
new CreateProfileRequest(commitment, "validversion", ProfileHelper.encodeToBase64(name),
|
||||
null, null, null, true, false, List.of()),
|
||||
MediaType.APPLICATION_JSON_TYPE), ProfileAvatarUploadAttributes.class);
|
||||
|
||||
final ArgumentCaptor<VersionedProfile> profileArgumentCaptor = ArgumentCaptor.forClass(VersionedProfile.class);
|
||||
@@ -667,12 +653,12 @@ class ProfileControllerTest {
|
||||
verify(profilesManager, times(1)).set(eq(AuthHelper.VALID_UUID_TWO), profileArgumentCaptor.capture());
|
||||
verify(s3client, times(1)).deleteObject(eq(DeleteObjectRequest.builder().bucket("profilesBucket").key("profiles/validavatar").build()));
|
||||
|
||||
assertThat(profileArgumentCaptor.getValue().getCommitment()).isEqualTo(commitment.serialize());
|
||||
assertThat(profileArgumentCaptor.getValue().getAvatar()).startsWith("profiles/");
|
||||
assertThat(profileArgumentCaptor.getValue().getVersion()).isEqualTo("validversion");
|
||||
assertThat(profileArgumentCaptor.getValue().getName()).isEqualTo(name);
|
||||
assertThat(profileArgumentCaptor.getValue().getAboutEmoji()).isNull();
|
||||
assertThat(profileArgumentCaptor.getValue().getAbout()).isNull();
|
||||
assertThat(profileArgumentCaptor.getValue().commitment()).isEqualTo(commitment.serialize());
|
||||
assertThat(profileArgumentCaptor.getValue().avatar()).startsWith("profiles/");
|
||||
assertThat(profileArgumentCaptor.getValue().version()).isEqualTo("validversion");
|
||||
assertThat(profileArgumentCaptor.getValue().name()).isEqualTo(name);
|
||||
assertThat(profileArgumentCaptor.getValue().aboutEmoji()).isNull();
|
||||
assertThat(profileArgumentCaptor.getValue().about()).isNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -681,16 +667,17 @@ class ProfileControllerTest {
|
||||
|
||||
clearInvocations(AuthHelper.VALID_ACCOUNT_TWO);
|
||||
|
||||
final String name = RandomStringUtils.randomAlphabetic(380);
|
||||
final String emoji = RandomStringUtils.randomAlphanumeric(80);
|
||||
final String text = RandomStringUtils.randomAlphanumeric(720);
|
||||
final byte[] name = ProfileHelper.generateRandomByteArray(81);
|
||||
final byte[] emoji = ProfileHelper.generateRandomByteArray(60);
|
||||
final byte[] about = ProfileHelper.generateRandomByteArray(156);
|
||||
|
||||
try (final Response response = resources.getJerseyTest()
|
||||
.target("/v1/profile/")
|
||||
.request()
|
||||
.header("Authorization", AuthHelper.getAuthHeader(AuthHelper.VALID_UUID_TWO, AuthHelper.VALID_PASSWORD_TWO))
|
||||
.put(Entity.entity(
|
||||
new CreateProfileRequest(commitment, "anotherversion", name, emoji, text, null, false, false, List.of()),
|
||||
new CreateProfileRequest(commitment, "anotherversion", ProfileHelper.encodeToBase64(name),
|
||||
ProfileHelper.encodeToBase64(emoji), ProfileHelper.encodeToBase64(about), null, false, false, List.of()),
|
||||
MediaType.APPLICATION_JSON_TYPE))) {
|
||||
|
||||
assertThat(response.getStatus()).isEqualTo(200);
|
||||
@@ -704,13 +691,13 @@ class ProfileControllerTest {
|
||||
verifyNoMoreInteractions(s3client);
|
||||
|
||||
final VersionedProfile profile = profileArgumentCaptor.getValue();
|
||||
assertThat(profile.getCommitment()).isEqualTo(commitment.serialize());
|
||||
assertThat(profile.getAvatar()).isNull();
|
||||
assertThat(profile.getVersion()).isEqualTo("anotherversion");
|
||||
assertThat(profile.getName()).isEqualTo(name);
|
||||
assertThat(profile.getAboutEmoji()).isEqualTo(emoji);
|
||||
assertThat(profile.getAbout()).isEqualTo(text);
|
||||
assertThat(profile.getPaymentAddress()).isNull();
|
||||
assertThat(profile.commitment()).isEqualTo(commitment.serialize());
|
||||
assertThat(profile.avatar()).isNull();
|
||||
assertThat(profile.version()).isEqualTo("anotherversion");
|
||||
assertThat(profile.name()).isEqualTo(name);
|
||||
assertThat(profile.aboutEmoji()).isEqualTo(emoji);
|
||||
assertThat(profile.about()).isEqualTo(about);
|
||||
assertThat(profile.paymentAddress()).isNull();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -720,15 +707,16 @@ class ProfileControllerTest {
|
||||
|
||||
clearInvocations(AuthHelper.VALID_ACCOUNT_TWO);
|
||||
|
||||
final String name = RandomStringUtils.randomAlphabetic(380);
|
||||
final String paymentAddress = RandomStringUtils.randomAlphanumeric(776);
|
||||
final byte[] name = ProfileHelper.generateRandomByteArray(81);
|
||||
final byte[] paymentAddress = ProfileHelper.generateRandomByteArray(582);
|
||||
|
||||
try (final Response response = resources.getJerseyTest()
|
||||
.target("/v1/profile")
|
||||
.request()
|
||||
.header("Authorization", AuthHelper.getAuthHeader(AuthHelper.VALID_UUID_TWO, AuthHelper.VALID_PASSWORD_TWO))
|
||||
.put(Entity.entity(
|
||||
new CreateProfileRequest(commitment, "yetanotherversion", name, null, null, paymentAddress, false, false,
|
||||
new CreateProfileRequest(commitment, "yetanotherversion", ProfileHelper.encodeToBase64(name),
|
||||
null, null, ProfileHelper.encodeToBase64(paymentAddress), false, false,
|
||||
List.of()), MediaType.APPLICATION_JSON_TYPE))) {
|
||||
|
||||
assertThat(response.getStatus()).isEqualTo(200);
|
||||
@@ -742,13 +730,13 @@ class ProfileControllerTest {
|
||||
verifyNoMoreInteractions(s3client);
|
||||
|
||||
final VersionedProfile profile = profileArgumentCaptor.getValue();
|
||||
assertThat(profile.getCommitment()).isEqualTo(commitment.serialize());
|
||||
assertThat(profile.getAvatar()).isNull();
|
||||
assertThat(profile.getVersion()).isEqualTo("yetanotherversion");
|
||||
assertThat(profile.getName()).isEqualTo(name);
|
||||
assertThat(profile.getAboutEmoji()).isNull();
|
||||
assertThat(profile.getAbout()).isNull();
|
||||
assertThat(profile.getPaymentAddress()).isEqualTo(paymentAddress);
|
||||
assertThat(profile.commitment()).isEqualTo(commitment.serialize());
|
||||
assertThat(profile.avatar()).isNull();
|
||||
assertThat(profile.version()).isEqualTo("yetanotherversion");
|
||||
assertThat(profile.name()).isEqualTo(name);
|
||||
assertThat(profile.aboutEmoji()).isNull();
|
||||
assertThat(profile.about()).isNull();
|
||||
assertThat(profile.paymentAddress()).isEqualTo(paymentAddress);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -761,15 +749,16 @@ class ProfileControllerTest {
|
||||
|
||||
clearInvocations(AuthHelper.VALID_ACCOUNT_TWO);
|
||||
|
||||
final String name = RandomStringUtils.randomAlphabetic(380);
|
||||
final String paymentAddress = RandomStringUtils.randomAlphanumeric(776);
|
||||
final String name = ProfileHelper.generateRandomBase64FromByteArray(81);
|
||||
final String paymentAddress = ProfileHelper.generateRandomBase64FromByteArray(582);
|
||||
|
||||
try (final Response response = resources.getJerseyTest()
|
||||
.target("/v1/profile")
|
||||
.request()
|
||||
.header("Authorization", AuthHelper.getAuthHeader(AuthHelper.VALID_UUID_TWO, AuthHelper.VALID_PASSWORD_TWO))
|
||||
.put(Entity.entity(
|
||||
new CreateProfileRequest(commitment, "yetanotherversion", name, null, null, paymentAddress, false, false,
|
||||
new CreateProfileRequest(commitment, "yetanotherversion", name,
|
||||
null, null, paymentAddress, false, false,
|
||||
List.of()), MediaType.APPLICATION_JSON_TYPE))) {
|
||||
|
||||
assertThat(response.getStatus()).isEqualTo(403);
|
||||
@@ -787,24 +776,25 @@ class ProfileControllerTest {
|
||||
.thenReturn(List.of(AuthHelper.VALID_NUMBER_TWO.substring(0, 3)));
|
||||
|
||||
final ProfileKeyCommitment commitment = new ProfileKey(new byte[32]).getCommitment(new ServiceId.Aci(AuthHelper.VALID_UUID));
|
||||
final byte[] name = ProfileHelper.generateRandomByteArray(81);
|
||||
final byte[] paymentAddress = ProfileHelper.generateRandomByteArray(582);
|
||||
|
||||
clearInvocations(AuthHelper.VALID_ACCOUNT_TWO);
|
||||
|
||||
when(profilesManager.get(eq(AuthHelper.VALID_UUID_TWO), any()))
|
||||
.thenReturn(Optional.of(
|
||||
new VersionedProfile("1", "name", null, null, null,
|
||||
existingPaymentAddressOnProfile ? RandomStringUtils.randomAlphanumeric(776) : null,
|
||||
new VersionedProfile("1", name, null, null, null,
|
||||
existingPaymentAddressOnProfile ? ProfileHelper.generateRandomByteArray(582) : null,
|
||||
commitment.serialize())));
|
||||
|
||||
final String name = RandomStringUtils.randomAlphabetic(380);
|
||||
final String paymentAddress = RandomStringUtils.randomAlphanumeric(776);
|
||||
|
||||
try (final Response response = resources.getJerseyTest()
|
||||
.target("/v1/profile")
|
||||
.request()
|
||||
.header("Authorization", AuthHelper.getAuthHeader(AuthHelper.VALID_UUID_TWO, AuthHelper.VALID_PASSWORD_TWO))
|
||||
.put(Entity.entity(
|
||||
new CreateProfileRequest(commitment, "yetanotherversion", name, null, null, paymentAddress, false, false,
|
||||
new CreateProfileRequest(commitment, "yetanotherversion", ProfileHelper.encodeToBase64(name),
|
||||
null, null, ProfileHelper.encodeToBase64(paymentAddress), false, false,
|
||||
List.of()), MediaType.APPLICATION_JSON_TYPE))) {
|
||||
|
||||
if (existingPaymentAddressOnProfile) {
|
||||
@@ -819,13 +809,13 @@ class ProfileControllerTest {
|
||||
verifyNoMoreInteractions(s3client);
|
||||
|
||||
final VersionedProfile profile = profileArgumentCaptor.getValue();
|
||||
assertThat(profile.getCommitment()).isEqualTo(commitment.serialize());
|
||||
assertThat(profile.getAvatar()).isNull();
|
||||
assertThat(profile.getVersion()).isEqualTo("yetanotherversion");
|
||||
assertThat(profile.getName()).isEqualTo(name);
|
||||
assertThat(profile.getAboutEmoji()).isNull();
|
||||
assertThat(profile.getAbout()).isNull();
|
||||
assertThat(profile.getPaymentAddress()).isEqualTo(paymentAddress);
|
||||
assertThat(profile.commitment()).isEqualTo(commitment.serialize());
|
||||
assertThat(profile.avatar()).isNull();
|
||||
assertThat(profile.version()).isEqualTo("yetanotherversion");
|
||||
assertThat(profile.name()).isEqualTo(name);
|
||||
assertThat(profile.aboutEmoji()).isNull();
|
||||
assertThat(profile.about()).isNull();
|
||||
assertThat(profile.paymentAddress()).isEqualTo(paymentAddress);
|
||||
} else {
|
||||
assertThat(response.getStatus()).isEqualTo(403);
|
||||
assertThat(response.hasEntity()).isFalse();
|
||||
@@ -837,6 +827,13 @@ class ProfileControllerTest {
|
||||
|
||||
@Test
|
||||
void testGetProfileByVersion() throws RateLimitExceededException {
|
||||
final byte[] name = ProfileHelper.generateRandomByteArray(81);
|
||||
final byte[] emoji = ProfileHelper.generateRandomByteArray(60);
|
||||
final byte[] about = ProfileHelper.generateRandomByteArray(156);
|
||||
|
||||
when(profilesManager.get(eq(AuthHelper.VALID_UUID_TWO), eq("validversion"))).thenReturn(Optional.of(new VersionedProfile(
|
||||
"validversion", name, "profiles/validavatar", emoji, about, null, "validcommitmnet".getBytes())));
|
||||
|
||||
final VersionedProfileResponse profile = resources.getJerseyTest()
|
||||
.target("/v1/profile/" + AuthHelper.VALID_UUID_TWO + "/validversion")
|
||||
.request()
|
||||
@@ -844,9 +841,9 @@ class ProfileControllerTest {
|
||||
.get(VersionedProfileResponse.class);
|
||||
|
||||
assertThat(profile.getBaseProfileResponse().getIdentityKey()).isEqualTo(ACCOUNT_TWO_IDENTITY_KEY);
|
||||
assertThat(profile.getName()).isEqualTo("validname");
|
||||
assertThat(profile.getAbout()).isEqualTo("about");
|
||||
assertThat(profile.getAboutEmoji()).isEqualTo("emoji");
|
||||
assertThat(profile.getName()).isEqualTo(ProfileHelper.encodeToBase64(name));
|
||||
assertThat(profile.getAbout()).isEqualTo(ProfileHelper.encodeToBase64(about));
|
||||
assertThat(profile.getAboutEmoji()).isEqualTo(ProfileHelper.encodeToBase64(emoji));
|
||||
assertThat(profile.getAvatar()).isEqualTo("profiles/validavatar");
|
||||
assertThat(profile.getBaseProfileResponse().getCapabilities().gv1Migration()).isTrue();
|
||||
assertThat(profile.getBaseProfileResponse().getUuid()).isEqualTo(new AciServiceIdentifier(AuthHelper.VALID_UUID_TWO));
|
||||
@@ -865,8 +862,8 @@ class ProfileControllerTest {
|
||||
|
||||
clearInvocations(AuthHelper.VALID_ACCOUNT_TWO);
|
||||
|
||||
final String name = RandomStringUtils.randomAlphabetic(380);
|
||||
final String paymentAddress = RandomStringUtils.randomAlphanumeric(776);
|
||||
final String name = ProfileHelper.generateRandomBase64FromByteArray(81);
|
||||
final String paymentAddress = ProfileHelper.generateRandomBase64FromByteArray(582);
|
||||
|
||||
try (final Response response = resources.getJerseyTest()
|
||||
.target("/v1/profile")
|
||||
@@ -885,8 +882,9 @@ class ProfileControllerTest {
|
||||
|
||||
@Test
|
||||
void testGetProfileReturnsNoPaymentAddressIfCurrentVersionMismatch() {
|
||||
final byte[] paymentAddress = ProfileHelper.generateRandomByteArray(582);
|
||||
when(profilesManager.get(AuthHelper.VALID_UUID_TWO, "validversion")).thenReturn(
|
||||
Optional.of(new VersionedProfile(null, null, null, null, null, "paymentaddress", null)));
|
||||
Optional.of(new VersionedProfile(null, null, null, null, null, paymentAddress, null)));
|
||||
|
||||
{
|
||||
final VersionedProfileResponse profile = resources.getJerseyTest()
|
||||
@@ -895,7 +893,7 @@ class ProfileControllerTest {
|
||||
.header("Authorization", AuthHelper.getAuthHeader(AuthHelper.VALID_UUID, AuthHelper.VALID_PASSWORD))
|
||||
.get(VersionedProfileResponse.class);
|
||||
|
||||
assertThat(profile.getPaymentAddress()).isEqualTo("paymentaddress");
|
||||
assertThat(profile.getPaymentAddress()).isEqualTo(ProfileHelper.encodeToBase64(paymentAddress));
|
||||
}
|
||||
|
||||
when(profileAccount.getCurrentProfileVersion()).thenReturn(Optional.of("validversion"));
|
||||
@@ -907,7 +905,7 @@ class ProfileControllerTest {
|
||||
.header("Authorization", AuthHelper.getAuthHeader(AuthHelper.VALID_UUID, AuthHelper.VALID_PASSWORD))
|
||||
.get(VersionedProfileResponse.class);
|
||||
|
||||
assertThat(profile.getPaymentAddress()).isEqualTo("paymentaddress");
|
||||
assertThat(profile.getPaymentAddress()).isEqualTo(ProfileHelper.encodeToBase64(paymentAddress));
|
||||
}
|
||||
|
||||
when(profileAccount.getCurrentProfileVersion()).thenReturn(Optional.of("someotherversion"));
|
||||
@@ -954,15 +952,15 @@ class ProfileControllerTest {
|
||||
|
||||
clearInvocations(AuthHelper.VALID_ACCOUNT_TWO);
|
||||
|
||||
final String name = RandomStringUtils.randomAlphabetic(380);
|
||||
final String emoji = RandomStringUtils.randomAlphanumeric(80);
|
||||
final String text = RandomStringUtils.randomAlphanumeric(720);
|
||||
final String name = ProfileHelper.generateRandomBase64FromByteArray(81);
|
||||
final String emoji = ProfileHelper.generateRandomBase64FromByteArray(60);
|
||||
final String about = ProfileHelper.generateRandomBase64FromByteArray(156);
|
||||
|
||||
try (final Response response = resources.getJerseyTest()
|
||||
.target("/v1/profile/")
|
||||
.request()
|
||||
.header("Authorization", AuthHelper.getAuthHeader(AuthHelper.VALID_UUID_TWO, AuthHelper.VALID_PASSWORD_TWO))
|
||||
.put(Entity.entity(new CreateProfileRequest(commitment, "anotherversion", name, emoji, text, null, false, false,
|
||||
.put(Entity.entity(new CreateProfileRequest(commitment, "anotherversion", name, emoji, about, null, false, false,
|
||||
List.of("TEST2")), MediaType.APPLICATION_JSON_TYPE))) {
|
||||
|
||||
assertThat(response.getStatus()).isEqualTo(200);
|
||||
@@ -985,7 +983,7 @@ class ProfileControllerTest {
|
||||
.target("/v1/profile/")
|
||||
.request()
|
||||
.header("Authorization", AuthHelper.getAuthHeader(AuthHelper.VALID_UUID_TWO, AuthHelper.VALID_PASSWORD_TWO))
|
||||
.put(Entity.entity(new CreateProfileRequest(commitment, "anotherversion", name, emoji, text, null, false, false,
|
||||
.put(Entity.entity(new CreateProfileRequest(commitment, "anotherversion", name, emoji, about, null, false, false,
|
||||
List.of("TEST3", "TEST2")), MediaType.APPLICATION_JSON_TYPE))) {
|
||||
|
||||
assertThat(response.getStatus()).isEqualTo(200);
|
||||
@@ -1011,7 +1009,7 @@ class ProfileControllerTest {
|
||||
.target("/v1/profile/")
|
||||
.request()
|
||||
.header("Authorization", AuthHelper.getAuthHeader(AuthHelper.VALID_UUID_TWO, AuthHelper.VALID_PASSWORD_TWO))
|
||||
.put(Entity.entity(new CreateProfileRequest(commitment, "anotherversion", name, emoji, text, null, false, false,
|
||||
.put(Entity.entity(new CreateProfileRequest(commitment, "anotherversion", name, emoji, about, null, false, false,
|
||||
List.of("TEST2", "TEST3")), MediaType.APPLICATION_JSON_TYPE))) {
|
||||
|
||||
assertThat(response.getStatus()).isEqualTo(200);
|
||||
@@ -1037,7 +1035,7 @@ class ProfileControllerTest {
|
||||
.target("/v1/profile/")
|
||||
.request()
|
||||
.header("Authorization", AuthHelper.getAuthHeader(AuthHelper.VALID_UUID_TWO, AuthHelper.VALID_PASSWORD_TWO))
|
||||
.put(Entity.entity(new CreateProfileRequest(commitment, "anotherversion", name, emoji, text, null, false, false,
|
||||
.put(Entity.entity(new CreateProfileRequest(commitment, "anotherversion", name, emoji, about, null, false, false,
|
||||
List.of("TEST1")), MediaType.APPLICATION_JSON_TYPE))) {
|
||||
|
||||
assertThat(response.getStatus()).isEqualTo(200);
|
||||
@@ -1075,7 +1073,7 @@ class ProfileControllerTest {
|
||||
final ProfileKeyCommitment profileKeyCommitment = profileKey.getCommitment(new ServiceId.Aci(AuthHelper.VALID_UUID));
|
||||
|
||||
final VersionedProfile versionedProfile = mock(VersionedProfile.class);
|
||||
when(versionedProfile.getCommitment()).thenReturn(profileKeyCommitment.serialize());
|
||||
when(versionedProfile.commitment()).thenReturn(profileKeyCommitment.serialize());
|
||||
|
||||
final ProfileKeyCredentialRequestContext profileKeyCredentialRequestContext =
|
||||
clientZkProfile.createProfileKeyCredentialRequestContext(new ServiceId.Aci(AuthHelper.VALID_UUID), profileKey);
|
||||
@@ -1132,9 +1130,9 @@ class ProfileControllerTest {
|
||||
|
||||
clearInvocations(AuthHelper.VALID_ACCOUNT_TWO);
|
||||
|
||||
final String name = RandomStringUtils.randomAlphabetic(380);
|
||||
final String emoji = RandomStringUtils.randomAlphanumeric(80);
|
||||
final String text = RandomStringUtils.randomAlphanumeric(720);
|
||||
final String name = ProfileHelper.generateRandomBase64FromByteArray(81);
|
||||
final String emoji = ProfileHelper.generateRandomBase64FromByteArray(60);
|
||||
final String text = ProfileHelper.generateRandomBase64FromByteArray(156);
|
||||
|
||||
when(AuthHelper.VALID_ACCOUNT_TWO.getBadges()).thenReturn(List.of(
|
||||
new AccountBadge("TEST", Instant.ofEpochSecond(42 + 86400), true)
|
||||
|
||||
+6
-6
@@ -437,10 +437,10 @@ class RegistrationControllerTest {
|
||||
}
|
||||
|
||||
final AccountAttributes fetchesMessagesAccountAttributes =
|
||||
new AccountAttributes(true, 1, "test", null, true, new Device.DeviceCapabilities());
|
||||
new AccountAttributes(true, 1, "test", null, true, new Device.DeviceCapabilities(false, false, false, false));
|
||||
|
||||
final AccountAttributes pushAccountAttributes =
|
||||
new AccountAttributes(false, 1, "test", null, true, new Device.DeviceCapabilities());
|
||||
new AccountAttributes(false, 1, "test", null, true, new Device.DeviceCapabilities(false, false, false, false));
|
||||
|
||||
return Stream.of(
|
||||
// "Fetches messages" is true, but an APNs token is provided
|
||||
@@ -529,7 +529,7 @@ class RegistrationControllerTest {
|
||||
}
|
||||
|
||||
final AccountAttributes accountAttributes =
|
||||
new AccountAttributes(true, 1, "test", null, true, new Device.DeviceCapabilities());
|
||||
new AccountAttributes(true, 1, "test", null, true, new Device.DeviceCapabilities(false, false, false, false));
|
||||
|
||||
return Stream.of(
|
||||
// Signed PNI EC pre-key is missing
|
||||
@@ -720,7 +720,7 @@ class RegistrationControllerTest {
|
||||
|
||||
RegistrationRequest reg = new RegistrationRequest("session-id",
|
||||
new byte[0],
|
||||
new AccountAttributes(true, 1, "test", null, true, new Device.DeviceCapabilities()),
|
||||
new AccountAttributes(true, 1, "test", null, true, new Device.DeviceCapabilities(false, false, false, false)),
|
||||
true,
|
||||
requireAtomic,
|
||||
Optional.empty(),
|
||||
@@ -758,10 +758,10 @@ class RegistrationControllerTest {
|
||||
}
|
||||
|
||||
final AccountAttributes fetchesMessagesAccountAttributes =
|
||||
new AccountAttributes(true, 1, "test", null, true, new Device.DeviceCapabilities());
|
||||
new AccountAttributes(true, 1, "test", null, true, new Device.DeviceCapabilities(false, false, false, false));
|
||||
|
||||
final AccountAttributes pushAccountAttributes =
|
||||
new AccountAttributes(false, 1, "test", null, true, new Device.DeviceCapabilities());
|
||||
new AccountAttributes(false, 1, "test", null, true, new Device.DeviceCapabilities(false, false, false, false));
|
||||
|
||||
final String apnsToken = "apns-token";
|
||||
final String apnsVoipToken = "apns-voip-token";
|
||||
|
||||
+1
-1
@@ -1071,7 +1071,7 @@ class VerificationControllerTest {
|
||||
.request()
|
||||
.header(HttpHeaders.X_FORWARDED_FOR, "127.0.0.1");
|
||||
try (Response response = request.post(Entity.json(requestVerificationCodeJson("voice", "ios")))) {
|
||||
assertEquals(HttpStatus.SC_BAD_GATEWAY, response.getStatus());
|
||||
assertEquals(RegistrationServiceSenderExceptionMapper.REMOTE_SERVICE_REJECTED_REQUEST_STATUS, response.getStatus());
|
||||
|
||||
final Map<String, Object> responseMap = response.readEntity(Map.class);
|
||||
|
||||
|
||||
+106
@@ -0,0 +1,106 @@
|
||||
/*
|
||||
* Copyright 2023 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.grpc;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
import io.grpc.ServerInterceptors;
|
||||
import io.grpc.Status;
|
||||
import io.grpc.StatusRuntimeException;
|
||||
import java.time.Duration;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.RegisterExtension;
|
||||
import org.signal.chat.calling.CallingGrpc;
|
||||
import org.signal.chat.calling.GetTurnCredentialsRequest;
|
||||
import org.signal.chat.calling.GetTurnCredentialsResponse;
|
||||
import org.whispersystems.textsecuregcm.auth.TurnToken;
|
||||
import org.whispersystems.textsecuregcm.auth.TurnTokenGenerator;
|
||||
import org.whispersystems.textsecuregcm.auth.grpc.MockAuthenticationInterceptor;
|
||||
import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimiter;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimiters;
|
||||
import org.whispersystems.textsecuregcm.storage.Device;
|
||||
import reactor.core.publisher.Mono;
|
||||
|
||||
class CallingGrpcServiceTest {
|
||||
|
||||
private TurnTokenGenerator turnTokenGenerator;
|
||||
private RateLimiter turnCredentialRateLimiter;
|
||||
|
||||
private CallingGrpc.CallingBlockingStub callingStub;
|
||||
|
||||
private static final UUID AUTHENTICATED_ACI = UUID.randomUUID();
|
||||
private static final long AUTHENTICATED_DEVICE_ID = Device.MASTER_ID;
|
||||
|
||||
@RegisterExtension
|
||||
static final GrpcServerExtension GRPC_SERVER_EXTENSION = new GrpcServerExtension();
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
turnTokenGenerator = mock(TurnTokenGenerator.class);
|
||||
turnCredentialRateLimiter = mock(RateLimiter.class);
|
||||
|
||||
final RateLimiters rateLimiters = mock(RateLimiters.class);
|
||||
when(rateLimiters.getTurnLimiter()).thenReturn(turnCredentialRateLimiter);
|
||||
|
||||
final CallingGrpcService callingGrpcService = new CallingGrpcService(turnTokenGenerator, rateLimiters);
|
||||
|
||||
final MockAuthenticationInterceptor mockAuthenticationInterceptor = new MockAuthenticationInterceptor();
|
||||
mockAuthenticationInterceptor.setAuthenticatedDevice(AUTHENTICATED_ACI, AUTHENTICATED_DEVICE_ID);
|
||||
|
||||
GRPC_SERVER_EXTENSION.getServiceRegistry()
|
||||
.addService(ServerInterceptors.intercept(callingGrpcService, mockAuthenticationInterceptor));
|
||||
|
||||
callingStub = CallingGrpc.newBlockingStub(GRPC_SERVER_EXTENSION.getChannel());
|
||||
}
|
||||
|
||||
@Test
|
||||
void getTurnCredentials() {
|
||||
final String username = "test-username";
|
||||
final String password = "test-password";
|
||||
final List<String> urls = List.of("first", "second");
|
||||
|
||||
when(turnCredentialRateLimiter.validateReactive(AUTHENTICATED_ACI)).thenReturn(Mono.empty());
|
||||
when(turnTokenGenerator.generate(any())).thenReturn(new TurnToken(username, password, urls));
|
||||
|
||||
final GetTurnCredentialsResponse response = callingStub.getTurnCredentials(GetTurnCredentialsRequest.newBuilder().build());
|
||||
|
||||
final GetTurnCredentialsResponse expectedResponse = GetTurnCredentialsResponse.newBuilder()
|
||||
.setUsername(username)
|
||||
.setPassword(password)
|
||||
.addAllUrls(urls)
|
||||
.build();
|
||||
|
||||
assertEquals(expectedResponse, response);
|
||||
}
|
||||
|
||||
@Test
|
||||
void getTurnCredentialsRateLimited() {
|
||||
final Duration retryAfter = Duration.ofMinutes(19);
|
||||
|
||||
when(turnCredentialRateLimiter.validateReactive(AUTHENTICATED_ACI))
|
||||
.thenReturn(Mono.error(new RateLimitExceededException(retryAfter, false)));
|
||||
|
||||
final StatusRuntimeException exception =
|
||||
assertThrows(StatusRuntimeException.class, () -> callingStub.getTurnCredentials(GetTurnCredentialsRequest.newBuilder().build()));
|
||||
|
||||
verify(turnTokenGenerator, never()).generate(any());
|
||||
|
||||
assertEquals(Status.Code.RESOURCE_EXHAUSTED, exception.getStatus().getCode());
|
||||
assertNotNull(exception.getTrailers());
|
||||
assertEquals(retryAfter, exception.getTrailers().get(RateLimitUtil.RETRY_AFTER_DURATION_KEY));
|
||||
}
|
||||
}
|
||||
+3
-3
@@ -152,7 +152,7 @@ class KeysAnonymousGrpcServiceTest {
|
||||
when(accountsManager.getByServiceIdentifierAsync(new AciServiceIdentifier(identifier)))
|
||||
.thenReturn(CompletableFuture.completedFuture(Optional.of(targetAccount)));
|
||||
|
||||
@SuppressWarnings("ResultOfMethodCallIgnored") final StatusRuntimeException statusRuntimeException =
|
||||
final StatusRuntimeException statusRuntimeException =
|
||||
assertThrows(StatusRuntimeException.class,
|
||||
() -> keysAnonymousStub.getPreKeys(GetPreKeysAnonymousRequest.newBuilder()
|
||||
.setRequest(GetPreKeysRequest.newBuilder()
|
||||
@@ -172,7 +172,7 @@ class KeysAnonymousGrpcServiceTest {
|
||||
when(accountsManager.getByServiceIdentifierAsync(any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(Optional.empty()));
|
||||
|
||||
@SuppressWarnings("ResultOfMethodCallIgnored") final StatusRuntimeException exception =
|
||||
final StatusRuntimeException exception =
|
||||
assertThrows(StatusRuntimeException.class,
|
||||
() -> keysAnonymousStub.getPreKeys(GetPreKeysAnonymousRequest.newBuilder()
|
||||
.setUnidentifiedAccessKey(UUIDUtil.toByteString(UUID.randomUUID()))
|
||||
@@ -205,7 +205,7 @@ class KeysAnonymousGrpcServiceTest {
|
||||
when(accountsManager.getByServiceIdentifierAsync(new AciServiceIdentifier(accountIdentifier)))
|
||||
.thenReturn(CompletableFuture.completedFuture(Optional.of(targetAccount)));
|
||||
|
||||
@SuppressWarnings("ResultOfMethodCallIgnored") final StatusRuntimeException exception =
|
||||
final StatusRuntimeException exception =
|
||||
assertThrows(StatusRuntimeException.class,
|
||||
() -> keysAnonymousStub.getPreKeys(GetPreKeysAnonymousRequest.newBuilder()
|
||||
.setUnidentifiedAccessKey(ByteString.copyFrom(unidentifiedAccessKey))
|
||||
|
||||
+81
-81
@@ -188,34 +188,37 @@ class KeysGrpcServiceTest {
|
||||
@ParameterizedTest
|
||||
@MethodSource
|
||||
void setOneTimeEcPreKeysWithError(final SetOneTimeEcPreKeysRequest request) {
|
||||
@SuppressWarnings("ResultOfMethodCallIgnored") final StatusRuntimeException exception =
|
||||
final StatusRuntimeException exception =
|
||||
assertThrows(StatusRuntimeException.class, () -> keysStub.setOneTimeEcPreKeys(request));
|
||||
|
||||
assertEquals(Status.INVALID_ARGUMENT.getCode(), exception.getStatus().getCode());
|
||||
}
|
||||
|
||||
private static Stream<Arguments> setOneTimeEcPreKeysWithError() {
|
||||
final SetOneTimeEcPreKeysRequest prototypeRequest = SetOneTimeEcPreKeysRequest.newBuilder()
|
||||
.setIdentityType(org.signal.chat.common.IdentityType.IDENTITY_TYPE_ACI)
|
||||
.addPreKeys(EcPreKey.newBuilder()
|
||||
.setKeyId(1)
|
||||
.setPublicKey(ByteString.copyFrom(Curve.generateKeyPair().getPublicKey().serialize()))
|
||||
.build())
|
||||
.build();
|
||||
|
||||
return Stream.of(
|
||||
// Missing identity type
|
||||
Arguments.of(SetOneTimeEcPreKeysRequest.newBuilder()
|
||||
.addPreKeys(EcPreKey.newBuilder()
|
||||
.setKeyId(1)
|
||||
.setPublicKey(ByteString.copyFrom(Curve.generateKeyPair().getPublicKey().serialize()))
|
||||
.build())
|
||||
Arguments.of(SetOneTimeEcPreKeysRequest.newBuilder(prototypeRequest)
|
||||
.clearIdentityType()
|
||||
.build()),
|
||||
|
||||
// Invalid public key
|
||||
Arguments.of(SetOneTimeEcPreKeysRequest.newBuilder()
|
||||
.setIdentityType(org.signal.chat.common.IdentityType.IDENTITY_TYPE_ACI)
|
||||
.addPreKeys(EcPreKey.newBuilder()
|
||||
.setKeyId(1)
|
||||
.setPublicKey(ByteString.empty())
|
||||
Arguments.of(SetOneTimeEcPreKeysRequest.newBuilder(prototypeRequest)
|
||||
.setPreKeys(0, EcPreKey.newBuilder(prototypeRequest.getPreKeys(0))
|
||||
.clearPublicKey()
|
||||
.build())
|
||||
.build()),
|
||||
|
||||
// No keys
|
||||
Arguments.of(SetOneTimeEcPreKeysRequest.newBuilder()
|
||||
.setIdentityType(org.signal.chat.common.IdentityType.IDENTITY_TYPE_ACI)
|
||||
Arguments.of(SetOneTimeEcPreKeysRequest.newBuilder(prototypeRequest)
|
||||
.clearPreKeys()
|
||||
.build())
|
||||
);
|
||||
}
|
||||
@@ -261,7 +264,7 @@ class KeysGrpcServiceTest {
|
||||
@ParameterizedTest
|
||||
@MethodSource
|
||||
void setOneTimeKemSignedPreKeysWithError(final SetOneTimeKemSignedPreKeysRequest request) {
|
||||
@SuppressWarnings("ResultOfMethodCallIgnored") final StatusRuntimeException exception =
|
||||
final StatusRuntimeException exception =
|
||||
assertThrows(StatusRuntimeException.class, () -> keysStub.setOneTimeKemSignedPreKeys(request));
|
||||
|
||||
assertEquals(Status.INVALID_ARGUMENT.getCode(), exception.getStatus().getCode());
|
||||
@@ -270,39 +273,38 @@ class KeysGrpcServiceTest {
|
||||
private static Stream<Arguments> setOneTimeKemSignedPreKeysWithError() {
|
||||
final KEMSignedPreKey signedPreKey = KeysHelper.signedKEMPreKey(1, ACI_IDENTITY_KEY_PAIR);
|
||||
|
||||
final SetOneTimeKemSignedPreKeysRequest prototypeRequest = SetOneTimeKemSignedPreKeysRequest.newBuilder()
|
||||
.setIdentityType(org.signal.chat.common.IdentityType.IDENTITY_TYPE_ACI)
|
||||
.addPreKeys(KemSignedPreKey.newBuilder()
|
||||
.setKeyId(1)
|
||||
.setPublicKey(ByteString.copyFrom(signedPreKey.serializedPublicKey()))
|
||||
.setSignature(ByteString.copyFrom(signedPreKey.signature()))
|
||||
.build())
|
||||
.build();
|
||||
|
||||
return Stream.of(
|
||||
// Missing identity type
|
||||
Arguments.of(SetOneTimeKemSignedPreKeysRequest.newBuilder()
|
||||
.addPreKeys(KemSignedPreKey.newBuilder()
|
||||
.setKeyId(1)
|
||||
.setPublicKey(ByteString.copyFrom(signedPreKey.serializedPublicKey()))
|
||||
.setSignature(ByteString.copyFrom(signedPreKey.signature()))
|
||||
.build())
|
||||
Arguments.of(SetOneTimeKemSignedPreKeysRequest.newBuilder(prototypeRequest)
|
||||
.clearIdentityType()
|
||||
.build()),
|
||||
|
||||
// Invalid public key
|
||||
Arguments.of(SetOneTimeKemSignedPreKeysRequest.newBuilder()
|
||||
.setIdentityType(org.signal.chat.common.IdentityType.IDENTITY_TYPE_ACI)
|
||||
.addPreKeys(KemSignedPreKey.newBuilder()
|
||||
.setKeyId(1)
|
||||
.setPublicKey(ByteString.empty())
|
||||
.setSignature(ByteString.copyFrom(signedPreKey.signature()))
|
||||
Arguments.of(SetOneTimeKemSignedPreKeysRequest.newBuilder(prototypeRequest)
|
||||
.setPreKeys(0, KemSignedPreKey.newBuilder(prototypeRequest.getPreKeys(0))
|
||||
.clearPublicKey()
|
||||
.build())
|
||||
.build()),
|
||||
|
||||
// Invalid signature
|
||||
Arguments.of(SetOneTimeKemSignedPreKeysRequest.newBuilder()
|
||||
.setIdentityType(org.signal.chat.common.IdentityType.IDENTITY_TYPE_ACI)
|
||||
.addPreKeys(KemSignedPreKey.newBuilder()
|
||||
.setKeyId(1)
|
||||
.setPublicKey(ByteString.copyFrom(signedPreKey.serializedPublicKey()))
|
||||
.setSignature(ByteString.empty())
|
||||
Arguments.of(SetOneTimeKemSignedPreKeysRequest.newBuilder(prototypeRequest)
|
||||
.setPreKeys(0, KemSignedPreKey.newBuilder(prototypeRequest.getPreKeys(0))
|
||||
.clearSignature()
|
||||
.build())
|
||||
.build()),
|
||||
|
||||
// No keys
|
||||
Arguments.of(SetOneTimeKemSignedPreKeysRequest.newBuilder()
|
||||
.setIdentityType(org.signal.chat.common.IdentityType.IDENTITY_TYPE_ACI)
|
||||
Arguments.of(SetOneTimeKemSignedPreKeysRequest.newBuilder(prototypeRequest)
|
||||
.clearPreKeys()
|
||||
.build())
|
||||
);
|
||||
}
|
||||
@@ -355,7 +357,7 @@ class KeysGrpcServiceTest {
|
||||
@ParameterizedTest
|
||||
@MethodSource
|
||||
void setSignedPreKeyWithError(final SetEcSignedPreKeyRequest request) {
|
||||
@SuppressWarnings("ResultOfMethodCallIgnored") final StatusRuntimeException exception =
|
||||
final StatusRuntimeException exception =
|
||||
assertThrows(StatusRuntimeException.class, () -> keysStub.setEcSignedPreKey(request));
|
||||
|
||||
assertEquals(Status.INVALID_ARGUMENT.getCode(), exception.getStatus().getCode());
|
||||
@@ -364,39 +366,38 @@ class KeysGrpcServiceTest {
|
||||
private static Stream<Arguments> setSignedPreKeyWithError() {
|
||||
final ECSignedPreKey signedPreKey = KeysHelper.signedECPreKey(17, ACI_IDENTITY_KEY_PAIR);
|
||||
|
||||
final SetEcSignedPreKeyRequest prototypeRequest = SetEcSignedPreKeyRequest.newBuilder()
|
||||
.setIdentityType(org.signal.chat.common.IdentityType.IDENTITY_TYPE_ACI)
|
||||
.setSignedPreKey(EcSignedPreKey.newBuilder()
|
||||
.setKeyId(signedPreKey.keyId())
|
||||
.setPublicKey(ByteString.copyFrom(signedPreKey.serializedPublicKey()))
|
||||
.setSignature(ByteString.copyFrom(signedPreKey.signature()))
|
||||
.build())
|
||||
.build();
|
||||
|
||||
return Stream.of(
|
||||
// Missing identity type
|
||||
Arguments.of(SetEcSignedPreKeyRequest.newBuilder()
|
||||
.setSignedPreKey(EcSignedPreKey.newBuilder()
|
||||
.setKeyId(signedPreKey.keyId())
|
||||
.setPublicKey(ByteString.copyFrom(signedPreKey.serializedPublicKey()))
|
||||
.setSignature(ByteString.copyFrom(signedPreKey.signature()))
|
||||
.build())
|
||||
Arguments.of(SetEcSignedPreKeyRequest.newBuilder(prototypeRequest)
|
||||
.clearIdentityType()
|
||||
.build()),
|
||||
|
||||
// Invalid public key
|
||||
Arguments.of(SetEcSignedPreKeyRequest.newBuilder()
|
||||
.setIdentityType(org.signal.chat.common.IdentityType.IDENTITY_TYPE_ACI)
|
||||
.setSignedPreKey(EcSignedPreKey.newBuilder()
|
||||
.setKeyId(signedPreKey.keyId())
|
||||
.setPublicKey(ByteString.empty())
|
||||
.setSignature(ByteString.copyFrom(signedPreKey.signature()))
|
||||
Arguments.of(SetEcSignedPreKeyRequest.newBuilder(prototypeRequest)
|
||||
.setSignedPreKey(EcSignedPreKey.newBuilder(prototypeRequest.getSignedPreKey())
|
||||
.clearPublicKey()
|
||||
.build())
|
||||
.build()),
|
||||
|
||||
// Invalid signature
|
||||
Arguments.of(SetEcSignedPreKeyRequest.newBuilder()
|
||||
.setIdentityType(org.signal.chat.common.IdentityType.IDENTITY_TYPE_ACI)
|
||||
.setSignedPreKey(EcSignedPreKey.newBuilder()
|
||||
.setKeyId(signedPreKey.keyId())
|
||||
.setPublicKey(ByteString.copyFrom(signedPreKey.serializedPublicKey()))
|
||||
.setSignature(ByteString.empty())
|
||||
.build())
|
||||
.build()),
|
||||
Arguments.of(SetEcSignedPreKeyRequest.newBuilder(prototypeRequest)
|
||||
.setSignedPreKey(EcSignedPreKey.newBuilder(prototypeRequest.getSignedPreKey())
|
||||
.clearSignature()
|
||||
.build())
|
||||
.build()),
|
||||
|
||||
// Missing key
|
||||
Arguments.of(SetEcSignedPreKeyRequest.newBuilder()
|
||||
.setIdentityType(org.signal.chat.common.IdentityType.IDENTITY_TYPE_ACI)
|
||||
Arguments.of(SetEcSignedPreKeyRequest.newBuilder(prototypeRequest)
|
||||
.clearSignedPreKey()
|
||||
.build())
|
||||
);
|
||||
}
|
||||
@@ -435,7 +436,7 @@ class KeysGrpcServiceTest {
|
||||
@ParameterizedTest
|
||||
@MethodSource
|
||||
void setLastResortPreKeyWithError(final SetKemLastResortPreKeyRequest request) {
|
||||
@SuppressWarnings("ResultOfMethodCallIgnored") final StatusRuntimeException exception =
|
||||
final StatusRuntimeException exception =
|
||||
assertThrows(StatusRuntimeException.class, () -> keysStub.setKemLastResortPreKey(request));
|
||||
|
||||
assertEquals(Status.INVALID_ARGUMENT.getCode(), exception.getStatus().getCode());
|
||||
@@ -444,39 +445,38 @@ class KeysGrpcServiceTest {
|
||||
private static Stream<Arguments> setLastResortPreKeyWithError() {
|
||||
final KEMSignedPreKey lastResortPreKey = KeysHelper.signedKEMPreKey(17, ACI_IDENTITY_KEY_PAIR);
|
||||
|
||||
final SetKemLastResortPreKeyRequest prototypeRequest = SetKemLastResortPreKeyRequest.newBuilder()
|
||||
.setIdentityType(org.signal.chat.common.IdentityType.IDENTITY_TYPE_ACI)
|
||||
.setSignedPreKey(KemSignedPreKey.newBuilder()
|
||||
.setKeyId(lastResortPreKey.keyId())
|
||||
.setPublicKey(ByteString.copyFrom(lastResortPreKey.serializedPublicKey()))
|
||||
.setSignature(ByteString.copyFrom(lastResortPreKey.signature()))
|
||||
.build())
|
||||
.build();
|
||||
|
||||
return Stream.of(
|
||||
// No identity type
|
||||
Arguments.of(SetKemLastResortPreKeyRequest.newBuilder()
|
||||
.setSignedPreKey(KemSignedPreKey.newBuilder()
|
||||
.setKeyId(lastResortPreKey.keyId())
|
||||
.setPublicKey(ByteString.copyFrom(lastResortPreKey.serializedPublicKey()))
|
||||
.setSignature(ByteString.copyFrom(lastResortPreKey.signature()))
|
||||
.build())
|
||||
Arguments.of(SetKemLastResortPreKeyRequest.newBuilder(prototypeRequest)
|
||||
.clearIdentityType()
|
||||
.build()),
|
||||
|
||||
// Bad public key
|
||||
Arguments.of(SetKemLastResortPreKeyRequest.newBuilder()
|
||||
.setIdentityType(org.signal.chat.common.IdentityType.IDENTITY_TYPE_ACI)
|
||||
.setSignedPreKey(KemSignedPreKey.newBuilder()
|
||||
.setKeyId(lastResortPreKey.keyId())
|
||||
.setPublicKey(ByteString.empty())
|
||||
.setSignature(ByteString.copyFrom(lastResortPreKey.signature()))
|
||||
Arguments.of(SetKemLastResortPreKeyRequest.newBuilder(prototypeRequest)
|
||||
.setSignedPreKey(KemSignedPreKey.newBuilder(prototypeRequest.getSignedPreKey())
|
||||
.clearPublicKey()
|
||||
.build())
|
||||
.build()),
|
||||
|
||||
// Bad signature
|
||||
Arguments.of(SetKemLastResortPreKeyRequest.newBuilder()
|
||||
.setIdentityType(org.signal.chat.common.IdentityType.IDENTITY_TYPE_ACI)
|
||||
.setSignedPreKey(KemSignedPreKey.newBuilder()
|
||||
.setKeyId(lastResortPreKey.keyId())
|
||||
.setPublicKey(ByteString.copyFrom(lastResortPreKey.serializedPublicKey()))
|
||||
.setSignature(ByteString.empty())
|
||||
Arguments.of(SetKemLastResortPreKeyRequest.newBuilder(prototypeRequest)
|
||||
.setSignedPreKey(KemSignedPreKey.newBuilder(prototypeRequest.getSignedPreKey())
|
||||
.clearSignature()
|
||||
.build())
|
||||
.build()),
|
||||
|
||||
// Missing key
|
||||
Arguments.of(SetKemLastResortPreKeyRequest.newBuilder()
|
||||
.setIdentityType(org.signal.chat.common.IdentityType.IDENTITY_TYPE_ACI)
|
||||
Arguments.of(SetKemLastResortPreKeyRequest.newBuilder(prototypeRequest)
|
||||
.clearSignedPreKey()
|
||||
.build())
|
||||
);
|
||||
}
|
||||
@@ -605,7 +605,7 @@ class KeysGrpcServiceTest {
|
||||
when(accountsManager.getByServiceIdentifierAsync(any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(Optional.empty()));
|
||||
|
||||
@SuppressWarnings("ResultOfMethodCallIgnored") final StatusRuntimeException exception =
|
||||
final StatusRuntimeException exception =
|
||||
assertThrows(StatusRuntimeException.class, () -> keysStub.getPreKeys(GetPreKeysRequest.newBuilder()
|
||||
.setTargetIdentifier(ServiceIdentifier.newBuilder()
|
||||
.setIdentityType(org.signal.chat.common.IdentityType.IDENTITY_TYPE_ACI)
|
||||
@@ -630,7 +630,7 @@ class KeysGrpcServiceTest {
|
||||
when(accountsManager.getByServiceIdentifierAsync(new AciServiceIdentifier(accountIdentifier)))
|
||||
.thenReturn(CompletableFuture.completedFuture(Optional.of(targetAccount)));
|
||||
|
||||
@SuppressWarnings("ResultOfMethodCallIgnored") final StatusRuntimeException exception =
|
||||
final StatusRuntimeException exception =
|
||||
assertThrows(StatusRuntimeException.class, () -> keysStub.getPreKeys(GetPreKeysRequest.newBuilder()
|
||||
.setTargetIdentifier(ServiceIdentifier.newBuilder()
|
||||
.setIdentityType(org.signal.chat.common.IdentityType.IDENTITY_TYPE_ACI)
|
||||
@@ -658,7 +658,7 @@ class KeysGrpcServiceTest {
|
||||
when(preKeysRateLimiter.validateReactive(anyString()))
|
||||
.thenReturn(Mono.error(new RateLimitExceededException(retryAfterDuration, false)));
|
||||
|
||||
@SuppressWarnings("ResultOfMethodCallIgnored") final StatusRuntimeException exception =
|
||||
final StatusRuntimeException exception =
|
||||
assertThrows(StatusRuntimeException.class, () -> keysStub.getPreKeys(GetPreKeysRequest.newBuilder()
|
||||
.setTargetIdentifier(ServiceIdentifier.newBuilder()
|
||||
.setIdentityType(org.signal.chat.common.IdentityType.IDENTITY_TYPE_ACI)
|
||||
|
||||
+339
@@ -0,0 +1,339 @@
|
||||
package org.whispersystems.textsecuregcm.grpc;
|
||||
|
||||
import com.google.i18n.phonenumbers.PhoneNumberUtil;
|
||||
import com.google.i18n.phonenumbers.Phonenumber;
|
||||
import com.google.protobuf.ByteString;
|
||||
import io.grpc.ServerInterceptors;
|
||||
import io.grpc.Status;
|
||||
import io.grpc.StatusRuntimeException;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.extension.RegisterExtension;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.Arguments;
|
||||
import org.junit.jupiter.params.provider.MethodSource;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
import org.signal.chat.profile.SetProfileRequest.AvatarChange;
|
||||
import org.signal.chat.profile.ProfileGrpc;
|
||||
import org.signal.chat.profile.SetProfileRequest;
|
||||
import org.signal.chat.profile.SetProfileResponse;
|
||||
import org.signal.libsignal.protocol.ServiceId;
|
||||
import org.signal.libsignal.zkgroup.InvalidInputException;
|
||||
import org.signal.libsignal.zkgroup.profiles.ProfileKey;
|
||||
import org.whispersystems.textsecuregcm.auth.grpc.MockAuthenticationInterceptor;
|
||||
import org.whispersystems.textsecuregcm.configuration.BadgeConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.BadgesConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicPaymentsConfiguration;
|
||||
import org.whispersystems.textsecuregcm.entities.BadgeSvg;
|
||||
import org.whispersystems.textsecuregcm.s3.PolicySigner;
|
||||
import org.whispersystems.textsecuregcm.s3.PostPolicyGenerator;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.Device;
|
||||
import org.whispersystems.textsecuregcm.storage.DynamicConfigurationManager;
|
||||
import org.whispersystems.textsecuregcm.storage.ProfilesManager;
|
||||
import org.whispersystems.textsecuregcm.storage.VersionedProfile;
|
||||
import org.whispersystems.textsecuregcm.tests.util.AuthHelper;
|
||||
import software.amazon.awssdk.services.s3.S3AsyncClient;
|
||||
import software.amazon.awssdk.services.s3.model.DeleteObjectRequest;
|
||||
import java.time.Clock;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.verifyNoInteractions;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
public class ProfileGrpcServiceTest {
|
||||
private static final UUID AUTHENTICATED_ACI = UUID.randomUUID();
|
||||
private static final long AUTHENTICATED_DEVICE_ID = Device.MASTER_ID;
|
||||
private static final String S3_BUCKET = "profileBucket";
|
||||
private static final String VERSION = "someVersion";
|
||||
private static final byte[] VALID_NAME = new byte[81];
|
||||
private ProfilesManager profilesManager;
|
||||
private DynamicPaymentsConfiguration dynamicPaymentsConfiguration;
|
||||
private S3AsyncClient asyncS3client;
|
||||
private VersionedProfile profile;
|
||||
private Account account;
|
||||
private ProfileGrpc.ProfileBlockingStub profileBlockingStub;
|
||||
|
||||
@RegisterExtension
|
||||
static final GrpcServerExtension GRPC_SERVER_EXTENSION = new GrpcServerExtension();
|
||||
|
||||
@BeforeEach
|
||||
void setup() {
|
||||
profilesManager = mock(ProfilesManager.class);
|
||||
dynamicPaymentsConfiguration = mock(DynamicPaymentsConfiguration.class);
|
||||
asyncS3client = mock(S3AsyncClient.class);
|
||||
profile = mock(VersionedProfile.class);
|
||||
account = mock(Account.class);
|
||||
|
||||
final AccountsManager accountsManager = mock(AccountsManager.class);
|
||||
@SuppressWarnings("unchecked") final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager = mock(DynamicConfigurationManager.class);
|
||||
final DynamicConfiguration dynamicConfiguration = mock(DynamicConfiguration.class);
|
||||
final PolicySigner policySigner = new PolicySigner("accessSecret", "us-west-1");
|
||||
final PostPolicyGenerator policyGenerator = new PostPolicyGenerator("us-west-1", "profile-bucket", "accessKey");
|
||||
final BadgesConfiguration badgesConfiguration = new BadgesConfiguration(
|
||||
List.of(new BadgeConfiguration(
|
||||
"TEST",
|
||||
"other",
|
||||
List.of("l", "m", "h", "x", "xx", "xxx"),
|
||||
"SVG",
|
||||
List.of(
|
||||
new BadgeSvg("sl", "sd"),
|
||||
new BadgeSvg("ml", "md"),
|
||||
new BadgeSvg("ll", "ld")
|
||||
)
|
||||
)),
|
||||
List.of("TEST1"),
|
||||
Map.of(1L, "TEST1", 2L, "TEST2", 3L, "TEST3")
|
||||
);
|
||||
final String phoneNumber = PhoneNumberUtil.getInstance().format(
|
||||
PhoneNumberUtil.getInstance().getExampleNumber("US"),
|
||||
PhoneNumberUtil.PhoneNumberFormat.E164);
|
||||
|
||||
profileBlockingStub = ProfileGrpc.newBlockingStub(GRPC_SERVER_EXTENSION.getChannel());
|
||||
|
||||
final ProfileGrpcService profileGrpcService = new ProfileGrpcService(
|
||||
Clock.systemUTC(),
|
||||
accountsManager,
|
||||
profilesManager,
|
||||
dynamicConfigurationManager,
|
||||
badgesConfiguration,
|
||||
asyncS3client,
|
||||
policyGenerator,
|
||||
policySigner,
|
||||
S3_BUCKET
|
||||
);
|
||||
|
||||
final MockAuthenticationInterceptor mockAuthenticationInterceptor = new MockAuthenticationInterceptor();
|
||||
mockAuthenticationInterceptor.setAuthenticatedDevice(AUTHENTICATED_ACI, AUTHENTICATED_DEVICE_ID);
|
||||
|
||||
GRPC_SERVER_EXTENSION.getServiceRegistry()
|
||||
.addService(ServerInterceptors.intercept(profileGrpcService, mockAuthenticationInterceptor));
|
||||
|
||||
when(dynamicConfigurationManager.getConfiguration()).thenReturn(dynamicConfiguration);
|
||||
when(dynamicConfiguration.getPaymentsConfiguration()).thenReturn(dynamicPaymentsConfiguration);
|
||||
|
||||
when(account.getUuid()).thenReturn(AUTHENTICATED_ACI);
|
||||
when(account.getNumber()).thenReturn(phoneNumber);
|
||||
when(account.getBadges()).thenReturn(Collections.emptyList());
|
||||
|
||||
when(profile.paymentAddress()).thenReturn(null);
|
||||
when(profile.avatar()).thenReturn("");
|
||||
|
||||
when(accountsManager.getByAccountIdentifierAsync(any())).thenReturn(CompletableFuture.completedFuture(Optional.of(account)));
|
||||
when(accountsManager.updateAsync(any(), any())).thenReturn(CompletableFuture.completedFuture(null));
|
||||
|
||||
when(profilesManager.getAsync(any(), any())).thenReturn(CompletableFuture.completedFuture(Optional.of(profile)));
|
||||
when(profilesManager.setAsync(any(), any())).thenReturn(CompletableFuture.completedFuture(null));
|
||||
|
||||
when(dynamicConfigurationManager.getConfiguration()).thenReturn(dynamicConfiguration);
|
||||
when(dynamicConfiguration.getPaymentsConfiguration()).thenReturn(dynamicPaymentsConfiguration);
|
||||
when(dynamicPaymentsConfiguration.getDisallowedPrefixes()).thenReturn(Collections.emptyList());
|
||||
|
||||
when(asyncS3client.deleteObject(any(DeleteObjectRequest.class))).thenReturn(CompletableFuture.completedFuture(null));
|
||||
}
|
||||
|
||||
@Test
|
||||
void setProfile() throws InvalidInputException {
|
||||
final byte[] commitment = new ProfileKey(new byte[32]).getCommitment(new ServiceId.Aci(AUTHENTICATED_ACI)).serialize();
|
||||
final byte[] validAboutEmoji = new byte[60];
|
||||
final byte[] validAbout = new byte[540];
|
||||
final byte[] validPaymentAddress = new byte[582];
|
||||
|
||||
final SetProfileRequest request = SetProfileRequest.newBuilder()
|
||||
.setVersion(VERSION)
|
||||
.setName(ByteString.copyFrom(VALID_NAME))
|
||||
.setAvatarChange(AvatarChange.AVATAR_CHANGE_UNCHANGED)
|
||||
.setAboutEmoji(ByteString.copyFrom(validAboutEmoji))
|
||||
.setAbout(ByteString.copyFrom(validAbout))
|
||||
.setPaymentAddress(ByteString.copyFrom(validPaymentAddress))
|
||||
.setCommitment(ByteString.copyFrom(commitment))
|
||||
.build();
|
||||
|
||||
//noinspection ResultOfMethodCallIgnored
|
||||
profileBlockingStub.setProfile(request);
|
||||
|
||||
final ArgumentCaptor<VersionedProfile> profileArgumentCaptor = ArgumentCaptor.forClass(VersionedProfile.class);
|
||||
|
||||
verify(profilesManager).setAsync(eq(account.getUuid()), profileArgumentCaptor.capture());
|
||||
|
||||
final VersionedProfile profile = profileArgumentCaptor.getValue();
|
||||
|
||||
assertThat(profile.commitment()).isEqualTo(commitment);
|
||||
assertThat(profile.avatar()).isNull();
|
||||
assertThat(profile.version()).isEqualTo(VERSION);
|
||||
assertThat(profile.name()).isEqualTo(VALID_NAME);
|
||||
assertThat(profile.aboutEmoji()).isEqualTo(validAboutEmoji);
|
||||
assertThat(profile.about()).isEqualTo(validAbout);
|
||||
assertThat(profile.paymentAddress()).isEqualTo(validPaymentAddress);
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@MethodSource
|
||||
void setProfileUpload(AvatarChange avatarChange, boolean hasPreviousProfile,
|
||||
boolean expectHasS3UploadPath, boolean expectDeleteS3Object) throws InvalidInputException {
|
||||
final String currentAvatar = "profiles/currentAvatar";
|
||||
final byte[] commitment = new ProfileKey(new byte[32]).getCommitment(new ServiceId.Aci(AUTHENTICATED_ACI)).serialize();
|
||||
|
||||
final SetProfileRequest request = SetProfileRequest.newBuilder()
|
||||
.setVersion(VERSION)
|
||||
.setName(ByteString.copyFrom(VALID_NAME))
|
||||
.setAvatarChange(avatarChange)
|
||||
.setCommitment(ByteString.copyFrom(commitment))
|
||||
.build();
|
||||
|
||||
when(profile.avatar()).thenReturn(currentAvatar);
|
||||
|
||||
when(profilesManager.getAsync(any(), anyString())).thenReturn(CompletableFuture.completedFuture(
|
||||
hasPreviousProfile ? Optional.of(profile) : Optional.empty()));
|
||||
when(profilesManager.setAsync(any(), any())).thenReturn(CompletableFuture.completedFuture(null));
|
||||
|
||||
SetProfileResponse response = profileBlockingStub.setProfile(request);
|
||||
|
||||
if (expectHasS3UploadPath) {
|
||||
assertTrue(response.getAttributes().getPath().startsWith("profiles/"));
|
||||
} else {
|
||||
assertEquals(response.getAttributes().getPath(), "");
|
||||
}
|
||||
|
||||
if (expectDeleteS3Object) {
|
||||
verify(asyncS3client).deleteObject(DeleteObjectRequest.builder()
|
||||
.bucket(S3_BUCKET)
|
||||
.key(currentAvatar)
|
||||
.build());
|
||||
} else {
|
||||
verifyNoInteractions(asyncS3client);
|
||||
}
|
||||
}
|
||||
|
||||
private static Stream<Arguments> setProfileUpload() {
|
||||
return Stream.of(
|
||||
// Upload new avatar, no previous avatar
|
||||
Arguments.of(AvatarChange.AVATAR_CHANGE_UPDATE, false, true, false),
|
||||
// Upload new avatar, has previous avatar
|
||||
Arguments.of(AvatarChange.AVATAR_CHANGE_UPDATE, true, true, true),
|
||||
// Clear avatar on profile, no previous avatar
|
||||
Arguments.of(AvatarChange.AVATAR_CHANGE_CLEAR, false, false, false),
|
||||
// Clear avatar on profile, has previous avatar
|
||||
Arguments.of(AvatarChange.AVATAR_CHANGE_CLEAR, true, false, true),
|
||||
// Set same avatar, no previous avatar
|
||||
Arguments.of(AvatarChange.AVATAR_CHANGE_UNCHANGED, false, false, false),
|
||||
// Set same avatar, has previous avatar
|
||||
Arguments.of(AvatarChange.AVATAR_CHANGE_UNCHANGED, true, false, false)
|
||||
);
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@MethodSource
|
||||
void setProfileInvalidRequestData(SetProfileRequest request) {
|
||||
final StatusRuntimeException exception =
|
||||
assertThrows(StatusRuntimeException.class, () -> profileBlockingStub.setProfile(request));
|
||||
|
||||
assertEquals(Status.INVALID_ARGUMENT.getCode(), exception.getStatus().getCode());
|
||||
}
|
||||
|
||||
private static Stream<Arguments> setProfileInvalidRequestData() throws InvalidInputException{
|
||||
final byte[] commitment = new ProfileKey(new byte[32]).getCommitment(new ServiceId.Aci(AuthHelper.VALID_UUID_TWO)).serialize();
|
||||
final byte[] invalidValue = new byte[42];
|
||||
|
||||
final SetProfileRequest prototypeRequest = SetProfileRequest.newBuilder()
|
||||
.setVersion(VERSION)
|
||||
.setName(ByteString.copyFrom(VALID_NAME))
|
||||
.setCommitment(ByteString.copyFrom(commitment))
|
||||
.build();
|
||||
|
||||
return Stream.of(
|
||||
// Missing version
|
||||
Arguments.of(SetProfileRequest.newBuilder(prototypeRequest)
|
||||
.clearVersion()
|
||||
.build()),
|
||||
// Missing name
|
||||
Arguments.of(SetProfileRequest.newBuilder(prototypeRequest)
|
||||
.clearName()
|
||||
.build()),
|
||||
// Invalid name length
|
||||
Arguments.of(SetProfileRequest.newBuilder(prototypeRequest)
|
||||
.setName(ByteString.copyFrom(invalidValue))
|
||||
.build()),
|
||||
// Invalid about emoji length
|
||||
Arguments.of(SetProfileRequest.newBuilder(prototypeRequest)
|
||||
.setAboutEmoji(ByteString.copyFrom(invalidValue))
|
||||
.build()),
|
||||
// Invalid about length
|
||||
Arguments.of(SetProfileRequest.newBuilder(prototypeRequest)
|
||||
.setAbout(ByteString.copyFrom(invalidValue))
|
||||
.build()),
|
||||
// Invalid payment address
|
||||
Arguments.of(SetProfileRequest.newBuilder(prototypeRequest)
|
||||
.setPaymentAddress(ByteString.copyFrom(invalidValue))
|
||||
.build()),
|
||||
// Missing profile commitment
|
||||
Arguments.of(SetProfileRequest.newBuilder()
|
||||
.clearCommitment()
|
||||
.build())
|
||||
);
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(booleans = {true, false})
|
||||
void setPaymentAddressDisallowedCountry(boolean hasExistingPaymentAddress) throws InvalidInputException {
|
||||
final Phonenumber.PhoneNumber disallowedPhoneNumber = PhoneNumberUtil.getInstance().getExampleNumber("CU");
|
||||
final byte[] commitment = new ProfileKey(new byte[32]).getCommitment(new ServiceId.Aci(AUTHENTICATED_ACI)).serialize();
|
||||
|
||||
final byte[] validPaymentAddress = new byte[582];
|
||||
if (hasExistingPaymentAddress) {
|
||||
when(profile.paymentAddress()).thenReturn(validPaymentAddress);
|
||||
}
|
||||
|
||||
final SetProfileRequest request = SetProfileRequest.newBuilder()
|
||||
.setVersion(VERSION)
|
||||
.setName(ByteString.copyFrom(VALID_NAME))
|
||||
.setAvatarChange(AvatarChange.AVATAR_CHANGE_UNCHANGED)
|
||||
.setPaymentAddress(ByteString.copyFrom(validPaymentAddress))
|
||||
.setCommitment(ByteString.copyFrom(commitment))
|
||||
.build();
|
||||
final String disallowedCountryCode = String.format("+%d", disallowedPhoneNumber.getCountryCode());
|
||||
when(dynamicPaymentsConfiguration.getDisallowedPrefixes()).thenReturn(List.of(disallowedCountryCode));
|
||||
when(account.getNumber()).thenReturn(PhoneNumberUtil.getInstance().format(
|
||||
disallowedPhoneNumber,
|
||||
PhoneNumberUtil.PhoneNumberFormat.E164));
|
||||
when(profilesManager.getAsync(any(), anyString())).thenReturn(CompletableFuture.completedFuture(Optional.of(profile)));
|
||||
|
||||
if (hasExistingPaymentAddress) {
|
||||
assertDoesNotThrow(() -> profileBlockingStub.setProfile(request),
|
||||
"Payment address changes in disallowed countries should still be allowed if the account already has a valid payment address");
|
||||
} else {
|
||||
final StatusRuntimeException exception =
|
||||
assertThrows(StatusRuntimeException.class, () -> profileBlockingStub.setProfile(request));
|
||||
assertEquals(Status.PERMISSION_DENIED.getCode(), exception.getStatus().getCode());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void test() {
|
||||
record Person(String firstName, String lastName) {};
|
||||
|
||||
Person rob = new Person("rob", "l");
|
||||
Person mike = new Person("rob", "l");
|
||||
|
||||
assertEquals(rob, mike);
|
||||
}
|
||||
}
|
||||
@@ -5,8 +5,13 @@
|
||||
|
||||
package org.whispersystems.textsecuregcm.metrics;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
import io.micrometer.core.instrument.Meter;
|
||||
import io.micrometer.core.instrument.MeterRegistry;
|
||||
import io.micrometer.core.instrument.simple.SimpleMeterRegistry;
|
||||
import java.util.List;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
|
||||
@@ -19,4 +24,25 @@ class MetricsUtilTest {
|
||||
assertEquals("chat.MetricsUtilTest.namespace.metric",
|
||||
MetricsUtil.name(MetricsUtilTest.class, "namespace", "metric"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void lettuceRejection() {
|
||||
MeterRegistry registry = new SimpleMeterRegistry();
|
||||
MetricsUtil.configureMeterFilters(registry.config());
|
||||
|
||||
registry.counter("lettuce.command.completion.count").increment();
|
||||
registry.counter("lettuce.command.firstresponse.max").increment();
|
||||
registry.counter("lettuce.test").increment();
|
||||
assertThat(registry.getMeters()).isEmpty();
|
||||
|
||||
// this lettuce statistic is allow-listed
|
||||
registry.counter("lettuce.command.completion.max", "command", "hello", "remote", "world").increment();
|
||||
final List<Meter> meters = registry.getMeters();
|
||||
assertThat(meters).hasSize(1);
|
||||
|
||||
Meter meter = meters.get(0);
|
||||
assertThat(meter.getId().getName()).isEqualTo("chat.lettuce.command.completion.max");
|
||||
assertThat(meter.getId().getTag("command")).isNull();
|
||||
assertThat(meter.getId().getTag("remote")).isNotNull();
|
||||
}
|
||||
}
|
||||
@@ -92,86 +92,86 @@ class AccountTest {
|
||||
when(oldSecondaryDevice.getId()).thenReturn(2L);
|
||||
|
||||
when(senderKeyCapableDevice.getCapabilities()).thenReturn(
|
||||
new DeviceCapabilities(true, true, true, false, false, false, false, false, false));
|
||||
new DeviceCapabilities(true, true, false, false));
|
||||
when(senderKeyCapableDevice.isEnabled()).thenReturn(true);
|
||||
|
||||
when(senderKeyIncapableDevice.getCapabilities()).thenReturn(
|
||||
new DeviceCapabilities(true, true, false, false, false, false, false, false, false));
|
||||
new DeviceCapabilities(true, true, false, false));
|
||||
when(senderKeyIncapableDevice.isEnabled()).thenReturn(true);
|
||||
|
||||
when(senderKeyIncapableExpiredDevice.getCapabilities()).thenReturn(
|
||||
new DeviceCapabilities(true, true, false, false, false, false, false, false, false));
|
||||
new DeviceCapabilities(true, true, false, false));
|
||||
when(senderKeyIncapableExpiredDevice.isEnabled()).thenReturn(false);
|
||||
|
||||
when(announcementGroupCapableDevice.getCapabilities()).thenReturn(
|
||||
new DeviceCapabilities(true, true, true, true, false, false, false, false, false));
|
||||
new DeviceCapabilities(true, true, false, false));
|
||||
when(announcementGroupCapableDevice.isEnabled()).thenReturn(true);
|
||||
|
||||
when(announcementGroupIncapableDevice.getCapabilities()).thenReturn(
|
||||
new DeviceCapabilities(true, true, true, false, false, false, false, false, false));
|
||||
new DeviceCapabilities(true, true, false, false));
|
||||
when(announcementGroupIncapableDevice.isEnabled()).thenReturn(true);
|
||||
|
||||
when(announcementGroupIncapableExpiredDevice.getCapabilities()).thenReturn(
|
||||
new DeviceCapabilities(true, true, true, false, false, false, false, false, false));
|
||||
new DeviceCapabilities(true, true, false, false));
|
||||
when(announcementGroupIncapableExpiredDevice.isEnabled()).thenReturn(false);
|
||||
|
||||
when(changeNumberCapableDevice.getCapabilities()).thenReturn(
|
||||
new DeviceCapabilities(true, true, true, false, true, false, false, false, false));
|
||||
new DeviceCapabilities(true, true, false, false));
|
||||
when(changeNumberCapableDevice.isEnabled()).thenReturn(true);
|
||||
|
||||
when(changeNumberIncapableDevice.getCapabilities()).thenReturn(
|
||||
new DeviceCapabilities(true, true, true, false, false, false, false, false, false));
|
||||
new DeviceCapabilities(true, true, false, false));
|
||||
when(changeNumberIncapableDevice.isEnabled()).thenReturn(true);
|
||||
|
||||
when(changeNumberIncapableExpiredDevice.getCapabilities()).thenReturn(
|
||||
new DeviceCapabilities(true, true, true, false, false, false, false, false, false));
|
||||
new DeviceCapabilities(true, true, false, false));
|
||||
when(changeNumberIncapableExpiredDevice.isEnabled()).thenReturn(false);
|
||||
|
||||
when(pniCapableDevice.getCapabilities()).thenReturn(
|
||||
new DeviceCapabilities(true, true, true, false, false, true, false, false, false));
|
||||
new DeviceCapabilities(true, true, true, false));
|
||||
when(pniCapableDevice.isEnabled()).thenReturn(true);
|
||||
|
||||
when(pniIncapableDevice.getCapabilities()).thenReturn(
|
||||
new DeviceCapabilities(true, true, true, false, false, false, false, false, false));
|
||||
new DeviceCapabilities(true, true, false, false));
|
||||
when(pniIncapableDevice.isEnabled()).thenReturn(true);
|
||||
|
||||
when(pniIncapableExpiredDevice.getCapabilities()).thenReturn(
|
||||
new DeviceCapabilities(true, true, true, false, false, false, false, false, false));
|
||||
new DeviceCapabilities(true, true, false, false));
|
||||
when(pniIncapableExpiredDevice.isEnabled()).thenReturn(false);
|
||||
|
||||
when(storiesCapableDevice.getId()).thenReturn(1L);
|
||||
when(storiesCapableDevice.getCapabilities()).thenReturn(
|
||||
new DeviceCapabilities(true, true, true, false, false, false, true, false, false));
|
||||
new DeviceCapabilities(true, true, false, false));
|
||||
when(storiesCapableDevice.isEnabled()).thenReturn(true);
|
||||
|
||||
when(storiesCapableDevice.getId()).thenReturn(2L);
|
||||
when(storiesIncapableDevice.getCapabilities()).thenReturn(
|
||||
new DeviceCapabilities(true, true, true, false, false, false, false, false, false));
|
||||
new DeviceCapabilities(true, true, false, false));
|
||||
when(storiesIncapableDevice.isEnabled()).thenReturn(true);
|
||||
|
||||
when(storiesCapableDevice.getId()).thenReturn(3L);
|
||||
when(storiesIncapableExpiredDevice.getCapabilities()).thenReturn(
|
||||
new DeviceCapabilities(true, true, true, false, false, false, false, false, false));
|
||||
new DeviceCapabilities(true, true, false, false));
|
||||
when(storiesIncapableExpiredDevice.isEnabled()).thenReturn(false);
|
||||
|
||||
when(giftBadgesCapableDevice.getCapabilities()).thenReturn(
|
||||
new DeviceCapabilities(true, true, true, true, true, true, true, true, false));
|
||||
new DeviceCapabilities(true, true, true, false));
|
||||
when(giftBadgesCapableDevice.isEnabled()).thenReturn(true);
|
||||
when(giftBadgesIncapableDevice.getCapabilities()).thenReturn(
|
||||
new DeviceCapabilities(true, true, true, true, true, true, true, false, false));
|
||||
new DeviceCapabilities(true, true, true, false));
|
||||
when(giftBadgesIncapableDevice.isEnabled()).thenReturn(true);
|
||||
when(giftBadgesIncapableExpiredDevice.getCapabilities()).thenReturn(
|
||||
new DeviceCapabilities(true, true, true, true, true, true, true, false, false));
|
||||
new DeviceCapabilities(true, true, true, false));
|
||||
when(giftBadgesIncapableExpiredDevice.isEnabled()).thenReturn(false);
|
||||
|
||||
when(paymentActivationCapableDevice.getCapabilities()).thenReturn(
|
||||
new DeviceCapabilities(true, true, true, true, true, true, true, true, true));
|
||||
new DeviceCapabilities(true, true, true, true));
|
||||
when(paymentActivationCapableDevice.isEnabled()).thenReturn(true);
|
||||
when(paymentActivationIncapableDevice.getCapabilities()).thenReturn(
|
||||
new DeviceCapabilities(true, true, true, true, true, true, true, false, false));
|
||||
new DeviceCapabilities(true, true, true, false));
|
||||
when(paymentActivationIncapableDevice.isEnabled()).thenReturn(true);
|
||||
when(paymentActivationIncapableExpiredDevice.getCapabilities()).thenReturn(
|
||||
new DeviceCapabilities(true, true, true, true, true, true, true, false, false));
|
||||
new DeviceCapabilities(true, true, true, false));
|
||||
when(paymentActivationIncapableExpiredDevice.isEnabled()).thenReturn(false);
|
||||
|
||||
}
|
||||
@@ -222,8 +222,8 @@ class AccountTest {
|
||||
when(transferCapableLinkedDevice.isMaster()).thenReturn(false);
|
||||
when(transferCapableLinkedDevice.getCapabilities()).thenReturn(transferCapabilities);
|
||||
|
||||
when(transferCapabilities.isTransfer()).thenReturn(true);
|
||||
when(nonTransferCapabilities.isTransfer()).thenReturn(false);
|
||||
when(transferCapabilities.transfer()).thenReturn(true);
|
||||
when(nonTransferCapabilities.transfer()).thenReturn(false);
|
||||
|
||||
{
|
||||
final Account transferableMasterAccount =
|
||||
@@ -261,44 +261,6 @@ class AccountTest {
|
||||
assertTrue(account.isDiscoverableByPhoneNumber());
|
||||
}
|
||||
|
||||
@Test
|
||||
void isSenderKeySupported() {
|
||||
assertThat(AccountsHelper.generateTestAccount("+18005551234", UUID.randomUUID(), UUID.randomUUID(), List.of(senderKeyCapableDevice),
|
||||
"1234".getBytes(StandardCharsets.UTF_8)).isSenderKeySupported()).isTrue();
|
||||
assertThat(AccountsHelper.generateTestAccount("+18005551234", UUID.randomUUID(), UUID.randomUUID(),
|
||||
List.of(senderKeyCapableDevice, senderKeyIncapableDevice),
|
||||
"1234".getBytes(StandardCharsets.UTF_8)).isSenderKeySupported()).isFalse();
|
||||
assertThat(AccountsHelper.generateTestAccount("+18005551234", UUID.randomUUID(),
|
||||
UUID.randomUUID(), List.of(senderKeyCapableDevice, senderKeyIncapableExpiredDevice),
|
||||
"1234".getBytes(StandardCharsets.UTF_8)).isSenderKeySupported()).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
void isAnnouncementGroupSupported() {
|
||||
assertThat(AccountsHelper.generateTestAccount("+18005551234", UUID.randomUUID(),
|
||||
UUID.randomUUID(), List.of(announcementGroupCapableDevice),
|
||||
"1234".getBytes(StandardCharsets.UTF_8)).isAnnouncementGroupSupported()).isTrue();
|
||||
assertThat(AccountsHelper.generateTestAccount("+18005551234", UUID.randomUUID(),
|
||||
UUID.randomUUID(), List.of(announcementGroupCapableDevice, announcementGroupIncapableDevice),
|
||||
"1234".getBytes(StandardCharsets.UTF_8)).isAnnouncementGroupSupported()).isFalse();
|
||||
assertThat(AccountsHelper.generateTestAccount("+18005551234", UUID.randomUUID(),
|
||||
UUID.randomUUID(), List.of(announcementGroupCapableDevice, announcementGroupIncapableExpiredDevice),
|
||||
"1234".getBytes(StandardCharsets.UTF_8)).isAnnouncementGroupSupported()).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
void isChangeNumberSupported() {
|
||||
assertThat(AccountsHelper.generateTestAccount("+18005551234", UUID.randomUUID(),
|
||||
UUID.randomUUID(), List.of(changeNumberCapableDevice),
|
||||
"1234".getBytes(StandardCharsets.UTF_8)).isChangeNumberSupported()).isTrue();
|
||||
assertThat(AccountsHelper.generateTestAccount("+18005551234", UUID.randomUUID(),
|
||||
UUID.randomUUID(), List.of(changeNumberCapableDevice, changeNumberIncapableDevice),
|
||||
"1234".getBytes(StandardCharsets.UTF_8)).isChangeNumberSupported()).isFalse();
|
||||
assertThat(AccountsHelper.generateTestAccount("+18005551234", UUID.randomUUID(),
|
||||
UUID.randomUUID(), List.of(changeNumberCapableDevice, changeNumberIncapableExpiredDevice),
|
||||
"1234".getBytes(StandardCharsets.UTF_8)).isChangeNumberSupported()).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
void isPniSupported() {
|
||||
assertThat(AccountsHelper.generateTestAccount("+18005551234", UUID.randomUUID(),
|
||||
@@ -312,32 +274,6 @@ class AccountTest {
|
||||
"1234".getBytes(StandardCharsets.UTF_8)).isPniSupported()).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
void isStoriesSupported() {
|
||||
assertThat(AccountsHelper.generateTestAccount("+18005551234", UUID.randomUUID(),
|
||||
UUID.randomUUID(), List.of(storiesCapableDevice),
|
||||
"1234".getBytes(StandardCharsets.UTF_8)).isStoriesSupported()).isTrue();
|
||||
assertThat(AccountsHelper.generateTestAccount("+18005551234", UUID.randomUUID(),
|
||||
UUID.randomUUID(), List.of(storiesCapableDevice, storiesIncapableDevice),
|
||||
"1234".getBytes(StandardCharsets.UTF_8)).isStoriesSupported()).isFalse();
|
||||
assertThat(AccountsHelper.generateTestAccount("+18005551234", UUID.randomUUID(),
|
||||
UUID.randomUUID(), List.of(storiesCapableDevice, storiesIncapableExpiredDevice),
|
||||
"1234".getBytes(StandardCharsets.UTF_8)).isStoriesSupported()).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
void isGiftBadgesSupported() {
|
||||
assertThat(AccountsHelper.generateTestAccount("+18005551234", UUID.randomUUID(), UUID.randomUUID(),
|
||||
List.of(giftBadgesCapableDevice),
|
||||
"1234".getBytes(StandardCharsets.UTF_8)).isGiftBadgesSupported()).isTrue();
|
||||
assertThat(AccountsHelper.generateTestAccount("+18005551234", UUID.randomUUID(), UUID.randomUUID(),
|
||||
List.of(giftBadgesCapableDevice, giftBadgesIncapableDevice),
|
||||
"1234".getBytes(StandardCharsets.UTF_8)).isGiftBadgesSupported()).isFalse();
|
||||
assertThat(AccountsHelper.generateTestAccount("+18005551234", UUID.randomUUID(), UUID.randomUUID(),
|
||||
List.of(giftBadgesCapableDevice, giftBadgesIncapableExpiredDevice),
|
||||
"1234".getBytes(StandardCharsets.UTF_8)).isGiftBadgesSupported()).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
void isPaymentActivationSupported() {
|
||||
assertThat(AccountsHelper.generateTestAccount("+18005551234", UUID.randomUUID(), UUID.randomUUID(),
|
||||
|
||||
+5
-2
@@ -103,6 +103,9 @@ class AccountsManagerChangeNumberIntegrationTest {
|
||||
final KeysManager keysManager = mock(KeysManager.class);
|
||||
when(keysManager.delete(any())).thenReturn(CompletableFuture.completedFuture(null));
|
||||
|
||||
final MessagesManager messagesManager = mock(MessagesManager.class);
|
||||
when(messagesManager.clear(any())).thenReturn(CompletableFuture.completedFuture(null));
|
||||
|
||||
accountsManager = new AccountsManager(
|
||||
accounts,
|
||||
phoneNumberIdentifiers,
|
||||
@@ -110,7 +113,7 @@ class AccountsManagerChangeNumberIntegrationTest {
|
||||
accountLockManager,
|
||||
deletedAccounts,
|
||||
keysManager,
|
||||
mock(MessagesManager.class),
|
||||
messagesManager,
|
||||
mock(ProfilesManager.class),
|
||||
secureStorageClient,
|
||||
secureBackupClient,
|
||||
@@ -153,7 +156,7 @@ class AccountsManagerChangeNumberIntegrationTest {
|
||||
final ECKeyPair pniIdentityKeyPair = Curve.generateKeyPair();
|
||||
final ECSignedPreKey rotatedSignedPreKey = KeysHelper.signedECPreKey(1L, pniIdentityKeyPair);
|
||||
|
||||
final AccountAttributes accountAttributes = new AccountAttributes(true, rotatedPniRegistrationId + 1, "test", null, true, new Device.DeviceCapabilities());
|
||||
final AccountAttributes accountAttributes = new AccountAttributes(true, rotatedPniRegistrationId + 1, "test", null, true, new Device.DeviceCapabilities(false, false, false, false));
|
||||
final Account account = accountsManager.create(originalNumber, "password", null, accountAttributes, new ArrayList<>());
|
||||
account.getMasterDevice().orElseThrow().setSignedPreKey(KeysHelper.signedECPreKey(1, pniIdentityKeyPair));
|
||||
|
||||
|
||||
+2
-1
@@ -188,6 +188,7 @@ class AccountsManagerTest {
|
||||
}).when(accountLockManager).withLock(any(), any());
|
||||
|
||||
when(keysManager.delete(any())).thenReturn(CompletableFuture.completedFuture(null));
|
||||
when(messagesManager.clear(any())).thenReturn(CompletableFuture.completedFuture(null));
|
||||
|
||||
accountsManager = new AccountsManager(
|
||||
accounts,
|
||||
@@ -976,7 +977,7 @@ class AccountsManagerTest {
|
||||
@ValueSource(booleans = {true, false})
|
||||
void testCreateWithStorageCapability(final boolean hasStorage) throws InterruptedException {
|
||||
final AccountAttributes attributes = new AccountAttributes(false, 0, null, null, true,
|
||||
new DeviceCapabilities(hasStorage, false, false, false, false, false, false, false, false));
|
||||
new DeviceCapabilities(hasStorage, false, false, false));
|
||||
|
||||
final Account account = accountsManager.create("+18005550123", "password", null, attributes, new ArrayList<>());
|
||||
|
||||
|
||||
+2
-8
@@ -320,7 +320,7 @@ class MessagesCacheTest {
|
||||
}
|
||||
}
|
||||
|
||||
messagesCache.clear(DESTINATION_UUID, DESTINATION_DEVICE_ID);
|
||||
messagesCache.clear(DESTINATION_UUID, DESTINATION_DEVICE_ID).join();
|
||||
|
||||
assertEquals(Collections.emptyList(), get(DESTINATION_UUID, DESTINATION_DEVICE_ID, messageCount));
|
||||
assertEquals(messageCount, get(DESTINATION_UUID, DESTINATION_DEVICE_ID + 1, messageCount).size());
|
||||
@@ -340,18 +340,12 @@ class MessagesCacheTest {
|
||||
}
|
||||
}
|
||||
|
||||
messagesCache.clear(DESTINATION_UUID);
|
||||
messagesCache.clear(DESTINATION_UUID).join();
|
||||
|
||||
assertEquals(Collections.emptyList(), get(DESTINATION_UUID, DESTINATION_DEVICE_ID, messageCount));
|
||||
assertEquals(Collections.emptyList(), get(DESTINATION_UUID, DESTINATION_DEVICE_ID + 1, messageCount));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testClearNullUuid() {
|
||||
// We're happy as long as this doesn't throw an exception
|
||||
messagesCache.clear(null);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetAccountFromQueueName() {
|
||||
assertEquals(DESTINATION_UUID,
|
||||
|
||||
+2
-2
@@ -194,7 +194,7 @@ class MessagesDynamoDbTest {
|
||||
assertThat(load(secondDestinationUuid, 1, MessagesDynamoDb.RESULT_SET_CHUNK_SIZE)).isNotNull()
|
||||
.hasSize(1).element(0).isEqualTo(MESSAGE2);
|
||||
|
||||
messagesDynamoDb.deleteAllMessagesForAccount(destinationUuid);
|
||||
messagesDynamoDb.deleteAllMessagesForAccount(destinationUuid).join();
|
||||
|
||||
assertThat(load(destinationUuid, 1, MessagesDynamoDb.RESULT_SET_CHUNK_SIZE)).isNotNull().isEmpty();
|
||||
assertThat(load(destinationUuid, 2, MessagesDynamoDb.RESULT_SET_CHUNK_SIZE)).isNotNull().isEmpty();
|
||||
@@ -217,7 +217,7 @@ class MessagesDynamoDbTest {
|
||||
assertThat(load(secondDestinationUuid, 1, MessagesDynamoDb.RESULT_SET_CHUNK_SIZE)).isNotNull()
|
||||
.hasSize(1).element(0).isEqualTo(MESSAGE2);
|
||||
|
||||
messagesDynamoDb.deleteAllMessagesForDevice(destinationUuid, 2);
|
||||
messagesDynamoDb.deleteAllMessagesForDevice(destinationUuid, 2).join();
|
||||
|
||||
assertThat(load(destinationUuid, 1, MessagesDynamoDb.RESULT_SET_CHUNK_SIZE)).isNotNull().hasSize(1)
|
||||
.element(0).isEqualTo(MESSAGE1);
|
||||
|
||||
+44
-27
@@ -5,7 +5,7 @@
|
||||
|
||||
package org.whispersystems.textsecuregcm.storage;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertSame;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
@@ -21,15 +21,18 @@ import static org.mockito.Mockito.when;
|
||||
import io.lettuce.core.RedisException;
|
||||
import io.lettuce.core.cluster.api.async.RedisAdvancedClusterAsyncCommands;
|
||||
import io.lettuce.core.cluster.api.sync.RedisAdvancedClusterCommands;
|
||||
import java.util.Base64;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.Timeout;
|
||||
import org.signal.libsignal.protocol.ServiceId;
|
||||
import org.signal.libsignal.zkgroup.InvalidInputException;
|
||||
import org.signal.libsignal.zkgroup.profiles.ProfileKey;
|
||||
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisCluster;
|
||||
import org.whispersystems.textsecuregcm.tests.util.MockRedisFuture;
|
||||
import org.whispersystems.textsecuregcm.tests.util.ProfileHelper;
|
||||
import org.whispersystems.textsecuregcm.tests.util.RedisClusterHelper;
|
||||
|
||||
@Timeout(value = 10, threadMode = Timeout.ThreadMode.SEPARATE_THREAD)
|
||||
@@ -57,17 +60,21 @@ public class ProfilesManagerTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGetProfileInCache() {
|
||||
UUID uuid = UUID.randomUUID();
|
||||
|
||||
when(commands.hget(eq("profiles::" + uuid), eq("someversion"))).thenReturn("{\"version\": \"someversion\", \"name\": \"somename\", \"avatar\": \"someavatar\", \"commitment\":\"" + Base64.getEncoder().encodeToString("somecommitment".getBytes()) + "\"}");
|
||||
public void testGetProfileInCache() throws InvalidInputException {
|
||||
final UUID uuid = UUID.randomUUID();
|
||||
final byte[] name = ProfileHelper.generateRandomByteArray(81);
|
||||
final byte[] commitment = new ProfileKey(new byte[32]).getCommitment(new ServiceId.Aci(uuid)).serialize();
|
||||
when(commands.hget(eq("profiles::" + uuid), eq("someversion"))).thenReturn(String.format(
|
||||
"{\"version\": \"someversion\", \"name\": \"%s\", \"avatar\": \"someavatar\", \"commitment\":\"%s\"}",
|
||||
ProfileHelper.encodeToBase64(name),
|
||||
ProfileHelper.encodeToBase64(commitment)));
|
||||
|
||||
Optional<VersionedProfile> profile = profilesManager.get(uuid, "someversion");
|
||||
|
||||
assertTrue(profile.isPresent());
|
||||
assertEquals(profile.get().getName(), "somename");
|
||||
assertEquals(profile.get().getAvatar(), "someavatar");
|
||||
assertThat(profile.get().getCommitment()).isEqualTo("somecommitment".getBytes());
|
||||
assertArrayEquals(profile.get().name(), name);
|
||||
assertEquals(profile.get().avatar(), "someavatar");
|
||||
assertArrayEquals(profile.get().commitment(), commitment);
|
||||
|
||||
verify(commands, times(1)).hget(eq("profiles::" + uuid), eq("someversion"));
|
||||
verifyNoMoreInteractions(commands);
|
||||
@@ -75,18 +82,22 @@ public class ProfilesManagerTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGetProfileAsyncInCache() {
|
||||
UUID uuid = UUID.randomUUID();
|
||||
public void testGetProfileAsyncInCache() throws InvalidInputException {
|
||||
final UUID uuid = UUID.randomUUID();
|
||||
final byte[] name = ProfileHelper.generateRandomByteArray(81);
|
||||
final byte[] commitment = new ProfileKey(new byte[32]).getCommitment(new ServiceId.Aci(uuid)).serialize();
|
||||
|
||||
when(asyncCommands.hget(eq("profiles::" + uuid), eq("someversion"))).thenReturn(
|
||||
MockRedisFuture.completedFuture("{\"version\": \"someversion\", \"name\": \"somename\", \"avatar\": \"someavatar\", \"commitment\":\"" + Base64.getEncoder().encodeToString("somecommitment".getBytes()) + "\"}"));
|
||||
MockRedisFuture.completedFuture(String.format("{\"version\": \"someversion\", \"name\": \"%s\", \"avatar\": \"someavatar\", \"commitment\":\"%s\"}",
|
||||
ProfileHelper.encodeToBase64(name),
|
||||
ProfileHelper.encodeToBase64(commitment))));
|
||||
|
||||
Optional<VersionedProfile> profile = profilesManager.getAsync(uuid, "someversion").join();
|
||||
|
||||
assertTrue(profile.isPresent());
|
||||
assertEquals(profile.get().getName(), "somename");
|
||||
assertEquals(profile.get().getAvatar(), "someavatar");
|
||||
assertThat(profile.get().getCommitment()).isEqualTo("somecommitment".getBytes());
|
||||
assertArrayEquals(profile.get().name(), name);
|
||||
assertEquals(profile.get().avatar(), "someavatar");
|
||||
assertArrayEquals(profile.get().commitment(), commitment);
|
||||
|
||||
verify(asyncCommands, times(1)).hget(eq("profiles::" + uuid), eq("someversion"));
|
||||
verifyNoMoreInteractions(asyncCommands);
|
||||
@@ -95,8 +106,9 @@ public class ProfilesManagerTest {
|
||||
|
||||
@Test
|
||||
public void testGetProfileNotInCache() {
|
||||
UUID uuid = UUID.randomUUID();
|
||||
VersionedProfile profile = new VersionedProfile("someversion", "somename", "someavatar", null, null,
|
||||
final UUID uuid = UUID.randomUUID();
|
||||
final byte[] name = ProfileHelper.generateRandomByteArray(81);
|
||||
final VersionedProfile profile = new VersionedProfile("someversion", name, "someavatar", null, null,
|
||||
null, "somecommitment".getBytes());
|
||||
|
||||
when(commands.hget(eq("profiles::" + uuid), eq("someversion"))).thenReturn(null);
|
||||
@@ -117,8 +129,9 @@ public class ProfilesManagerTest {
|
||||
|
||||
@Test
|
||||
public void testGetProfileAsyncNotInCache() {
|
||||
UUID uuid = UUID.randomUUID();
|
||||
VersionedProfile profile = new VersionedProfile("someversion", "somename", "someavatar", null, null,
|
||||
final UUID uuid = UUID.randomUUID();
|
||||
final byte[] name = ProfileHelper.generateRandomByteArray(81);
|
||||
final VersionedProfile profile = new VersionedProfile("someversion", name, "someavatar", null, null,
|
||||
null, "somecommitment".getBytes());
|
||||
|
||||
when(asyncCommands.hget(eq("profiles::" + uuid), eq("someversion"))).thenReturn(MockRedisFuture.completedFuture(null));
|
||||
@@ -140,8 +153,9 @@ public class ProfilesManagerTest {
|
||||
|
||||
@Test
|
||||
public void testGetProfileBrokenCache() {
|
||||
UUID uuid = UUID.randomUUID();
|
||||
VersionedProfile profile = new VersionedProfile("someversion", "somename", "someavatar", null, null,
|
||||
final UUID uuid = UUID.randomUUID();
|
||||
final byte[] name = ProfileHelper.generateRandomByteArray(81);
|
||||
final VersionedProfile profile = new VersionedProfile("someversion", name, "someavatar", null, null,
|
||||
null, "somecommitment".getBytes());
|
||||
|
||||
when(commands.hget(eq("profiles::" + uuid), eq("someversion"))).thenThrow(new RedisException("Connection lost"));
|
||||
@@ -162,8 +176,9 @@ public class ProfilesManagerTest {
|
||||
|
||||
@Test
|
||||
public void testGetProfileAsyncBrokenCache() {
|
||||
UUID uuid = UUID.randomUUID();
|
||||
VersionedProfile profile = new VersionedProfile("someversion", "somename", "someavatar", null, null,
|
||||
final UUID uuid = UUID.randomUUID();
|
||||
final byte[] name = ProfileHelper.generateRandomByteArray(81);
|
||||
final VersionedProfile profile = new VersionedProfile("someversion", name, "someavatar", null, null,
|
||||
null, "somecommitment".getBytes());
|
||||
|
||||
when(asyncCommands.hget(eq("profiles::" + uuid), eq("someversion"))).thenReturn(MockRedisFuture.failedFuture(new RedisException("Connection lost")));
|
||||
@@ -185,8 +200,9 @@ public class ProfilesManagerTest {
|
||||
|
||||
@Test
|
||||
public void testSet() {
|
||||
UUID uuid = UUID.randomUUID();
|
||||
VersionedProfile profile = new VersionedProfile("someversion", "somename", "someavatar", null, null,
|
||||
final UUID uuid = UUID.randomUUID();
|
||||
final byte[] name = ProfileHelper.generateRandomByteArray(81);
|
||||
final VersionedProfile profile = new VersionedProfile("someversion", name, "someavatar", null, null,
|
||||
null, "somecommitment".getBytes());
|
||||
|
||||
profilesManager.set(uuid, profile);
|
||||
@@ -200,8 +216,9 @@ public class ProfilesManagerTest {
|
||||
|
||||
@Test
|
||||
public void testSetAsync() {
|
||||
UUID uuid = UUID.randomUUID();
|
||||
VersionedProfile profile = new VersionedProfile("someversion", "somename", "someavatar", null, null,
|
||||
final UUID uuid = UUID.randomUUID();
|
||||
final byte[] name = ProfileHelper.generateRandomByteArray(81);
|
||||
final VersionedProfile profile = new VersionedProfile("someversion", name, "someavatar", null, null,
|
||||
null, "somecommitment".getBytes());
|
||||
|
||||
when(asyncCommands.hset(eq("profiles::" + uuid), eq("someversion"), anyString())).thenReturn(MockRedisFuture.completedFuture(null));
|
||||
|
||||
+190
-138
@@ -12,6 +12,10 @@ import org.junit.jupiter.api.extension.RegisterExtension;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.Arguments;
|
||||
import org.junit.jupiter.params.provider.MethodSource;
|
||||
import org.signal.libsignal.protocol.ServiceId;
|
||||
import org.signal.libsignal.zkgroup.InvalidInputException;
|
||||
import org.signal.libsignal.zkgroup.profiles.ProfileKey;
|
||||
import org.whispersystems.textsecuregcm.tests.util.ProfileHelper;
|
||||
import org.whispersystems.textsecuregcm.util.AttributeValues;
|
||||
import org.whispersystems.textsecuregcm.storage.DynamoDbExtensionSchema.Tables;
|
||||
import software.amazon.awssdk.services.dynamodb.model.AttributeValue;
|
||||
@@ -19,7 +23,6 @@ import software.amazon.awssdk.services.dynamodb.model.AttributeValue;
|
||||
import static org.assertj.core.api.AssertionsForClassTypes.assertThat;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
@@ -27,188 +30,225 @@ import java.util.stream.Stream;
|
||||
|
||||
@Timeout(value = 10, threadMode = Timeout.ThreadMode.SEPARATE_THREAD)
|
||||
public class ProfilesTest {
|
||||
|
||||
private static final UUID ACI = UUID.randomUUID();
|
||||
@RegisterExtension
|
||||
static final DynamoDbExtension DYNAMO_DB_EXTENSION = new DynamoDbExtension(Tables.PROFILES);
|
||||
|
||||
private Profiles profiles;
|
||||
private VersionedProfile validProfile;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
void setUp() throws InvalidInputException {
|
||||
profiles = new Profiles(DYNAMO_DB_EXTENSION.getDynamoDbClient(),
|
||||
DYNAMO_DB_EXTENSION.getDynamoDbAsyncClient(),
|
||||
Tables.PROFILES.tableName());
|
||||
final byte[] commitment = new ProfileKey(new byte[32]).getCommitment(new ServiceId.Aci(ACI)).serialize();
|
||||
final String version = "someVersion";
|
||||
final byte[] name = ProfileHelper.generateRandomByteArray(81);
|
||||
final byte[] validAboutEmoji = ProfileHelper.generateRandomByteArray(60);
|
||||
final byte[] validAbout = ProfileHelper.generateRandomByteArray(156);
|
||||
final String avatar = "profiles/" + ProfileHelper.generateRandomBase64FromByteArray(16);
|
||||
|
||||
validProfile = new VersionedProfile(version, name, avatar, validAboutEmoji, validAbout, null, commitment);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testSetGet() {
|
||||
UUID uuid = UUID.randomUUID();
|
||||
VersionedProfile profile = new VersionedProfile("123", "foo", "avatarLocation", "emoji",
|
||||
"the very model of a modern major general",
|
||||
null, "acommitment".getBytes());
|
||||
profiles.set(uuid, profile);
|
||||
profiles.set(ACI, validProfile);
|
||||
|
||||
Optional<VersionedProfile> retrieved = profiles.get(uuid, "123");
|
||||
Optional<VersionedProfile> retrieved = profiles.get(ACI, validProfile.version());
|
||||
|
||||
assertThat(retrieved.isPresent()).isTrue();
|
||||
assertThat(retrieved.get().getName()).isEqualTo(profile.getName());
|
||||
assertThat(retrieved.get().getAvatar()).isEqualTo(profile.getAvatar());
|
||||
assertThat(retrieved.get().getCommitment()).isEqualTo(profile.getCommitment());
|
||||
assertThat(retrieved.get().getAbout()).isEqualTo(profile.getAbout());
|
||||
assertThat(retrieved.get().getAboutEmoji()).isEqualTo(profile.getAboutEmoji());
|
||||
assertThat(retrieved.get().name()).isEqualTo(validProfile.name());
|
||||
assertThat(retrieved.get().avatar()).isEqualTo(validProfile.avatar());
|
||||
assertThat(retrieved.get().commitment()).isEqualTo(validProfile.commitment());
|
||||
assertThat(retrieved.get().about()).isEqualTo(validProfile.about());
|
||||
assertThat(retrieved.get().aboutEmoji()).isEqualTo(validProfile.aboutEmoji());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testSetGetAsync() {
|
||||
UUID uuid = UUID.randomUUID();
|
||||
VersionedProfile profile = new VersionedProfile("123", "foo", "avatarLocation", "emoji",
|
||||
"the very model of a modern major general",
|
||||
null, "acommitment".getBytes());
|
||||
profiles.setAsync(uuid, profile).join();
|
||||
profiles.setAsync(ACI, validProfile).join();
|
||||
|
||||
Optional<VersionedProfile> retrieved = profiles.getAsync(uuid, "123").join();
|
||||
Optional<VersionedProfile> retrieved = profiles.getAsync(ACI, validProfile.version()).join();
|
||||
|
||||
assertThat(retrieved.isPresent()).isTrue();
|
||||
assertThat(retrieved.get().getName()).isEqualTo(profile.getName());
|
||||
assertThat(retrieved.get().getAvatar()).isEqualTo(profile.getAvatar());
|
||||
assertThat(retrieved.get().getCommitment()).isEqualTo(profile.getCommitment());
|
||||
assertThat(retrieved.get().getAbout()).isEqualTo(profile.getAbout());
|
||||
assertThat(retrieved.get().getAboutEmoji()).isEqualTo(profile.getAboutEmoji());
|
||||
assertThat(retrieved.get().name()).isEqualTo(validProfile.name());
|
||||
assertThat(retrieved.get().avatar()).isEqualTo(validProfile.avatar());
|
||||
assertThat(retrieved.get().commitment()).isEqualTo(validProfile.commitment());
|
||||
assertThat(retrieved.get().about()).isEqualTo(validProfile.about());
|
||||
assertThat(retrieved.get().aboutEmoji()).isEqualTo(validProfile.aboutEmoji());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testDeleteReset() {
|
||||
UUID uuid = UUID.randomUUID();
|
||||
profiles.set(uuid, new VersionedProfile("123", "foo", "avatarLocation", "emoji",
|
||||
"the very model of a modern major general",
|
||||
null, "acommitment".getBytes()));
|
||||
void testDeleteReset() throws InvalidInputException {
|
||||
profiles.set(ACI, validProfile);
|
||||
|
||||
profiles.deleteAll(uuid);
|
||||
profiles.deleteAll(ACI);
|
||||
|
||||
VersionedProfile updatedProfile = new VersionedProfile("123", "name", "differentAvatarLocation",
|
||||
"differentEmoji", "changed text", "paymentAddress", "differentcommitment".getBytes(StandardCharsets.UTF_8));
|
||||
final String version = "someVersion";
|
||||
final byte[] name = ProfileHelper.generateRandomByteArray(81);
|
||||
final String differentAvatar = "profiles/" + ProfileHelper.generateRandomBase64FromByteArray(16);
|
||||
final byte[] differentEmoji = ProfileHelper.generateRandomByteArray(60);
|
||||
final byte[] differentAbout = ProfileHelper.generateRandomByteArray(156);
|
||||
final byte[] paymentAddress = ProfileHelper.generateRandomByteArray(582);
|
||||
final byte[] commitment = new ProfileKey(ProfileHelper.generateRandomByteArray(32)).getCommitment(new ServiceId.Aci(ACI)).serialize();
|
||||
|
||||
profiles.set(uuid, updatedProfile);
|
||||
VersionedProfile updatedProfile = new VersionedProfile(version, name, differentAvatar,
|
||||
differentEmoji, differentAbout, paymentAddress, commitment);
|
||||
|
||||
Optional<VersionedProfile> retrieved = profiles.get(uuid, "123");
|
||||
profiles.set(ACI, updatedProfile);
|
||||
|
||||
Optional<VersionedProfile> retrieved = profiles.get(ACI, version);
|
||||
|
||||
assertThat(retrieved.isPresent()).isTrue();
|
||||
assertThat(retrieved.get().getName()).isEqualTo(updatedProfile.getName());
|
||||
assertThat(retrieved.get().getAvatar()).isEqualTo(updatedProfile.getAvatar());
|
||||
assertThat(retrieved.get().getCommitment()).isEqualTo(updatedProfile.getCommitment());
|
||||
assertThat(retrieved.get().getAbout()).isEqualTo(updatedProfile.getAbout());
|
||||
assertThat(retrieved.get().getAboutEmoji()).isEqualTo(updatedProfile.getAboutEmoji());
|
||||
assertThat(retrieved.get().name()).isEqualTo(updatedProfile.name());
|
||||
assertThat(retrieved.get().avatar()).isEqualTo(updatedProfile.avatar());
|
||||
assertThat(retrieved.get().commitment()).isEqualTo(updatedProfile.commitment());
|
||||
assertThat(retrieved.get().about()).isEqualTo(updatedProfile.about());
|
||||
assertThat(retrieved.get().aboutEmoji()).isEqualTo(updatedProfile.aboutEmoji());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testSetGetNullOptionalFields() {
|
||||
UUID uuid = UUID.randomUUID();
|
||||
VersionedProfile profile = new VersionedProfile("123", "foo", null, null, null, null,
|
||||
"acommitment".getBytes());
|
||||
profiles.set(uuid, profile);
|
||||
void testSetGetNullOptionalFields() throws InvalidInputException {
|
||||
final String version = "someVersion";
|
||||
final byte[] name = ProfileHelper.generateRandomByteArray(81);
|
||||
final byte[] commitment = new ProfileKey(ProfileHelper.generateRandomByteArray(32)).getCommitment(new ServiceId.Aci(ACI)).serialize();
|
||||
|
||||
Optional<VersionedProfile> retrieved = profiles.get(uuid, "123");
|
||||
VersionedProfile profile = new VersionedProfile(version, name, null, null, null, null,
|
||||
commitment);
|
||||
profiles.set(ACI, profile);
|
||||
|
||||
Optional<VersionedProfile> retrieved = profiles.get(ACI, version);
|
||||
|
||||
assertThat(retrieved.isPresent()).isTrue();
|
||||
assertThat(retrieved.get().getName()).isEqualTo(profile.getName());
|
||||
assertThat(retrieved.get().getAvatar()).isEqualTo(profile.getAvatar());
|
||||
assertThat(retrieved.get().getCommitment()).isEqualTo(profile.getCommitment());
|
||||
assertThat(retrieved.get().getAbout()).isEqualTo(profile.getAbout());
|
||||
assertThat(retrieved.get().getAboutEmoji()).isEqualTo(profile.getAboutEmoji());
|
||||
assertThat(retrieved.get().name()).isEqualTo(profile.name());
|
||||
assertThat(retrieved.get().avatar()).isEqualTo(profile.avatar());
|
||||
assertThat(retrieved.get().commitment()).isEqualTo(profile.commitment());
|
||||
assertThat(retrieved.get().about()).isEqualTo(profile.about());
|
||||
assertThat(retrieved.get().aboutEmoji()).isEqualTo(profile.aboutEmoji());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testSetReplace() {
|
||||
UUID uuid = UUID.randomUUID();
|
||||
VersionedProfile profile = new VersionedProfile("123", "foo", "avatarLocation", null, null,
|
||||
"paymentAddress", "acommitment".getBytes());
|
||||
profiles.set(uuid, profile);
|
||||
void testSetReplace() throws InvalidInputException {
|
||||
profiles.set(ACI, validProfile);
|
||||
|
||||
Optional<VersionedProfile> retrieved = profiles.get(uuid, "123");
|
||||
Optional<VersionedProfile> retrieved = profiles.get(ACI, validProfile.version());
|
||||
|
||||
assertThat(retrieved.isPresent()).isTrue();
|
||||
assertThat(retrieved.get().getName()).isEqualTo(profile.getName());
|
||||
assertThat(retrieved.get().getAvatar()).isEqualTo(profile.getAvatar());
|
||||
assertThat(retrieved.get().getCommitment()).isEqualTo(profile.getCommitment());
|
||||
assertThat(retrieved.get().getAbout()).isNull();
|
||||
assertThat(retrieved.get().getAboutEmoji()).isNull();
|
||||
assertThat(retrieved.get().name()).isEqualTo(validProfile.name());
|
||||
assertThat(retrieved.get().avatar()).isEqualTo(validProfile.avatar());
|
||||
assertThat(retrieved.get().commitment()).isEqualTo(validProfile.commitment());
|
||||
assertThat(retrieved.get().about()).isEqualTo(validProfile.about());
|
||||
assertThat(retrieved.get().aboutEmoji()).isEqualTo(validProfile.aboutEmoji());
|
||||
assertThat(retrieved.get().paymentAddress()).isNull();
|
||||
|
||||
VersionedProfile updated = new VersionedProfile("123", "bar", "baz", "emoji", "bio", null,
|
||||
"boof".getBytes());
|
||||
profiles.set(uuid, updated);
|
||||
final byte[] differentName = ProfileHelper.generateRandomByteArray(81);
|
||||
final byte[] differentEmoji = ProfileHelper.generateRandomByteArray(60);
|
||||
final byte[] differentAbout = ProfileHelper.generateRandomByteArray(156);
|
||||
final String differentAvatar = "profiles/" + ProfileHelper.generateRandomBase64FromByteArray(16);
|
||||
final byte[] differentCommitment = new ProfileKey(ProfileHelper.generateRandomByteArray(32)).getCommitment(new ServiceId.Aci(ACI)).serialize();
|
||||
|
||||
retrieved = profiles.get(uuid, "123");
|
||||
VersionedProfile updated = new VersionedProfile(validProfile.version(), differentName, differentAvatar, differentEmoji, differentAbout, null,
|
||||
differentCommitment);
|
||||
profiles.set(ACI, updated);
|
||||
|
||||
retrieved = profiles.get(ACI, updated.version());
|
||||
|
||||
assertThat(retrieved.isPresent()).isTrue();
|
||||
assertThat(retrieved.get().getName()).isEqualTo(updated.getName());
|
||||
assertThat(retrieved.get().getAbout()).isEqualTo(updated.getAbout());
|
||||
assertThat(retrieved.get().getAboutEmoji()).isEqualTo(updated.getAboutEmoji());
|
||||
assertThat(retrieved.get().getAvatar()).isEqualTo(updated.getAvatar());
|
||||
assertThat(retrieved.get().name()).isEqualTo(updated.name());
|
||||
assertThat(retrieved.get().about()).isEqualTo(updated.about());
|
||||
assertThat(retrieved.get().aboutEmoji()).isEqualTo(updated.aboutEmoji());
|
||||
assertThat(retrieved.get().avatar()).isEqualTo(updated.avatar());
|
||||
|
||||
// Commitment should be unchanged after an overwrite
|
||||
assertThat(retrieved.get().getCommitment()).isEqualTo(profile.getCommitment());
|
||||
assertThat(retrieved.get().commitment()).isEqualTo(validProfile.commitment());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testMultipleVersions() {
|
||||
UUID uuid = UUID.randomUUID();
|
||||
VersionedProfile profileOne = new VersionedProfile("123", "foo", "avatarLocation", null, null,
|
||||
null, "acommitmnet".getBytes());
|
||||
VersionedProfile profileTwo = new VersionedProfile("345", "bar", "baz", "emoji",
|
||||
"i keep typing emoju for some reason",
|
||||
null, "boof".getBytes());
|
||||
void testMultipleVersions() throws InvalidInputException {
|
||||
final String versionOne = "versionOne";
|
||||
final String versionTwo = "versionTwo";
|
||||
|
||||
profiles.set(uuid, profileOne);
|
||||
profiles.set(uuid, profileTwo);
|
||||
final byte[] nameOne = ProfileHelper.generateRandomByteArray(81);
|
||||
final byte[] nameTwo = ProfileHelper.generateRandomByteArray(81);
|
||||
|
||||
Optional<VersionedProfile> retrieved = profiles.get(uuid, "123");
|
||||
final String avatarOne = "profiles/" + ProfileHelper.generateRandomBase64FromByteArray(16);
|
||||
final String avatarTwo = "profiles/" + ProfileHelper.generateRandomBase64FromByteArray(16);
|
||||
|
||||
final byte[] aboutEmoji = ProfileHelper.generateRandomByteArray(60);
|
||||
final byte[] about = ProfileHelper.generateRandomByteArray(156);
|
||||
|
||||
final byte[] commitmentOne = new ProfileKey(ProfileHelper.generateRandomByteArray(32)).getCommitment(new ServiceId.Aci(ACI)).serialize();
|
||||
final byte[] commitmentTwo = new ProfileKey(ProfileHelper.generateRandomByteArray(32)).getCommitment(new ServiceId.Aci(ACI)).serialize();
|
||||
|
||||
VersionedProfile profileOne = new VersionedProfile(versionOne, nameOne, avatarOne, null, null,
|
||||
null, commitmentOne);
|
||||
VersionedProfile profileTwo = new VersionedProfile(versionTwo, nameTwo, avatarTwo, aboutEmoji, about, null, commitmentTwo);
|
||||
|
||||
profiles.set(ACI, profileOne);
|
||||
profiles.set(ACI, profileTwo);
|
||||
|
||||
Optional<VersionedProfile> retrieved = profiles.get(ACI, versionOne);
|
||||
|
||||
assertThat(retrieved.isPresent()).isTrue();
|
||||
assertThat(retrieved.get().getName()).isEqualTo(profileOne.getName());
|
||||
assertThat(retrieved.get().getAvatar()).isEqualTo(profileOne.getAvatar());
|
||||
assertThat(retrieved.get().getCommitment()).isEqualTo(profileOne.getCommitment());
|
||||
assertThat(retrieved.get().getAbout()).isEqualTo(profileOne.getAbout());
|
||||
assertThat(retrieved.get().getAboutEmoji()).isEqualTo(profileOne.getAboutEmoji());
|
||||
assertThat(retrieved.get().name()).isEqualTo(profileOne.name());
|
||||
assertThat(retrieved.get().avatar()).isEqualTo(profileOne.avatar());
|
||||
assertThat(retrieved.get().commitment()).isEqualTo(profileOne.commitment());
|
||||
assertThat(retrieved.get().about()).isEqualTo(profileOne.about());
|
||||
assertThat(retrieved.get().aboutEmoji()).isEqualTo(profileOne.aboutEmoji());
|
||||
|
||||
retrieved = profiles.get(uuid, "345");
|
||||
retrieved = profiles.get(ACI, versionTwo);
|
||||
|
||||
assertThat(retrieved.isPresent()).isTrue();
|
||||
assertThat(retrieved.get().getName()).isEqualTo(profileTwo.getName());
|
||||
assertThat(retrieved.get().getAvatar()).isEqualTo(profileTwo.getAvatar());
|
||||
assertThat(retrieved.get().getCommitment()).isEqualTo(profileTwo.getCommitment());
|
||||
assertThat(retrieved.get().getAbout()).isEqualTo(profileTwo.getAbout());
|
||||
assertThat(retrieved.get().getAboutEmoji()).isEqualTo(profileTwo.getAboutEmoji());
|
||||
assertThat(retrieved.get().name()).isEqualTo(profileTwo.name());
|
||||
assertThat(retrieved.get().avatar()).isEqualTo(profileTwo.avatar());
|
||||
assertThat(retrieved.get().commitment()).isEqualTo(profileTwo.commitment());
|
||||
assertThat(retrieved.get().about()).isEqualTo(profileTwo.about());
|
||||
assertThat(retrieved.get().aboutEmoji()).isEqualTo(profileTwo.aboutEmoji());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testMissing() {
|
||||
UUID uuid = UUID.randomUUID();
|
||||
VersionedProfile profile = new VersionedProfile("123", "foo", "avatarLocation", null, null,
|
||||
null, "aDigest".getBytes());
|
||||
profiles.set(uuid, profile);
|
||||
profiles.set(ACI, validProfile);
|
||||
final String missingVersion = "missingVersion";
|
||||
|
||||
Optional<VersionedProfile> retrieved = profiles.get(uuid, "888");
|
||||
Optional<VersionedProfile> retrieved = profiles.get(ACI, missingVersion);
|
||||
assertThat(retrieved.isPresent()).isFalse();
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
void testDelete() {
|
||||
UUID uuid = UUID.randomUUID();
|
||||
VersionedProfile profileOne = new VersionedProfile("123", "foo", "avatarLocation", null, null,
|
||||
null, "aDigest".getBytes());
|
||||
VersionedProfile profileTwo = new VersionedProfile("345", "bar", "baz", null, null, null, "boof".getBytes());
|
||||
void testDelete() throws InvalidInputException {
|
||||
final String versionOne = "versionOne";
|
||||
final String versionTwo = "versionTwo";
|
||||
|
||||
profiles.set(uuid, profileOne);
|
||||
profiles.set(uuid, profileTwo);
|
||||
final byte[] nameOne = ProfileHelper.generateRandomByteArray(81);
|
||||
final byte[] nameTwo = ProfileHelper.generateRandomByteArray(81);
|
||||
|
||||
profiles.deleteAll(uuid);
|
||||
final byte[] aboutEmoji = ProfileHelper.generateRandomByteArray(60);
|
||||
final byte[] about = ProfileHelper.generateRandomByteArray(156);
|
||||
|
||||
Optional<VersionedProfile> retrieved = profiles.get(uuid, "123");
|
||||
final String avatarOne = "profiles/" + ProfileHelper.generateRandomBase64FromByteArray(16);
|
||||
final String avatarTwo = "profiles/" + ProfileHelper.generateRandomBase64FromByteArray(16);
|
||||
|
||||
final byte[] commitmentOne = new ProfileKey(ProfileHelper.generateRandomByteArray(32)).getCommitment(new ServiceId.Aci(ACI)).serialize();
|
||||
final byte[] commitmentTwo = new ProfileKey(ProfileHelper.generateRandomByteArray(32)).getCommitment(new ServiceId.Aci(ACI)).serialize();
|
||||
|
||||
VersionedProfile profileOne = new VersionedProfile(versionOne, nameOne, avatarOne, null, null,
|
||||
null, commitmentOne);
|
||||
VersionedProfile profileTwo = new VersionedProfile(versionTwo, nameTwo, avatarTwo, aboutEmoji, about, null, commitmentTwo);
|
||||
|
||||
profiles.set(ACI, profileOne);
|
||||
profiles.set(ACI, profileTwo);
|
||||
|
||||
profiles.deleteAll(ACI);
|
||||
|
||||
Optional<VersionedProfile> retrieved = profiles.get(ACI, versionOne);
|
||||
|
||||
assertThat(retrieved.isPresent()).isFalse();
|
||||
|
||||
retrieved = profiles.get(uuid, "345");
|
||||
retrieved = profiles.get(ACI, versionTwo);
|
||||
|
||||
assertThat(retrieved.isPresent()).isFalse();
|
||||
}
|
||||
@@ -219,32 +259,38 @@ public class ProfilesTest {
|
||||
assertEquals(expectedUpdateExpression, Profiles.buildUpdateExpression(profile));
|
||||
}
|
||||
|
||||
private static Stream<Arguments> buildUpdateExpression() {
|
||||
final byte[] commitment = "commitment".getBytes(StandardCharsets.UTF_8);
|
||||
private static Stream<Arguments> buildUpdateExpression() throws InvalidInputException {
|
||||
final String version = "someVersion";
|
||||
final byte[] name = ProfileHelper.generateRandomByteArray(81);
|
||||
final String avatar = "profiles/" + ProfileHelper.generateRandomBase64FromByteArray(16);;
|
||||
final byte[] emoji = ProfileHelper.generateRandomByteArray(60);
|
||||
final byte[] about = ProfileHelper.generateRandomByteArray(156);
|
||||
final byte[] paymentAddress = ProfileHelper.generateRandomByteArray(582);
|
||||
final byte[] commitment = new ProfileKey(ProfileHelper.generateRandomByteArray(32)).getCommitment(new ServiceId.Aci(ACI)).serialize();
|
||||
|
||||
return Stream.of(
|
||||
Arguments.of(
|
||||
new VersionedProfile("version", "name", "avatar", "emoji", "about", "paymentAddress", commitment),
|
||||
new VersionedProfile(version, name, avatar, emoji, about, paymentAddress, commitment),
|
||||
"SET #commitment = if_not_exists(#commitment, :commitment), #name = :name, #avatar = :avatar, #about = :about, #aboutEmoji = :aboutEmoji, #paymentAddress = :paymentAddress"),
|
||||
|
||||
Arguments.of(
|
||||
new VersionedProfile("version", "name", "avatar", "emoji", "about", null, commitment),
|
||||
new VersionedProfile(version, name, avatar, emoji, about, null, commitment),
|
||||
"SET #commitment = if_not_exists(#commitment, :commitment), #name = :name, #avatar = :avatar, #about = :about, #aboutEmoji = :aboutEmoji REMOVE #paymentAddress"),
|
||||
|
||||
Arguments.of(
|
||||
new VersionedProfile("version", "name", "avatar", "emoji", null, null, commitment),
|
||||
new VersionedProfile(version, name, avatar, emoji, null, null, commitment),
|
||||
"SET #commitment = if_not_exists(#commitment, :commitment), #name = :name, #avatar = :avatar, #aboutEmoji = :aboutEmoji REMOVE #about, #paymentAddress"),
|
||||
|
||||
Arguments.of(
|
||||
new VersionedProfile("version", "name", "avatar", null, null, null, commitment),
|
||||
new VersionedProfile(version, name, avatar, null, null, null, commitment),
|
||||
"SET #commitment = if_not_exists(#commitment, :commitment), #name = :name, #avatar = :avatar REMOVE #about, #aboutEmoji, #paymentAddress"),
|
||||
|
||||
Arguments.of(
|
||||
new VersionedProfile("version", "name", null, null, null, null, commitment),
|
||||
new VersionedProfile(version, name, null, null, null, null, commitment),
|
||||
"SET #commitment = if_not_exists(#commitment, :commitment), #name = :name REMOVE #avatar, #about, #aboutEmoji, #paymentAddress"),
|
||||
|
||||
Arguments.of(
|
||||
new VersionedProfile("version", null, null, null, null, null, commitment),
|
||||
new VersionedProfile(version, null, null, null, null, null, commitment),
|
||||
"SET #commitment = if_not_exists(#commitment, :commitment) REMOVE #name, #avatar, #about, #aboutEmoji, #paymentAddress")
|
||||
);
|
||||
}
|
||||
@@ -255,52 +301,58 @@ public class ProfilesTest {
|
||||
assertEquals(expectedAttributeValues, Profiles.buildUpdateExpressionAttributeValues(profile));
|
||||
}
|
||||
|
||||
private static Stream<Arguments> buildUpdateExpressionAttributeValues() {
|
||||
final byte[] commitment = "commitment".getBytes(StandardCharsets.UTF_8);
|
||||
private static Stream<Arguments> buildUpdateExpressionAttributeValues() throws InvalidInputException {
|
||||
final String version = "someVersion";
|
||||
final byte[] name = ProfileHelper.generateRandomByteArray(81);
|
||||
final String avatar = "profiles/" + ProfileHelper.generateRandomBase64FromByteArray(16);;
|
||||
final byte[] emoji = ProfileHelper.generateRandomByteArray(60);
|
||||
final byte[] about = ProfileHelper.generateRandomByteArray(156);
|
||||
final byte[] paymentAddress = ProfileHelper.generateRandomByteArray(582);
|
||||
final byte[] commitment = new ProfileKey(ProfileHelper.generateRandomByteArray(32)).getCommitment(new ServiceId.Aci(ACI)).serialize();
|
||||
|
||||
return Stream.of(
|
||||
Arguments.of(
|
||||
new VersionedProfile("version", "name", "avatar", "emoji", "about", "paymentAddress", commitment),
|
||||
new VersionedProfile(version, name, avatar, emoji, about, paymentAddress, commitment),
|
||||
Map.of(
|
||||
":commitment", AttributeValues.fromByteArray(commitment),
|
||||
":name", AttributeValues.fromString("name"),
|
||||
":avatar", AttributeValues.fromString("avatar"),
|
||||
":aboutEmoji", AttributeValues.fromString("emoji"),
|
||||
":about", AttributeValues.fromString("about"),
|
||||
":paymentAddress", AttributeValues.fromString("paymentAddress"))),
|
||||
":name", AttributeValues.fromByteArray(name),
|
||||
":avatar", AttributeValues.fromString(avatar),
|
||||
":aboutEmoji", AttributeValues.fromByteArray(emoji),
|
||||
":about", AttributeValues.fromByteArray(about),
|
||||
":paymentAddress", AttributeValues.fromByteArray(paymentAddress))),
|
||||
|
||||
Arguments.of(
|
||||
new VersionedProfile("version", "name", "avatar", "emoji", "about", null, commitment),
|
||||
new VersionedProfile(version, name, avatar, emoji, about, null, commitment),
|
||||
Map.of(
|
||||
":commitment", AttributeValues.fromByteArray(commitment),
|
||||
":name", AttributeValues.fromString("name"),
|
||||
":avatar", AttributeValues.fromString("avatar"),
|
||||
":aboutEmoji", AttributeValues.fromString("emoji"),
|
||||
":about", AttributeValues.fromString("about"))),
|
||||
":name", AttributeValues.fromByteArray(name),
|
||||
":avatar", AttributeValues.fromString(avatar),
|
||||
":aboutEmoji", AttributeValues.fromByteArray(emoji),
|
||||
":about", AttributeValues.fromByteArray(about))),
|
||||
|
||||
Arguments.of(
|
||||
new VersionedProfile("version", "name", "avatar", "emoji", null, null, commitment),
|
||||
new VersionedProfile(version, name, avatar, emoji, null, null, commitment),
|
||||
Map.of(
|
||||
":commitment", AttributeValues.fromByteArray(commitment),
|
||||
":name", AttributeValues.fromString("name"),
|
||||
":avatar", AttributeValues.fromString("avatar"),
|
||||
":aboutEmoji", AttributeValues.fromString("emoji"))),
|
||||
":name",AttributeValues.fromByteArray(name),
|
||||
":avatar", AttributeValues.fromString(avatar),
|
||||
":aboutEmoji", AttributeValues.fromByteArray(emoji))),
|
||||
|
||||
Arguments.of(
|
||||
new VersionedProfile("version", "name", "avatar", null, null, null, commitment),
|
||||
new VersionedProfile(version, name, avatar, null, null, null, commitment),
|
||||
Map.of(
|
||||
":commitment", AttributeValues.fromByteArray(commitment),
|
||||
":name", AttributeValues.fromString("name"),
|
||||
":avatar", AttributeValues.fromString("avatar"))),
|
||||
":name", AttributeValues.fromByteArray(name),
|
||||
":avatar", AttributeValues.fromString(avatar))),
|
||||
|
||||
Arguments.of(
|
||||
new VersionedProfile("version", "name", null, null, null, null, commitment),
|
||||
new VersionedProfile(version, name, null, null, null, null, commitment),
|
||||
Map.of(
|
||||
":commitment", AttributeValues.fromByteArray(commitment),
|
||||
":name", AttributeValues.fromString("name"))),
|
||||
":name", AttributeValues.fromByteArray(name))),
|
||||
|
||||
Arguments.of(
|
||||
new VersionedProfile("version", null, null, null, null, null, commitment),
|
||||
new VersionedProfile(version, null, null, null, null, null, commitment),
|
||||
Map.of(":commitment", AttributeValues.fromByteArray(commitment)))
|
||||
);
|
||||
}
|
||||
|
||||
-30
@@ -122,34 +122,4 @@ abstract class SingleUsePreKeyStoreTest<K extends PreKey<?>> {
|
||||
assertEquals(0, preKeyStore.getCount(accountIdentifier, deviceId).join());
|
||||
assertEquals(0, preKeyStore.getCount(accountIdentifier, deviceId + 1).join());
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@MethodSource
|
||||
void extractByteArray(final AttributeValue attributeValue, final byte[] expectedByteArray) {
|
||||
assertArrayEquals(expectedByteArray, getPreKeyStore().extractByteArray(attributeValue));
|
||||
}
|
||||
|
||||
private static Stream<Arguments> extractByteArray() {
|
||||
final byte[] key = Base64.getDecoder().decode("c+k+8zv8WaFdDjR9IOvCk6BcY5OI7rge/YUDkaDGyRc=");
|
||||
|
||||
return Stream.of(
|
||||
Arguments.of(AttributeValue.fromB(SdkBytes.fromByteArray(key)), key),
|
||||
Arguments.of(AttributeValue.fromS(Base64.getEncoder().encodeToString(key)), key),
|
||||
Arguments.of(AttributeValue.fromS(Base64.getEncoder().withoutPadding().encodeToString(key)), key)
|
||||
);
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@MethodSource
|
||||
void extractByteArrayIllegalArgument(final AttributeValue attributeValue) {
|
||||
assertThrows(IllegalArgumentException.class, () -> getPreKeyStore().extractByteArray(attributeValue));
|
||||
}
|
||||
|
||||
private static Stream<Arguments> extractByteArrayIllegalArgument() {
|
||||
return Stream.of(
|
||||
Arguments.of(AttributeValue.fromN("12")),
|
||||
Arguments.of(AttributeValue.fromS("")),
|
||||
Arguments.of(AttributeValue.fromS("Definitely not legitimate base64 👎"))
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -121,12 +121,7 @@ public class AccountsHelper {
|
||||
case "isEnabled" -> when(updatedAccount.isEnabled()).thenAnswer(stubbing);
|
||||
case "isDiscoverableByPhoneNumber" -> when(updatedAccount.isDiscoverableByPhoneNumber()).thenAnswer(stubbing);
|
||||
case "getNextDeviceId" -> when(updatedAccount.getNextDeviceId()).thenAnswer(stubbing);
|
||||
case "isSenderKeySupported" -> when(updatedAccount.isSenderKeySupported()).thenAnswer(stubbing);
|
||||
case "isAnnouncementGroupSupported" -> when(updatedAccount.isAnnouncementGroupSupported()).thenAnswer(stubbing);
|
||||
case "isChangeNumberSupported" -> when(updatedAccount.isChangeNumberSupported()).thenAnswer(stubbing);
|
||||
case "isPniSupported" -> when(updatedAccount.isPniSupported()).thenAnswer(stubbing);
|
||||
case "isStoriesSupported" -> when(updatedAccount.isStoriesSupported()).thenAnswer(stubbing);
|
||||
case "isGiftBadgesSupported" -> when(updatedAccount.isGiftBadgesSupported()).thenAnswer(stubbing);
|
||||
case "isPaymentActivationSupported" -> when(updatedAccount.isPaymentActivationSupported()).thenAnswer(stubbing);
|
||||
case "getEnabledDeviceCount" -> when(updatedAccount.getEnabledDeviceCount()).thenAnswer(stubbing);
|
||||
case "getRegistrationLock" -> when(updatedAccount.getRegistrationLock()).thenAnswer(stubbing);
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
package org.whispersystems.textsecuregcm.tests.util;
|
||||
|
||||
import java.util.Base64;
|
||||
import java.util.Random;
|
||||
|
||||
public class ProfileHelper {
|
||||
public static String generateRandomBase64FromByteArray(final int byteArrayLength) {
|
||||
return encodeToBase64(generateRandomByteArray(byteArrayLength));
|
||||
}
|
||||
|
||||
public static byte[] generateRandomByteArray(final int length) {
|
||||
byte[] byteArray = new byte[length];
|
||||
new Random().nextBytes(byteArray);
|
||||
return byteArray;
|
||||
}
|
||||
|
||||
public static String encodeToBase64(final byte[] input) {
|
||||
return Base64.getEncoder().encodeToString(input);
|
||||
}
|
||||
}
|
||||
@@ -6,10 +6,16 @@
|
||||
package org.whispersystems.textsecuregcm.util;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.Arguments;
|
||||
import org.junit.jupiter.params.provider.MethodSource;
|
||||
import software.amazon.awssdk.core.SdkBytes;
|
||||
import software.amazon.awssdk.services.dynamodb.model.AttributeValue;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.util.Base64;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
@@ -63,4 +69,34 @@ public class AttributeValuesTest {
|
||||
final Map<String, AttributeValue> item = Map.of("key", AttributeValue.builder().nul(true).build());
|
||||
assertNull(AttributeValues.getUUID(item, "key", null));
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@MethodSource
|
||||
void extractByteArray(final AttributeValue attributeValue, final byte[] expectedByteArray) {
|
||||
assertArrayEquals(expectedByteArray, AttributeValues.extractByteArray(attributeValue, "counter"));
|
||||
}
|
||||
|
||||
private static Stream<Arguments> extractByteArray() {
|
||||
final byte[] key = Base64.getDecoder().decode("c+k+8zv8WaFdDjR9IOvCk6BcY5OI7rge/YUDkaDGyRc=");
|
||||
|
||||
return Stream.of(
|
||||
Arguments.of(AttributeValue.fromB(SdkBytes.fromByteArray(key)), key),
|
||||
Arguments.of(AttributeValue.fromS(Base64.getEncoder().encodeToString(key)), key),
|
||||
Arguments.of(AttributeValue.fromS(Base64.getEncoder().withoutPadding().encodeToString(key)), key)
|
||||
);
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@MethodSource
|
||||
void extractByteArrayIllegalArgument(final AttributeValue attributeValue) {
|
||||
assertThrows(IllegalArgumentException.class, () -> AttributeValues.extractByteArray(attributeValue, "counter"));
|
||||
}
|
||||
|
||||
private static Stream<Arguments> extractByteArrayIllegalArgument() {
|
||||
return Stream.of(
|
||||
Arguments.of(AttributeValue.fromN("12")),
|
||||
Arguments.of(AttributeValue.fromS("")),
|
||||
Arguments.of(AttributeValue.fromS("Definitely not legitimate base64 👎"))
|
||||
);
|
||||
}
|
||||
}
|
||||
+1
-1
Submodule spam-filter updated: 50095c012e...ee3923ae0d.
Reference in new issue
Block a user