Clear receipt state before integration tests

This commit is contained in:
Ravi Khadiwala authored and ravi-signal committed 2026-09-17 12:50:28 -05:00
1 parent b30fc7aa8b
commit 755a87c74d
2 files changed
+91 -69

No files matched your search

@@ -164,8 +164,7 @@ public final class Operations {
}
public static TestUser recoverNumberlessUserWithTotp(final TestUser testUser, @Nullable final Integer totp) {
final String accountPassword = Base64.getEncoder().encodeToString(randomBytes(32));
final TestUser recoveredUser = TestUser.createNumberlessForRecovery(accountPassword, testUser.registrationPassword());
final TestUser recoveredUser = TestUser.createNumberlessForRecovery(testUser.accountPassword(), testUser.registrationPassword());
final ECKeyPair aciIdentityKeyPair = ECKeyPair.generate();
final ECKeyPair pniIdentityKeyPair = ECKeyPair.generate();
@@ -187,7 +186,7 @@ public final class Operations {
final AccountIdentityResponse registrationResponse = apiPost("/v1/registration", registrationRequest)
// For a numberless account recovery, the username is the ACI
.authorized(testUser.aciUuid().toString(), accountPassword)
.authorized(testUser.aciUuid().toString(), testUser.accountPassword())
.executeExpectSuccess(AccountIdentityResponse.class);
recoveredUser.setAciUuid(registrationResponse.uuid());
@@ -198,8 +197,7 @@ public final class Operations {
final ClientPlatform clientPlatform,
final byte[] credentialId,
final String relyingPartyId) {
final String accountPassword = Base64.getEncoder().encodeToString(randomBytes(32));
final TestUser recoveredUser = TestUser.createNumberlessForRecovery(accountPassword, testUser.registrationPassword());
final TestUser recoveredUser = TestUser.createNumberlessForRecovery(testUser.accountPassword(), testUser.registrationPassword());
final ECKeyPair aciIdentityKeyPair = ECKeyPair.generate();
final ECKeyPair pniIdentityKeyPair = ECKeyPair.generate();
@@ -221,7 +219,7 @@ public final class Operations {
final Pair<Integer, MfaFailureExceptionMapper.MfaFailureResponse> initialResponse = apiPost("/v1/registration", initialRequest)
// For a numberless account recovery, the username is the ACI
.authorized(testUser.aciUuid().toString(), accountPassword)
.authorized(testUser.aciUuid().toString(), testUser.accountPassword())
.execute(MfaFailureExceptionMapper.MfaFailureResponse.class);
// we expect (and need) failure with status 441, which will contain the WebAuthn challenge
@@ -259,7 +257,7 @@ public final class Operations {
final AccountIdentityResponse registrationResponse = apiPost("/v1/registration", registrationRequest)
// For a numberless account recovery, the username is the ACI
.authorized(testUser.aciUuid().toString(), accountPassword)
.authorized(testUser.aciUuid().toString(), testUser.accountPassword())
.executeExpectSuccess(AccountIdentityResponse.class);
recoveredUser.setAciUuid(registrationResponse.uuid());
@@ -483,33 +481,39 @@ public final class Operations {
}
public Pair<Integer, Void> executeExpectSuccess() {
final Pair<Integer, Void> execute = execute();
final RawResponse response = executeRaw();
Validate.isTrue(
HttpUtils.isSuccessfulResponse(execute.getLeft()),
"Unexpected response code: %d",
execute.getLeft());
return execute;
HttpUtils.isSuccessfulResponse(response.statusCode()),
"Unexpected response code: %d, body: %s",
response.statusCode(), response.body());
return Pair.of(response.statusCode(), null);
}
public <T> T executeExpectSuccess(final Class<T> expectedType) {
final Pair<Integer, T> execute = execute(expectedType);
final RawResponse response = executeRaw();
Validate.isTrue(
HttpUtils.isSuccessfulResponse(execute.getLeft()),
"Unexpected response code: %d : %s",
execute.getLeft(), execute.getRight());
return requireNonNull(execute.getRight());
HttpUtils.isSuccessfulResponse(response.statusCode()),
"Unexpected response code: %d, body: %s",
response.statusCode(), response.body());
return requireNonNull(parseBody(response.body(), expectedType));
}
public void executeExpectStatusCode(final int expectedStatusCode) {
final Pair<Integer, Void> execute = execute(Void.class);
final RawResponse response = executeRaw();
Validate.isTrue(
execute.getLeft() == expectedStatusCode,
"Unexpected response code: %d",
execute.getLeft()
);
response.statusCode() == expectedStatusCode,
"Unexpected response code: %d (expected %d), body: %s",
response.statusCode(), expectedStatusCode, response.body());
}
public <T> Pair<Integer, T> execute(final Class<T> expectedType) {
final RawResponse response = executeRaw();
return Pair.of(response.statusCode(), parseBody(response.body(), expectedType));
}
private record RawResponse(int statusCode, String body) {}
private RawResponse executeRaw() {
builder.uri(serverUri(endpoint, queryParams))
.header(HttpHeaders.USER_AGENT, USER_AGENT);
return CLIENT.sendAsync(builder.build(), HttpResponse.BodyHandlers.ofString(StandardCharsets.UTF_8))
@@ -519,19 +523,24 @@ public final class Operations {
error.printStackTrace();
}
})
.thenApply(response -> {
try {
final T result = expectedType.equals(Void.class)
? null
: SystemMapper.jsonMapper().readValue(response.body(), expectedType);
return Pair.of(response.statusCode(), result);
} catch (final IOException e) {
throw new RuntimeException(e);
}
})
.thenApply(response -> new RawResponse(response.statusCode(), response.body()))
.join();
}
@Nullable
private static <T> T parseBody(final String body, final Class<T> expectedType) {
if (expectedType.equals(Void.class)) {
return null;
}
try {
return SystemMapper.jsonMapper().readValue(body, expectedType);
} catch (final IOException e) {
throw new RuntimeException(
"Could not parse response body as %s, body: %s".formatted(expectedType.getSimpleName(), body), e);
}
}
}
private static FaultTolerantHttpClient buildClient() {
@@ -39,11 +39,13 @@ import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.UUID;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.lang3.tuple.Pair;
import org.apache.http.HttpStatus;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;
import org.signal.chat.account.AccountsGrpc;
import org.signal.chat.account.ConfirmTotpKeyRequest;
@@ -80,26 +82,47 @@ public class AccountTest {
public void testCreateNumberlessAccount()
throws VerificationFailedException, InvalidInputException {
final Operations.Receipt receipt = Operations.getPrescribedReceipt();
final TestUser user = Operations.registerNumberlessUser(receipt.credential());
Operations.deleteReceipt(receipt.serial());
TestUser user = null;
try {
user = Operations.registerNumberlessUser(receipt.credential());
final Pair<Integer, AccountIdentityResponse> execute = Operations.apiGet("/v1/accounts/whoami")
.authorized(user)
.execute(AccountIdentityResponse.class);
assertEquals(HttpStatus.SC_OK, execute.getLeft());
} finally {
Operations.deleteReceipt(receipt.serial());
Operations.deleteUser(user);
if (user != null) {
Operations.deleteUser(user);
}
}
}
@Test
public void testRecoverWithTotp()
throws VerificationFailedException, InvalidInputException, NoSuchAlgorithmException, InvalidKeyException {
final Operations.Receipt receipt = Operations.getPrescribedReceipt();
TestUser user = Operations.registerNumberlessUser(receipt.credential());
final UUID originalAci = user.aciUuid();
@Nested
class RecoverWithMfa {
private TestUser user;
try {
@BeforeEach
void setup() throws InvalidInputException, VerificationFailedException {
final Operations.Receipt receipt = Operations.getPrescribedReceipt();
// Clear receipt state in case a previous run had an unclean failure
Operations.deleteReceipt(receipt.serial());
user = Operations.registerNumberlessUser(receipt.credential());
}
@AfterEach
void teardown() throws InvalidInputException {
final Operations.Receipt receipt = Operations.getPrescribedReceipt();
Operations.deleteReceipt(receipt.serial());
if (user != null) {
Operations.deleteUser(user);
}
}
@Test
public void testRecoverWithTotp() throws NoSuchAlgorithmException, InvalidKeyException {
final GenerateTotpKeyResponse generateTotpKeyResponse =
getAccountsStubForUser(user).generateTotpKey(GenerateTotpKeyRequest.getDefaultInstance());
assertEquals(GenerateTotpKeyResponse.ResponseCase.KEY_GENERATED, generateTotpKeyResponse.getResponseCase());
@@ -124,39 +147,31 @@ public class AccountTest {
assertEquals(ConfirmTotpKeyResponse.ResponseCase.KEY_CONFIRMED, confirmTotpKeyResponse.getResponseCase());
final int keyId = confirmTotpKeyResponse.getKeyConfirmed().getKeyId();
user = Operations.recoverNumberlessUserWithTotp(user, totpGenerator.generateOneTimePassword(totpKey, Instant.now()));
final TestUser recoveredUser =
Operations.recoverNumberlessUserWithTotp(user, totpGenerator.generateOneTimePassword(totpKey, Instant.now()));
assertEquals(user.aciUuid(), originalAci);
assertEquals(user.aciUuid(), recoveredUser.aciUuid());
// MFA key should remain set after re-registration
final Map<Integer, ListMfaKeysResponse.MfaKeyMetadata> mfaKeys =
getAccountsStubForUser(user).listMfaKeys(ListMfaKeysRequest.getDefaultInstance()).getKeysMap();
getAccountsStubForUser(recoveredUser).listMfaKeys(ListMfaKeysRequest.getDefaultInstance()).getKeysMap();
assertEquals(1, mfaKeys.size());
assertTrue(mfaKeys.containsKey(keyId));
assertEquals(ListMfaKeysResponse.MfaKeyMetadata.MfaKeyType.MFA_KEY_TYPE_TOTP, mfaKeys.get(keyId).getType());
assertArrayEquals(totpMetadata, mfaKeys.get(keyId).getMetadataCiphertext().toByteArray());
} finally {
Operations.deleteReceipt(receipt.serial());
Operations.deleteUser(user);
}
}
@Test
public void testRecoverWithWebAuthn() throws VerificationFailedException, InvalidInputException {
final WebAuthnConfiguration webAuthnConfiguration = Operations.getWebAuthnConfiguration();
final ClientPlatform clientPlatform = new ClientPlatform(new Origin(webAuthnConfiguration.origin()), new WebAuthnAuthenticatorAdaptor(EmulatorUtil.NONE_ATTESTATION_AUTHENTICATOR));
final COSEAlgorithmIdentifier algorithm = COSEAlgorithmIdentifier.ES256;
@Test
public void testRecoverWithWebAuthn() {
final WebAuthnConfiguration webAuthnConfiguration = Operations.getWebAuthnConfiguration();
final ClientPlatform clientPlatform = new ClientPlatform(new Origin(webAuthnConfiguration.origin()), new WebAuthnAuthenticatorAdaptor(EmulatorUtil.NONE_ATTESTATION_AUTHENTICATOR));
final COSEAlgorithmIdentifier algorithm = COSEAlgorithmIdentifier.ES256;
final Operations.Receipt receipt = Operations.getPrescribedReceipt();
TestUser user = Operations.registerNumberlessUser(receipt.credential());
final UUID originalAci = user.aciUuid();
try {
final StartWebAuthnRegistrationResponse startWebAuthnRegistrationResponse =
getAccountsStubForUser(user).startWebAuthnRegistration(StartWebAuthnRegistrationRequest.getDefaultInstance());
assertEquals(StartWebAuthnRegistrationResponse.ResponseCase.PARAMS, startWebAuthnRegistrationResponse.getResponseCase());
assertEquals(StartWebAuthnRegistrationResponse.ResponseCase.PARAMS,
startWebAuthnRegistrationResponse.getResponseCase());
final StartWebAuthnRegistrationResponse.WebAuthnCreateParameters webAuthnCreateParameters = startWebAuthnRegistrationResponse.getParams();
@@ -184,25 +199,23 @@ public class AccountTest {
.setCollectedClientDataJsonBytes(ByteString.copyFrom(credential.getResponse().getClientDataJSON()))
.setMetadataCiphertext(ByteString.copyFrom(metadataCiphertext))
.build());
assertEquals(FinishWebAuthnRegistrationResponse.ResponseCase.KEY_CONFIRMED, finishWebAuthnRegistrationResponse.getResponseCase());
assertEquals(FinishWebAuthnRegistrationResponse.ResponseCase.KEY_CONFIRMED,
finishWebAuthnRegistrationResponse.getResponseCase());
final int keyId = finishWebAuthnRegistrationResponse.getKeyConfirmed().getKeyId();
user = Operations.recoverNumberlessUserWithWebAuthn(user, clientPlatform, credential.getRawId(), webAuthnConfiguration.relyingPartyId());
final TestUser recoveredUser = Operations.recoverNumberlessUserWithWebAuthn(user, clientPlatform, credential.getRawId(),
webAuthnConfiguration.relyingPartyId());
assertEquals(originalAci, user.aciUuid());
assertEquals(user.aciUuid(), recoveredUser.aciUuid());
// MFA key should remain set after re-registration
final Map<Integer, ListMfaKeysResponse.MfaKeyMetadata> mfaKeys =
getAccountsStubForUser(user).listMfaKeys(ListMfaKeysRequest.getDefaultInstance()).getKeysMap();
getAccountsStubForUser(recoveredUser).listMfaKeys(ListMfaKeysRequest.getDefaultInstance()).getKeysMap();
assertEquals(1, mfaKeys.size());
assertTrue(mfaKeys.containsKey(keyId));
assertEquals(ListMfaKeysResponse.MfaKeyMetadata.MfaKeyType.MFA_KEY_TYPE_WEBAUTHN, mfaKeys.get(keyId).getType());
assertArrayEquals(metadataCiphertext, mfaKeys.get(keyId).getMetadataCiphertext().toByteArray());
} finally {
Operations.deleteReceipt(receipt.serial());
Operations.deleteUser(user);
}
}