Use better null-handling around registrar certificates (#922)

* Use better null-handling around registrar certificates

Now with Optional it's always very clear whether they do or do not have values.
isNullOrEmpty() shouldn't be necessary anymore (indeed it wasn't necessary prior
to this either, as the relevant setters in the Registrar builder already coerced
empty strings to null). And also the cert hash is a required HTTP header, so it
will error out in the Dagger component if null or empty long before getting to
any other code.

* Merge branch 'master' into optional-get-certs
This commit is contained in:
Ben McIlwain 2021-01-07 19:30:09 -05:00 committed by GitHub
parent 7a62aa0602
commit 9e03ae453c
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
16 changed files with 139 additions and 100 deletions

View file

@ -15,9 +15,7 @@
package google.registry.flows; package google.registry.flows;
import static com.google.common.base.MoreObjects.toStringHelper; import static com.google.common.base.MoreObjects.toStringHelper;
import static com.google.common.base.Strings.isNullOrEmpty;
import static google.registry.request.RequestParameters.extractOptionalHeader; import static google.registry.request.RequestParameters.extractOptionalHeader;
import static google.registry.request.RequestParameters.extractRequiredHeader;
import com.google.common.annotations.VisibleForTesting; import com.google.common.annotations.VisibleForTesting;
import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableList;
@ -56,17 +54,17 @@ public class TlsCredentials implements TransportCredentials {
private static final FluentLogger logger = FluentLogger.forEnclosingClass(); private static final FluentLogger logger = FluentLogger.forEnclosingClass();
private final boolean requireSslCertificates; private final boolean requireSslCertificates;
private final String clientCertificateHash; private final Optional<String> clientCertificateHash;
private final InetAddress clientInetAddr; private final Optional<InetAddress> clientInetAddr;
@Inject @Inject
public TlsCredentials( public TlsCredentials(
@Config("requireSslCertificates") boolean requireSslCertificates, @Config("requireSslCertificates") boolean requireSslCertificates,
@Header("X-SSL-Certificate") String clientCertificateHash, @Header("X-SSL-Certificate") Optional<String> clientCertificateHash,
@Header("X-Forwarded-For") Optional<String> clientAddress) { @Header("X-Forwarded-For") Optional<String> clientAddress) {
this.requireSslCertificates = requireSslCertificates; this.requireSslCertificates = requireSslCertificates;
this.clientCertificateHash = clientCertificateHash; this.clientCertificateHash = clientCertificateHash;
this.clientInetAddr = clientAddress.isPresent() ? parseInetAddress(clientAddress.get()) : null; this.clientInetAddr = clientAddress.map(TlsCredentials::parseInetAddress);
} }
static InetAddress parseInetAddress(String asciiAddr) { static InetAddress parseInetAddress(String asciiAddr) {
@ -97,10 +95,14 @@ public class TlsCredentials implements TransportCredentials {
registrar.getClientId()); registrar.getClientId());
return; return;
} }
for (CidrAddressBlock cidrAddressBlock : ipAddressAllowList) { // In the rare unexpected case that the client inet address wasn't passed along at all, then
if (cidrAddressBlock.contains(clientInetAddr)) { // by default deny access.
// IP address is in allow list; return early. if (clientInetAddr.isPresent()) {
return; for (CidrAddressBlock cidrAddressBlock : ipAddressAllowList) {
if (cidrAddressBlock.contains(clientInetAddr.get())) {
// IP address is in allow list; return early.
return;
}
} }
} }
logger.atInfo().log( logger.atInfo().log(
@ -118,8 +120,8 @@ public class TlsCredentials implements TransportCredentials {
*/ */
@VisibleForTesting @VisibleForTesting
void validateCertificate(Registrar registrar) throws AuthenticationErrorException { void validateCertificate(Registrar registrar) throws AuthenticationErrorException {
if (isNullOrEmpty(registrar.getClientCertificateHash()) if (!registrar.getClientCertificateHash().isPresent()
&& isNullOrEmpty(registrar.getFailoverClientCertificateHash())) { && !registrar.getFailoverClientCertificateHash().isPresent()) {
if (requireSslCertificates) { if (requireSslCertificates) {
throw new RegistrarCertificateNotConfiguredException(); throw new RegistrarCertificateNotConfiguredException();
} else { } else {
@ -128,7 +130,7 @@ public class TlsCredentials implements TransportCredentials {
return; return;
} }
} }
if (isNullOrEmpty(clientCertificateHash)) { if (!clientCertificateHash.isPresent()) {
logger.atInfo().log("Request did not include X-SSL-Certificate"); logger.atInfo().log("Request did not include X-SSL-Certificate");
throw new MissingRegistrarCertificateException(); throw new MissingRegistrarCertificateException();
} }
@ -154,21 +156,21 @@ public class TlsCredentials implements TransportCredentials {
@Override @Override
public String toString() { public String toString() {
return toStringHelper(getClass()) return toStringHelper(getClass())
.add("clientCertificateHash", clientCertificateHash) .add("clientCertificateHash", clientCertificateHash.orElse(null))
.add("clientAddress", clientInetAddr) .add("clientAddress", clientInetAddr.orElse(null))
.toString(); .toString();
} }
/** Registrar certificate does not match stored certificate. */ /** Registrar certificate does not match stored certificate. */
public static class BadRegistrarCertificateException extends AuthenticationErrorException { public static class BadRegistrarCertificateException extends AuthenticationErrorException {
public BadRegistrarCertificateException() { BadRegistrarCertificateException() {
super("Registrar certificate does not match stored certificate"); super("Registrar certificate does not match stored certificate");
} }
} }
/** Registrar certificate not present. */ /** Registrar certificate not present. */
public static class MissingRegistrarCertificateException extends AuthenticationErrorException { public static class MissingRegistrarCertificateException extends AuthenticationErrorException {
public MissingRegistrarCertificateException() { MissingRegistrarCertificateException() {
super("Registrar certificate not present"); super("Registrar certificate not present");
} }
} }
@ -176,14 +178,14 @@ public class TlsCredentials implements TransportCredentials {
/** Registrar certificate is not configured. */ /** Registrar certificate is not configured. */
public static class RegistrarCertificateNotConfiguredException public static class RegistrarCertificateNotConfiguredException
extends AuthenticationErrorException { extends AuthenticationErrorException {
public RegistrarCertificateNotConfiguredException() { RegistrarCertificateNotConfiguredException() {
super("Registrar certificate is not configured"); super("Registrar certificate is not configured");
} }
} }
/** Registrar IP address is not in stored allow list. */ /** Registrar IP address is not in stored allow list. */
public static class BadRegistrarIpAddressException extends AuthenticationErrorException { public static class BadRegistrarIpAddressException extends AuthenticationErrorException {
public BadRegistrarIpAddressException() { BadRegistrarIpAddressException() {
super("Registrar IP address is not in stored allow list"); super("Registrar IP address is not in stored allow list");
} }
} }
@ -191,10 +193,13 @@ public class TlsCredentials implements TransportCredentials {
/** Dagger module for the EPP TLS endpoint. */ /** Dagger module for the EPP TLS endpoint. */
@Module @Module
public static final class EppTlsModule { public static final class EppTlsModule {
@Provides @Provides
@Header("X-SSL-Certificate") @Header("X-SSL-Certificate")
static String provideClientCertificateHash(HttpServletRequest req) { static Optional<String> provideClientCertificateHash(HttpServletRequest req) {
return extractRequiredHeader(req, "X-SSL-Certificate"); // Note: This header is actually required, we just want to handle its absence explicitly
// by throwing an EPP exception rather than a generic Bad Request exception.
return extractOptionalHeader(req, "X-SSL-Certificate");
} }
@Provides @Provides

View file

@ -537,20 +537,24 @@ public class Registrar extends ImmutableObject
return LIVE_STATES.contains(state) && PUBLICLY_VISIBLE_TYPES.contains(type); return LIVE_STATES.contains(state) && PUBLICLY_VISIBLE_TYPES.contains(type);
} }
public String getClientCertificate() { /** Returns the client certificate string if it has been set, or empty otherwise. */
return clientCertificate; public Optional<String> getClientCertificate() {
return Optional.ofNullable(clientCertificate);
} }
public String getClientCertificateHash() { /** Returns the client certificate hash if it has been set, or empty otherwise. */
return clientCertificateHash; public Optional<String> getClientCertificateHash() {
return Optional.ofNullable(clientCertificateHash);
} }
public String getFailoverClientCertificate() { /** Returns the failover client certificate string if it has been set, or empty otherwise. */
return failoverClientCertificate; public Optional<String> getFailoverClientCertificate() {
return Optional.ofNullable(failoverClientCertificate);
} }
public String getFailoverClientCertificateHash() { /** Returns the failover client certificate hash if it has been set, or empty otherwise. */
return failoverClientCertificateHash; public Optional<String> getFailoverClientCertificateHash() {
return Optional.ofNullable(failoverClientCertificateHash);
} }
public ImmutableList<CidrAddressBlock> getIpAddressAllowList() { public ImmutableList<CidrAddressBlock> getIpAddressAllowList() {

View file

@ -310,7 +310,7 @@ public final class RequestParameters {
* @param name case insensitive header name * @param name case insensitive header name
*/ */
public static Optional<String> extractOptionalHeader(HttpServletRequest req, String name) { public static Optional<String> extractOptionalHeader(HttpServletRequest req, String name) {
return Optional.ofNullable(req.getHeader(name)); return Optional.ofNullable(emptyToNull(req.getHeader(name)));
} }
private RequestParameters() {} private RequestParameters() {}

View file

@ -61,6 +61,7 @@ final class ValidateLoginCredentialsCommand implements CommandWithRemoteApi {
description = "Hash of the client certificate.") description = "Hash of the client certificate.")
private String clientCertificateHash; private String clientCertificateHash;
@Nullable
@Parameter( @Parameter(
names = {"-i", "--ip_address"}, names = {"-i", "--ip_address"},
description = "Client ip address to pretend to use") description = "Client ip address to pretend to use")
@ -78,7 +79,8 @@ final class ValidateLoginCredentialsCommand implements CommandWithRemoteApi {
Registrar registrar = Registrar registrar =
checkArgumentPresent( checkArgumentPresent(
Registrar.loadByClientId(clientId), "Registrar %s not found", clientId); Registrar.loadByClientId(clientId), "Registrar %s not found", clientId);
new TlsCredentials(true, clientCertificateHash, Optional.of(clientIpAddress)) new TlsCredentials(
true, Optional.ofNullable(clientCertificateHash), Optional.ofNullable(clientIpAddress))
.validate(registrar, password); .validate(registrar, password);
checkState( checkState(
registrar.isLive(), "Registrar %s has non-live state: %s", clientId, registrar.getState()); registrar.isLive(), "Registrar %s has non-live state: %s", clientId, registrar.getState());

View file

@ -334,8 +334,9 @@ public class RegistrarSettingsAction implements Runnable, JsonActionRunner.JsonA
* Returns true if the registrar should accept the new certificate. Returns false if the * Returns true if the registrar should accept the new certificate. Returns false if the
* certificate is already the one stored for the registrar. * certificate is already the one stored for the registrar.
*/ */
private boolean validateCertificate(String existingCertificate, String certificateString) { private boolean validateCertificate(
if ((existingCertificate == null) || !existingCertificate.equals(certificateString)) { Optional<String> existingCertificate, String certificateString) {
if (!existingCertificate.isPresent() || !existingCertificate.get().equals(certificateString)) {
certificateChecker.validateCertificate(certificateString); certificateChecker.validateCertificate(certificateString);
return true; return true;
} }

View file

@ -36,7 +36,8 @@ class EppLoginTlsTest extends EppTestCase {
void setClientCertificateHash(String clientCertificateHash) { void setClientCertificateHash(String clientCertificateHash) {
setTransportCredentials( setTransportCredentials(
new TlsCredentials(true, clientCertificateHash, Optional.of("192.168.1.100:54321"))); new TlsCredentials(
true, Optional.ofNullable(clientCertificateHash), Optional.of("192.168.1.100:54321")));
} }
@BeforeEach @BeforeEach
@ -107,7 +108,7 @@ class EppLoginTlsTest extends EppTestCase {
@Test @Test
void testGfeDidntProvideClientCertificate_failsMissingCertificate2200() throws Exception { void testGfeDidntProvideClientCertificate_failsMissingCertificate2200() throws Exception {
setClientCertificateHash(""); setClientCertificateHash(null);
assertThatLogin("NewRegistrar", "foo-BAR2") assertThatLogin("NewRegistrar", "foo-BAR2")
.hasResponse( .hasResponse(
"response_error.xml", "response_error.xml",

View file

@ -137,7 +137,8 @@ class FlowRunnerTest {
@Test @Test
void testRun_loggingStatement_tlsCredentials() throws Exception { void testRun_loggingStatement_tlsCredentials() throws Exception {
flowRunner.credentials = new TlsCredentials(true, "abc123def", Optional.of("127.0.0.1")); flowRunner.credentials =
new TlsCredentials(true, Optional.of("abc123def"), Optional.of("127.0.0.1"));
flowRunner.run(eppMetricBuilder); flowRunner.run(eppMetricBuilder);
assertThat(Splitter.on("\n\t").split(findFirstLogMessageByPrefix(handler, "EPP Command\n\t"))) assertThat(Splitter.on("\n\t").split(findFirstLogMessageByPrefix(handler, "EPP Command\n\t")))
.contains("TlsCredentials{clientCertificateHash=abc123def, clientAddress=/127.0.0.1}"); .contains("TlsCredentials{clientCertificateHash=abc123def, clientAddress=/127.0.0.1}");

View file

@ -14,7 +14,8 @@
package google.registry.flows; package google.registry.flows;
import static com.google.common.truth.Truth.assertThat; import static com.google.common.truth.Truth8.assertThat;
import static google.registry.testing.CertificateSamples.SAMPLE_CERT;
import static google.registry.testing.DatabaseHelper.loadRegistrar; import static google.registry.testing.DatabaseHelper.loadRegistrar;
import static google.registry.testing.DatabaseHelper.persistResource; import static google.registry.testing.DatabaseHelper.persistResource;
import static org.joda.time.DateTimeZone.UTC; import static org.joda.time.DateTimeZone.UTC;
@ -22,9 +23,12 @@ import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when; import static org.mockito.Mockito.when;
import com.google.common.collect.ImmutableSet;
import google.registry.flows.TlsCredentials.BadRegistrarIpAddressException;
import google.registry.flows.TlsCredentials.MissingRegistrarCertificateException;
import google.registry.model.registrar.Registrar; import google.registry.model.registrar.Registrar;
import google.registry.request.HttpException.BadRequestException;
import google.registry.testing.AppEngineExtension; import google.registry.testing.AppEngineExtension;
import google.registry.util.CidrAddressBlock;
import java.util.Optional; import java.util.Optional;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
import org.joda.time.DateTime; import org.joda.time.DateTime;
@ -42,22 +46,40 @@ final class TlsCredentialsTest {
void testProvideClientCertificateHash() { void testProvideClientCertificateHash() {
HttpServletRequest req = mock(HttpServletRequest.class); HttpServletRequest req = mock(HttpServletRequest.class);
when(req.getHeader("X-SSL-Certificate")).thenReturn("data"); when(req.getHeader("X-SSL-Certificate")).thenReturn("data");
assertThat(TlsCredentials.EppTlsModule.provideClientCertificateHash(req)).isEqualTo("data"); assertThat(TlsCredentials.EppTlsModule.provideClientCertificateHash(req)).hasValue("data");
} }
@Test @Test
void testProvideClientCertificateHash_missing() { void testClientCertificateHash_missing() {
HttpServletRequest req = mock(HttpServletRequest.class); TlsCredentials tls = new TlsCredentials(true, Optional.empty(), Optional.of("192.168.1.1"));
BadRequestException thrown = persistResource(
assertThrows( loadRegistrar("TheRegistrar")
BadRequestException.class, .asBuilder()
() -> TlsCredentials.EppTlsModule.provideClientCertificateHash(req)); .setClientCertificate(SAMPLE_CERT, DateTime.now(UTC))
assertThat(thrown).hasMessageThat().contains("Missing header: X-SSL-Certificate"); .build());
assertThrows(
MissingRegistrarCertificateException.class,
() -> tls.validateCertificate(Registrar.loadByClientId("TheRegistrar").get()));
}
@Test
void test_missingIpAddress_doesntAllowAccess() {
TlsCredentials tls = new TlsCredentials(false, Optional.of("certHash"), Optional.empty());
persistResource(
loadRegistrar("TheRegistrar")
.asBuilder()
.setClientCertificate(SAMPLE_CERT, DateTime.now(UTC))
.setIpAddressAllowList(ImmutableSet.of(CidrAddressBlock.create("3.5.8.13")))
.build());
assertThrows(
BadRegistrarIpAddressException.class,
() -> tls.validate(Registrar.loadByClientId("TheRegistrar").get(), "password"));
} }
@Test @Test
void test_validateCertificate_canBeConfiguredToBypassCertHashes() throws Exception { void test_validateCertificate_canBeConfiguredToBypassCertHashes() throws Exception {
TlsCredentials tls = new TlsCredentials(false, "certHash", Optional.of("192.168.1.1")); TlsCredentials tls =
new TlsCredentials(false, Optional.of("certHash"), Optional.of("192.168.1.1"));
persistResource( persistResource(
loadRegistrar("TheRegistrar") loadRegistrar("TheRegistrar")
.asBuilder() .asBuilder()

View file

@ -33,8 +33,10 @@ import org.junit.jupiter.api.Test;
/** Unit tests for {@link LoginFlow} when accessed via a TLS transport. */ /** Unit tests for {@link LoginFlow} when accessed via a TLS transport. */
public class LoginFlowViaTlsTest extends LoginFlowTestCase { public class LoginFlowViaTlsTest extends LoginFlowTestCase {
private static final String GOOD_CERT = CertificateSamples.SAMPLE_CERT_HASH; private static final Optional<String> GOOD_CERT =
private static final String BAD_CERT = CertificateSamples.SAMPLE_CERT2_HASH; Optional.of(CertificateSamples.SAMPLE_CERT_HASH);
private static final Optional<String> BAD_CERT =
Optional.of(CertificateSamples.SAMPLE_CERT2_HASH);
private static final Optional<String> GOOD_IP = Optional.of("192.168.1.1"); private static final Optional<String> GOOD_IP = Optional.of("192.168.1.1");
private static final Optional<String> BAD_IP = Optional.of("1.1.1.1"); private static final Optional<String> BAD_IP = Optional.of("1.1.1.1");
private static final Optional<String> GOOD_IPV6 = Optional.of("2001:db8::1"); private static final Optional<String> GOOD_IPV6 = Optional.of("2001:db8::1");
@ -97,7 +99,7 @@ public class LoginFlowViaTlsTest extends LoginFlowTestCase {
@Test @Test
void testFailure_missingClientCertificateHash() { void testFailure_missingClientCertificateHash() {
persistResource(getRegistrarBuilder().build()); persistResource(getRegistrarBuilder().build());
credentials = new TlsCredentials(true, null, GOOD_IP); credentials = new TlsCredentials(true, Optional.empty(), GOOD_IP);
doFailingTest("login_valid.xml", MissingRegistrarCertificateException.class); doFailingTest("login_valid.xml", MissingRegistrarCertificateException.class);
} }

View file

@ -163,9 +163,9 @@ public final class OteAccountBuilderTest {
.buildAndPersist(); .buildAndPersist();
assertThat(Registrar.loadByClientId("myclientid-3").get().getClientCertificateHash()) assertThat(Registrar.loadByClientId("myclientid-3").get().getClientCertificateHash())
.isEqualTo(SAMPLE_CERT_HASH); .hasValue(SAMPLE_CERT_HASH);
assertThat(Registrar.loadByClientId("myclientid-3").get().getClientCertificate()) assertThat(Registrar.loadByClientId("myclientid-3").get().getClientCertificate())
.isEqualTo(SAMPLE_CERT); .hasValue(SAMPLE_CERT);
} }
@Test @Test

View file

@ -190,18 +190,18 @@ class RegistrarTest extends EntityTestCase {
fakeClock.advanceOneMilli(); fakeClock.advanceOneMilli();
registrar = registrar.asBuilder().setClientCertificate(SAMPLE_CERT, fakeClock.nowUtc()).build(); registrar = registrar.asBuilder().setClientCertificate(SAMPLE_CERT, fakeClock.nowUtc()).build();
assertThat(registrar.getLastCertificateUpdateTime()).isEqualTo(fakeClock.nowUtc()); assertThat(registrar.getLastCertificateUpdateTime()).isEqualTo(fakeClock.nowUtc());
assertThat(registrar.getClientCertificate()).isEqualTo(SAMPLE_CERT); assertThat(registrar.getClientCertificate()).hasValue(SAMPLE_CERT);
assertThat(registrar.getClientCertificateHash()).isEqualTo(SAMPLE_CERT_HASH); assertThat(registrar.getClientCertificateHash()).hasValue(SAMPLE_CERT_HASH);
} }
@TestOfyAndSql @TestOfyAndSql
void testDeleteCertificateHash_alsoDeletesHash() { void testDeleteCertificateHash_alsoDeletesHash() {
assertThat(registrar.getClientCertificateHash()).isNotNull(); assertThat(registrar.getClientCertificateHash()).isPresent();
fakeClock.advanceOneMilli(); fakeClock.advanceOneMilli();
registrar = registrar.asBuilder().setClientCertificate(null, fakeClock.nowUtc()).build(); registrar = registrar.asBuilder().setClientCertificate(null, fakeClock.nowUtc()).build();
assertThat(registrar.getLastCertificateUpdateTime()).isEqualTo(fakeClock.nowUtc()); assertThat(registrar.getLastCertificateUpdateTime()).isEqualTo(fakeClock.nowUtc());
assertThat(registrar.getClientCertificate()).isNull(); assertThat(registrar.getClientCertificate()).isEmpty();
assertThat(registrar.getClientCertificateHash()).isNull(); assertThat(registrar.getClientCertificateHash()).isEmpty();
} }
@TestOfyAndSql @TestOfyAndSql
@ -213,21 +213,21 @@ class RegistrarTest extends EntityTestCase {
.setFailoverClientCertificate(SAMPLE_CERT2, fakeClock.nowUtc()) .setFailoverClientCertificate(SAMPLE_CERT2, fakeClock.nowUtc())
.build(); .build();
assertThat(registrar.getLastCertificateUpdateTime()).isEqualTo(fakeClock.nowUtc()); assertThat(registrar.getLastCertificateUpdateTime()).isEqualTo(fakeClock.nowUtc());
assertThat(registrar.getFailoverClientCertificate()).isEqualTo(SAMPLE_CERT2); assertThat(registrar.getFailoverClientCertificate()).hasValue(SAMPLE_CERT2);
assertThat(registrar.getFailoverClientCertificateHash()).isEqualTo(SAMPLE_CERT2_HASH); assertThat(registrar.getFailoverClientCertificateHash()).hasValue(SAMPLE_CERT2_HASH);
} }
@TestOfyAndSql @TestOfyAndSql
void testDeleteFailoverCertificateHash_alsoDeletesHash() { void testDeleteFailoverCertificateHash_alsoDeletesHash() {
registrar = registrar =
registrar.asBuilder().setFailoverClientCertificate(SAMPLE_CERT, fakeClock.nowUtc()).build(); registrar.asBuilder().setFailoverClientCertificate(SAMPLE_CERT, fakeClock.nowUtc()).build();
assertThat(registrar.getFailoverClientCertificateHash()).isNotNull(); assertThat(registrar.getFailoverClientCertificateHash()).isPresent();
fakeClock.advanceOneMilli(); fakeClock.advanceOneMilli();
registrar = registrar =
registrar.asBuilder().setFailoverClientCertificate(null, fakeClock.nowUtc()).build(); registrar.asBuilder().setFailoverClientCertificate(null, fakeClock.nowUtc()).build();
assertThat(registrar.getLastCertificateUpdateTime()).isEqualTo(fakeClock.nowUtc()); assertThat(registrar.getLastCertificateUpdateTime()).isEqualTo(fakeClock.nowUtc());
assertThat(registrar.getFailoverClientCertificate()).isNull(); assertThat(registrar.getFailoverClientCertificate()).isEmpty();
assertThat(registrar.getFailoverClientCertificateHash()).isNull(); assertThat(registrar.getFailoverClientCertificateHash()).isEmpty();
} }
@TestOfyAndSql @TestOfyAndSql

View file

@ -95,7 +95,7 @@ class CreateRegistrarCommandTest extends CommandTestCase<CreateRegistrarCommand>
assertThat(registrar.getState()).isEqualTo(Registrar.State.ACTIVE); assertThat(registrar.getState()).isEqualTo(Registrar.State.ACTIVE);
assertThat(registrar.getAllowedTlds()).isEmpty(); assertThat(registrar.getAllowedTlds()).isEmpty();
assertThat(registrar.getIpAddressAllowList()).isEmpty(); assertThat(registrar.getIpAddressAllowList()).isEmpty();
assertThat(registrar.getClientCertificateHash()).isNull(); assertThat(registrar.getClientCertificateHash()).isEmpty();
assertThat(registrar.getPhonePasscode()).isEqualTo("01234"); assertThat(registrar.getPhonePasscode()).isEqualTo("01234");
assertThat(registrar.getCreationTime()).isIn(Range.closed(before, after)); assertThat(registrar.getCreationTime()).isIn(Range.closed(before, after));
assertThat(registrar.getLastUpdateTime()).isEqualTo(registrar.getCreationTime()); assertThat(registrar.getLastUpdateTime()).isEqualTo(registrar.getCreationTime());
@ -383,7 +383,7 @@ class CreateRegistrarCommandTest extends CommandTestCase<CreateRegistrarCommand>
Optional<Registrar> registrar = Registrar.loadByClientId("clientz"); Optional<Registrar> registrar = Registrar.loadByClientId("clientz");
assertThat(registrar).isPresent(); assertThat(registrar).isPresent();
assertThat(registrar.get().getClientCertificateHash()).isEqualTo(SAMPLE_CERT3_HASH); assertThat(registrar.get().getClientCertificateHash()).hasValue(SAMPLE_CERT3_HASH);
} }
@Test @Test
@ -467,10 +467,10 @@ class CreateRegistrarCommandTest extends CommandTestCase<CreateRegistrarCommand>
Optional<Registrar> registrarOptional = Registrar.loadByClientId("clientz"); Optional<Registrar> registrarOptional = Registrar.loadByClientId("clientz");
assertThat(registrarOptional).isPresent(); assertThat(registrarOptional).isPresent();
Registrar registrar = registrarOptional.get(); Registrar registrar = registrarOptional.get();
assertThat(registrar.getClientCertificate()).isNull(); assertThat(registrar.getClientCertificate()).isEmpty();
assertThat(registrar.getClientCertificateHash()).isNull(); assertThat(registrar.getClientCertificateHash()).isEmpty();
assertThat(registrar.getFailoverClientCertificate()).isEqualTo(SAMPLE_CERT3); assertThat(registrar.getFailoverClientCertificate()).hasValue(SAMPLE_CERT3);
assertThat(registrar.getFailoverClientCertificateHash()).isEqualTo(SAMPLE_CERT3_HASH); assertThat(registrar.getFailoverClientCertificateHash()).hasValue(SAMPLE_CERT3_HASH);
} }
@Test @Test

View file

@ -15,6 +15,7 @@
package google.registry.tools; package google.registry.tools;
import static com.google.common.truth.Truth.assertThat; import static com.google.common.truth.Truth.assertThat;
import static com.google.common.truth.Truth8.assertThat;
import static google.registry.model.registrar.Registrar.State.ACTIVE; import static google.registry.model.registrar.Registrar.State.ACTIVE;
import static google.registry.model.registry.Registry.TldState.GENERAL_AVAILABILITY; import static google.registry.model.registry.Registry.TldState.GENERAL_AVAILABILITY;
import static google.registry.model.registry.Registry.TldState.START_DATE_SUNRISE; import static google.registry.model.registry.Registry.TldState.START_DATE_SUNRISE;
@ -105,7 +106,7 @@ class SetupOteCommandTest extends CommandTestCase<SetupOteCommand> {
assertThat(registrar.getState()).isEqualTo(ACTIVE); assertThat(registrar.getState()).isEqualTo(ACTIVE);
assertThat(registrar.verifyPassword(password)).isTrue(); assertThat(registrar.verifyPassword(password)).isTrue();
assertThat(registrar.getIpAddressAllowList()).isEqualTo(ipAllowList); assertThat(registrar.getIpAddressAllowList()).isEqualTo(ipAllowList);
assertThat(registrar.getClientCertificateHash()).isEqualTo(SAMPLE_CERT_HASH); assertThat(registrar.getClientCertificateHash()).hasValue(SAMPLE_CERT_HASH);
} }
private void verifyRegistrarContactCreation(String registrarName, String email) { private void verifyRegistrarContactCreation(String registrarName, String email) {

View file

@ -14,7 +14,6 @@
package google.registry.tools; package google.registry.tools;
import static com.google.common.base.Strings.isNullOrEmpty;
import static com.google.common.truth.Truth.assertThat; import static com.google.common.truth.Truth.assertThat;
import static com.google.common.truth.Truth8.assertThat; import static com.google.common.truth.Truth8.assertThat;
import static google.registry.persistence.transaction.TransactionManagerFactory.jpaTm; import static google.registry.persistence.transaction.TransactionManagerFactory.jpaTm;
@ -250,22 +249,22 @@ class UpdateRegistrarCommandTest extends CommandTestCase<UpdateRegistrarCommand>
void testSuccess_certFile() throws Exception { void testSuccess_certFile() throws Exception {
fakeClock.setTo(DateTime.parse("2020-11-01T00:00:00Z")); fakeClock.setTo(DateTime.parse("2020-11-01T00:00:00Z"));
Registrar registrar = loadRegistrar("NewRegistrar"); Registrar registrar = loadRegistrar("NewRegistrar");
assertThat(registrar.getClientCertificate()).isNull(); assertThat(registrar.getClientCertificate()).isEmpty();
assertThat(registrar.getClientCertificateHash()).isNull(); assertThat(registrar.getClientCertificateHash()).isEmpty();
runCommand("--cert_file=" + getCertFilename(SAMPLE_CERT3), "--force", "NewRegistrar"); runCommand("--cert_file=" + getCertFilename(SAMPLE_CERT3), "--force", "NewRegistrar");
registrar = loadRegistrar("NewRegistrar"); registrar = loadRegistrar("NewRegistrar");
// NB: Hash was computed manually using 'openssl x509 -fingerprint -sha256 -in ...' and then // NB: Hash was computed manually using 'openssl x509 -fingerprint -sha256 -in ...' and then
// converting the result from a hex string to non-padded base64 encoded string. // converting the result from a hex string to non-padded base64 encoded string.
assertThat(registrar.getClientCertificate()).isEqualTo(SAMPLE_CERT3); assertThat(registrar.getClientCertificate()).hasValue(SAMPLE_CERT3);
assertThat(registrar.getClientCertificateHash()).isEqualTo(SAMPLE_CERT3_HASH); assertThat(registrar.getClientCertificateHash()).hasValue(SAMPLE_CERT3_HASH);
} }
@Test @Test
void testFail_certFileWithViolation() throws Exception { void testFail_certFileWithViolation() throws Exception {
fakeClock.setTo(DateTime.parse("2020-11-01T00:00:00Z")); fakeClock.setTo(DateTime.parse("2020-11-01T00:00:00Z"));
Registrar registrar = loadRegistrar("NewRegistrar"); Registrar registrar = loadRegistrar("NewRegistrar");
assertThat(registrar.getClientCertificate()).isNull(); assertThat(registrar.getClientCertificate()).isEmpty();
assertThat(registrar.getClientCertificateHash()).isNull(); assertThat(registrar.getClientCertificateHash()).isEmpty();
IllegalArgumentException thrown = IllegalArgumentException thrown =
assertThrows( assertThrows(
IllegalArgumentException.class, IllegalArgumentException.class,
@ -274,15 +273,15 @@ class UpdateRegistrarCommandTest extends CommandTestCase<UpdateRegistrarCommand>
.isEqualTo( .isEqualTo(
"Certificate validity period is too long; it must be less than or equal to 398" "Certificate validity period is too long; it must be less than or equal to 398"
+ " days."); + " days.");
assertThat(registrar.getClientCertificate()).isNull(); assertThat(registrar.getClientCertificate()).isEmpty();
} }
@Test @Test
void testFail_certFileWithMultipleViolations() throws Exception { void testFail_certFileWithMultipleViolations() throws Exception {
fakeClock.setTo(DateTime.parse("2055-10-01T00:00:00Z")); fakeClock.setTo(DateTime.parse("2055-10-01T00:00:00Z"));
Registrar registrar = loadRegistrar("NewRegistrar"); Registrar registrar = loadRegistrar("NewRegistrar");
assertThat(registrar.getClientCertificate()).isNull(); assertThat(registrar.getClientCertificate()).isEmpty();
assertThat(registrar.getClientCertificateHash()).isNull(); assertThat(registrar.getClientCertificateHash()).isEmpty();
IllegalArgumentException thrown = IllegalArgumentException thrown =
assertThrows( assertThrows(
IllegalArgumentException.class, IllegalArgumentException.class,
@ -291,14 +290,14 @@ class UpdateRegistrarCommandTest extends CommandTestCase<UpdateRegistrarCommand>
.isEqualTo( .isEqualTo(
"Certificate is expired.\nCertificate validity period is too long; it must be less" "Certificate is expired.\nCertificate validity period is too long; it must be less"
+ " than or equal to 398 days."); + " than or equal to 398 days.");
assertThat(registrar.getClientCertificate()).isNull(); assertThat(registrar.getClientCertificate()).isEmpty();
} }
@Test @Test
void testFail_failoverCertFileWithViolation() throws Exception { void testFail_failoverCertFileWithViolation() throws Exception {
fakeClock.setTo(DateTime.parse("2020-11-01T00:00:00Z")); fakeClock.setTo(DateTime.parse("2020-11-01T00:00:00Z"));
Registrar registrar = loadRegistrar("NewRegistrar"); Registrar registrar = loadRegistrar("NewRegistrar");
assertThat(registrar.getFailoverClientCertificate()).isNull(); assertThat(registrar.getFailoverClientCertificate()).isEmpty();
IllegalArgumentException thrown = IllegalArgumentException thrown =
assertThrows( assertThrows(
IllegalArgumentException.class, IllegalArgumentException.class,
@ -308,14 +307,14 @@ class UpdateRegistrarCommandTest extends CommandTestCase<UpdateRegistrarCommand>
.isEqualTo( .isEqualTo(
"Certificate validity period is too long; it must be less than or equal to 398" "Certificate validity period is too long; it must be less than or equal to 398"
+ " days."); + " days.");
assertThat(registrar.getFailoverClientCertificate()).isNull(); assertThat(registrar.getFailoverClientCertificate()).isEmpty();
} }
@Test @Test
void testFail_failoverCertFileWithMultipleViolations() throws Exception { void testFail_failoverCertFileWithMultipleViolations() throws Exception {
fakeClock.setTo(DateTime.parse("2055-10-01T00:00:00Z")); fakeClock.setTo(DateTime.parse("2055-10-01T00:00:00Z"));
Registrar registrar = loadRegistrar("NewRegistrar"); Registrar registrar = loadRegistrar("NewRegistrar");
assertThat(registrar.getFailoverClientCertificate()).isNull(); assertThat(registrar.getFailoverClientCertificate()).isEmpty();
IllegalArgumentException thrown = IllegalArgumentException thrown =
assertThrows( assertThrows(
IllegalArgumentException.class, IllegalArgumentException.class,
@ -325,17 +324,17 @@ class UpdateRegistrarCommandTest extends CommandTestCase<UpdateRegistrarCommand>
.isEqualTo( .isEqualTo(
"Certificate is expired.\nCertificate validity period is too long; it must be less" "Certificate is expired.\nCertificate validity period is too long; it must be less"
+ " than or equal to 398 days."); + " than or equal to 398 days.");
assertThat(registrar.getFailoverClientCertificate()).isNull(); assertThat(registrar.getFailoverClientCertificate()).isEmpty();
} }
@Test @Test
void testSuccess_failoverCertFile() throws Exception { void testSuccess_failoverCertFile() throws Exception {
fakeClock.setTo(DateTime.parse("2020-11-01T00:00:00Z")); fakeClock.setTo(DateTime.parse("2020-11-01T00:00:00Z"));
Registrar registrar = loadRegistrar("NewRegistrar"); Registrar registrar = loadRegistrar("NewRegistrar");
assertThat(registrar.getFailoverClientCertificate()).isNull(); assertThat(registrar.getFailoverClientCertificate()).isEmpty();
runCommand("--failover_cert_file=" + getCertFilename(SAMPLE_CERT3), "--force", "NewRegistrar"); runCommand("--failover_cert_file=" + getCertFilename(SAMPLE_CERT3), "--force", "NewRegistrar");
registrar = loadRegistrar("NewRegistrar"); registrar = loadRegistrar("NewRegistrar");
assertThat(registrar.getFailoverClientCertificate()).isEqualTo(SAMPLE_CERT3); assertThat(registrar.getFailoverClientCertificate()).hasValue(SAMPLE_CERT3);
} }
@Test @Test
@ -345,9 +344,9 @@ class UpdateRegistrarCommandTest extends CommandTestCase<UpdateRegistrarCommand>
.asBuilder() .asBuilder()
.setClientCertificate(SAMPLE_CERT, DateTime.now(UTC)) .setClientCertificate(SAMPLE_CERT, DateTime.now(UTC))
.build()); .build());
assertThat(isNullOrEmpty(loadRegistrar("NewRegistrar").getClientCertificate())).isFalse(); assertThat(loadRegistrar("NewRegistrar").getClientCertificate()).isPresent();
runCommand("--cert_file=/dev/null", "--force", "NewRegistrar"); runCommand("--cert_file=/dev/null", "--force", "NewRegistrar");
assertThat(loadRegistrar("NewRegistrar").getClientCertificate()).isNull(); assertThat(loadRegistrar("NewRegistrar").getClientCertificate()).isEmpty();
} }
@Test @Test

View file

@ -371,7 +371,7 @@ class RegistrarSettingsActionTest extends RegistrarSettingsActionTestCase {
clock.setTo(DateTime.parse("2020-11-02T00:00:00Z")); clock.setTo(DateTime.parse("2020-11-02T00:00:00Z"));
doTestUpdate( doTestUpdate(
Role.OWNER, Role.OWNER,
Registrar::getClientCertificate, r -> r.getClientCertificate().orElse(null),
CertificateSamples.SAMPLE_CERT3, CertificateSamples.SAMPLE_CERT3,
(builder, s) -> builder.setClientCertificate(s, clock.nowUtc())); (builder, s) -> builder.setClientCertificate(s, clock.nowUtc()));
} }
@ -431,7 +431,7 @@ class RegistrarSettingsActionTest extends RegistrarSettingsActionTestCase {
clock.setTo(DateTime.parse("2020-11-02T00:00:00Z")); clock.setTo(DateTime.parse("2020-11-02T00:00:00Z"));
doTestUpdate( doTestUpdate(
Role.OWNER, Role.OWNER,
Registrar::getFailoverClientCertificate, r -> r.getFailoverClientCertificate().orElse(null),
CertificateSamples.SAMPLE_CERT3, CertificateSamples.SAMPLE_CERT3,
(builder, s) -> builder.setFailoverClientCertificate(s, clock.nowUtc())); (builder, s) -> builder.setFailoverClientCertificate(s, clock.nowUtc()));
} }

View file

@ -15,6 +15,7 @@
package google.registry.ui.server.registrar; package google.registry.ui.server.registrar;
import static com.google.common.truth.Truth.assertThat; import static com.google.common.truth.Truth.assertThat;
import static com.google.common.truth.Truth8.assertThat;
import static google.registry.testing.CertificateSamples.SAMPLE_CERT; import static google.registry.testing.CertificateSamples.SAMPLE_CERT;
import static google.registry.testing.CertificateSamples.SAMPLE_CERT2; import static google.registry.testing.CertificateSamples.SAMPLE_CERT2;
import static google.registry.testing.CertificateSamples.SAMPLE_CERT2_HASH; import static google.registry.testing.CertificateSamples.SAMPLE_CERT2_HASH;
@ -121,10 +122,10 @@ class SecuritySettingsTest extends RegistrarSettingsActionTestCase {
"op", "update", "id", CLIENT_ID, "args", jsonMap)); "op", "update", "id", CLIENT_ID, "args", jsonMap));
assertThat(response).containsEntry("status", "SUCCESS"); assertThat(response).containsEntry("status", "SUCCESS");
Registrar registrar = loadRegistrar(CLIENT_ID); Registrar registrar = loadRegistrar(CLIENT_ID);
assertThat(registrar.getClientCertificate()).isEqualTo(SAMPLE_CERT3); assertThat(registrar.getClientCertificate()).hasValue(SAMPLE_CERT3);
assertThat(registrar.getClientCertificateHash()).isEqualTo(SAMPLE_CERT3_HASH); assertThat(registrar.getClientCertificateHash()).hasValue(SAMPLE_CERT3_HASH);
assertThat(registrar.getFailoverClientCertificate()).isNull(); assertThat(registrar.getFailoverClientCertificate()).isEmpty();
assertThat(registrar.getFailoverClientCertificateHash()).isNull(); assertThat(registrar.getFailoverClientCertificateHash()).isEmpty();
assertMetric(CLIENT_ID, "update", "[OWNER]", "SUCCESS"); assertMetric(CLIENT_ID, "update", "[OWNER]", "SUCCESS");
verifyNotificationEmailsSent(); verifyNotificationEmailsSent();
} }
@ -138,8 +139,8 @@ class SecuritySettingsTest extends RegistrarSettingsActionTestCase {
"op", "update", "id", CLIENT_ID, "args", jsonMap)); "op", "update", "id", CLIENT_ID, "args", jsonMap));
assertThat(response).containsEntry("status", "SUCCESS"); assertThat(response).containsEntry("status", "SUCCESS");
Registrar registrar = loadRegistrar(CLIENT_ID); Registrar registrar = loadRegistrar(CLIENT_ID);
assertThat(registrar.getFailoverClientCertificate()).isEqualTo(SAMPLE_CERT3); assertThat(registrar.getFailoverClientCertificate()).hasValue(SAMPLE_CERT3);
assertThat(registrar.getFailoverClientCertificateHash()).isEqualTo(SAMPLE_CERT3_HASH); assertThat(registrar.getFailoverClientCertificateHash()).hasValue(SAMPLE_CERT3_HASH);
assertMetric(CLIENT_ID, "update", "[OWNER]", "SUCCESS"); assertMetric(CLIENT_ID, "update", "[OWNER]", "SUCCESS");
verifyNotificationEmailsSent(); verifyNotificationEmailsSent();
} }
@ -160,10 +161,10 @@ class SecuritySettingsTest extends RegistrarSettingsActionTestCase {
"op", "update", "id", CLIENT_ID, "args", jsonMap)); "op", "update", "id", CLIENT_ID, "args", jsonMap));
assertThat(response).containsEntry("status", "SUCCESS"); assertThat(response).containsEntry("status", "SUCCESS");
Registrar registrar = loadRegistrar(CLIENT_ID); Registrar registrar = loadRegistrar(CLIENT_ID);
assertThat(registrar.getClientCertificate()).isEqualTo(SAMPLE_CERT); assertThat(registrar.getClientCertificate()).hasValue(SAMPLE_CERT);
assertThat(registrar.getClientCertificateHash()).isEqualTo(SAMPLE_CERT_HASH); assertThat(registrar.getClientCertificateHash()).hasValue(SAMPLE_CERT_HASH);
assertThat(registrar.getFailoverClientCertificate()).isEqualTo(SAMPLE_CERT2); assertThat(registrar.getFailoverClientCertificate()).hasValue(SAMPLE_CERT2);
assertThat(registrar.getFailoverClientCertificateHash()).isEqualTo(SAMPLE_CERT2_HASH); assertThat(registrar.getFailoverClientCertificateHash()).hasValue(SAMPLE_CERT2_HASH);
assertMetric(CLIENT_ID, "update", "[OWNER]", "SUCCESS"); assertMetric(CLIENT_ID, "update", "[OWNER]", "SUCCESS");
} }