diff --git a/core/src/main/java/google/registry/flows/domain/DomainFlowUtils.java b/core/src/main/java/google/registry/flows/domain/DomainFlowUtils.java index 046acc8dcb0..e891ba9fbd3 100644 --- a/core/src/main/java/google/registry/flows/domain/DomainFlowUtils.java +++ b/core/src/main/java/google/registry/flows/domain/DomainFlowUtils.java @@ -47,9 +47,9 @@ import static google.registry.util.DateTimeUtils.minusDays; import static google.registry.util.DateTimeUtils.plusYears; import static google.registry.util.DomainNameUtils.ACE_PREFIX; +import static google.registry.util.DomainNameUtils.ALLOWED_CHARS; import static java.util.stream.Collectors.joining; -import com.google.common.base.CharMatcher; import com.google.common.base.Joiner; import com.google.common.base.Splitter; import com.google.common.base.Strings; @@ -160,10 +160,6 @@ public class DomainFlowUtils { + "delegated. Please visit https://www.icann.org/namecollision for more information on " + "name collision."; - /** Strict validator for ascii lowercase letters, digits, and "-", allowing "." as a separator */ - private static final CharMatcher ALLOWED_CHARS = - CharMatcher.inRange('a', 'z').or(CharMatcher.inRange('0', '9').or(CharMatcher.anyOf("-."))); - /** Default validator used to determine if an IDN name can be provisioned on a TLD. */ private static final IdnLabelValidator IDN_LABEL_VALIDATOR = new IdnLabelValidator(); diff --git a/core/src/main/java/google/registry/model/registrar/Registrar.java b/core/src/main/java/google/registry/model/registrar/Registrar.java index 8f5618eb5e0..b82ce0d2b59 100644 --- a/core/src/main/java/google/registry/model/registrar/Registrar.java +++ b/core/src/main/java/google/registry/model/registrar/Registrar.java @@ -32,6 +32,7 @@ import static google.registry.util.CollectionUtils.nullToEmptyImmutableCopy; import static google.registry.util.CollectionUtils.nullToEmptyImmutableSortedCopy; import static google.registry.util.DateTimeUtils.START_INSTANT; +import static google.registry.util.DomainNameUtils.canonicalizeAndValidateHostname; import static google.registry.util.PasswordUtils.SALT_SUPPLIER; import static google.registry.util.PasswordUtils.hashPassword; import static google.registry.util.PreconditionsUtils.checkArgumentNotNull; @@ -185,6 +186,12 @@ public enum State { /** Regex for E.164 phone number format. */ private static final Pattern E164_PATTERN = Pattern.compile("\\+[0-9]{1,3}\\.[0-9]{1,14}"); + /** Maximum number of hostnames in the EPP client certificate allowlist. */ + public static final int MAX_EPP_CLIENT_CERTIFICATE_HOSTNAMES = 20; + + /** Maximum number of revoked client certificate hashes. */ + public static final int MAX_REVOKED_CLIENT_CERTIFICATE_HASHES = 20; + /** Regex for telephone support passcode (5 digit string). */ public static final Pattern PHONE_PASSCODE_PATTERN = Pattern.compile("\\d{5}"); @@ -295,6 +302,27 @@ public enum State { /** Base64 encoded SHA256 hash of {@link #failoverClientCertificate}. */ String failoverClientCertificateHash; + /** + * Hostnames for which a client certificate issued by a publicly trusted CA is accepted at EPP + * login, as an alternative to the pinned {@link #clientCertificate}. + * + *

Entries are stored in canonical A-label (punycode) lowercase form without a trailing dot. + * They are only consulted while the {@code ALLOW_EPP_CLIENT_CERT_HOSTNAME_AUTH} feature flag is + * active. + */ + @GetterDelegate(methodName = "getAllowedEppClientCertificateHostnames") + @Expose + Set allowedEppClientCertificateHostnames; + + /** + * Base64 encoded SHA256 hashes of client certificates the registrar has revoked, in the same form + * as {@link #clientCertificateHash}. A certificate with one of these hashes is rejected at EPP + * login regardless of which mechanism would otherwise have accepted it. + */ + @GetterDelegate(methodName = "getRevokedClientCertificateHashes") + @Expose + Set revokedClientCertificateHashes; + /** An allow list of netmasks (in CIDR notation) which the client is allowed to connect from. */ @org.hibernate.annotations.Type(CidrBlockListUserType.class) @Column(columnDefinition = "text[]") @@ -540,6 +568,14 @@ public ImmutableList getIpAddressAllowList() { return nullToEmptyImmutableCopy(ipAddressAllowList); } + public ImmutableSortedSet getAllowedEppClientCertificateHostnames() { + return nullToEmptyImmutableSortedCopy(allowedEppClientCertificateHostnames); + } + + public ImmutableSortedSet getRevokedClientCertificateHashes() { + return nullToEmptyImmutableSortedCopy(revokedClientCertificateHashes); + } + public RegistrarAddress getLocalizedAddress() { return localizedAddress; } @@ -662,6 +698,9 @@ public Map toJsonMap() { .put("clientCertificateHash", clientCertificateHash) .put("failoverClientCertificate", failoverClientCertificate) .put("failoverClientCertificateHash", failoverClientCertificateHash) + .putListOfStrings( + "allowedEppClientCertificateHostnames", getAllowedEppClientCertificateHostnames()) + .putListOfStrings("revokedClientCertificateHashes", getRevokedClientCertificateHashes()) .put("localizedAddress", localizedAddress) .put("internationalizedAddress", internationalizedAddress) .put("phoneNumber", phoneNumber) @@ -853,6 +892,60 @@ public Builder setLastPocVerificationDate(Instant now) { return this; } + /** + * Sets the hostnames for which CA-issued client certificates are accepted at EPP login. + * + *

Each entry is canonicalized to lowercase A-label (punycode) form and validated as a + * multi-label DNS name; duplicates collapse to one entry. + */ + public Builder setAllowedEppClientCertificateHostnames(Iterable hostnames) { + checkArgumentNotNull(hostnames, "EPP client certificate hostnames cannot be null"); + ImmutableSortedSet validated = + stream(hostnames) + .map( + hostname -> + canonicalizeAndValidateHostname( + checkArgumentNotNull( + hostname, "EPP client certificate hostname cannot be null"))) + .collect(toImmutableSortedSet(Comparator.naturalOrder())); + checkArgument( + validated.size() <= MAX_EPP_CLIENT_CERTIFICATE_HOSTNAMES, + "At most %s EPP client certificate hostnames may be configured, got %s", + MAX_EPP_CLIENT_CERTIFICATE_HOSTNAMES, + validated.size()); + getInstance().allowedEppClientCertificateHostnames = validated; + return this; + } + + /** Sets the hashes of client certificates that are rejected at EPP login. */ + public Builder setRevokedClientCertificateHashes(Iterable hashes) { + checkArgumentNotNull(hashes, "Revoked client certificate hashes cannot be null"); + ImmutableSortedSet validated = + stream(hashes) + .map( + hash -> { + checkArgumentNotNull(hash, "Revoked client certificate hash cannot be null"); + checkArgument( + base64().omitPadding().canDecode(hash), + "Invalid base64 SHA-256 certificate hash: %s", + hash); + byte[] decoded = base64().omitPadding().decode(hash); + checkArgument( + decoded.length == 32 && base64().omitPadding().encode(decoded).equals(hash), + "Invalid base64 SHA-256 certificate hash: %s", + hash); + return hash; + }) + .collect(toImmutableSortedSet(Comparator.naturalOrder())); + checkArgument( + validated.size() <= MAX_REVOKED_CLIENT_CERTIFICATE_HASHES, + "At most %s revoked client certificates may be configured, got %s", + MAX_REVOKED_CLIENT_CERTIFICATE_HASHES, + validated.size()); + getInstance().revokedClientCertificateHashes = validated; + return this; + } + private static String calculateHash(String clientCertificate) { if (clientCertificate == null) { return null; diff --git a/core/src/main/java/google/registry/ui/server/console/settings/SecurityAction.java b/core/src/main/java/google/registry/ui/server/console/settings/SecurityAction.java index 392664269ba..391aeb4abfa 100644 --- a/core/src/main/java/google/registry/ui/server/console/settings/SecurityAction.java +++ b/core/src/main/java/google/registry/ui/server/console/settings/SecurityAction.java @@ -22,6 +22,9 @@ import static jakarta.servlet.http.HttpServletResponse.SC_OK; import com.google.common.collect.ImmutableSet; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonSyntaxException; import google.registry.flows.certs.CertificateChecker; import google.registry.flows.certs.CertificateChecker.InsecureCertificateException; import google.registry.model.console.ConsolePermission; @@ -30,6 +33,7 @@ import google.registry.model.registrar.Registrar; import google.registry.request.Action; import google.registry.request.Action.Service; +import google.registry.request.OptionalJsonPayload; import google.registry.request.Parameter; import google.registry.request.auth.Auth; import google.registry.request.auth.AuthenticatedRegistrarAccessor; @@ -50,7 +54,7 @@ public class SecurityAction extends ConsoleApiAction { static final String PATH = "/console-api/settings/security"; private final String registrarId; private final AuthenticatedRegistrarAccessor registrarAccessor; - private final Optional registrar; + private final Optional payload; private final CertificateChecker certificateChecker; @Inject @@ -59,18 +63,19 @@ public SecurityAction( CertificateChecker certificateChecker, AuthenticatedRegistrarAccessor registrarAccessor, @Parameter("registrarId") String registrarId, - @Parameter("registrar") Optional registrar) { + @OptionalJsonPayload Optional payload) { super(consoleApiParams); this.registrarId = registrarId; this.registrarAccessor = registrarAccessor; - this.registrar = registrar; + this.payload = payload; this.certificateChecker = certificateChecker; } @Override protected void postHandler(User user) { checkPermission(user, registrarId, ConsolePermission.EDIT_REGISTRAR_DETAILS); - checkArgument(registrar.isPresent(), "'registrar' parameter is not present"); + checkArgument(payload.isPresent(), "'registrar' parameter is not present"); + checkArgument(payload.get().isJsonObject(), "'registrar' parameter must be a JSON object"); Registrar savedRegistrar; try { @@ -84,18 +89,45 @@ protected void postHandler(User user) { } private void setResponse(Registrar savedRegistrar) { - Registrar registrarParameter = registrar.get(); + JsonObject jsonObject = payload.get().getAsJsonObject(); Registrar.Builder updatedRegistrarBuilder = savedRegistrar.asBuilder(); StringJoiner updates = new StringJoiner(","); - if (!savedRegistrar - .getIpAddressAllowList() - .equals(registrarParameter.getIpAddressAllowList())) { - updatedRegistrarBuilder.setIpAddressAllowList(registrarParameter.getIpAddressAllowList()); - updates.add("IP_CHANGE"); - } - + boolean hasHostnames = isFieldPresent(jsonObject, "allowedEppClientCertificateHostnames"); + boolean hasRevokedHashes = isFieldPresent(jsonObject, "revokedClientCertificateHashes"); try { + if (hasHostnames) { + checkStringArrayElements( + jsonObject, + "allowedEppClientCertificateHostnames", + "EPP client certificate hostname cannot be null"); + } + if (hasRevokedHashes) { + checkStringArrayElements( + jsonObject, + "revokedClientCertificateHashes", + "Revoked client certificate hash cannot be null"); + } + Registrar registrarParameter = consoleApiParams.gson().fromJson(jsonObject, Registrar.class); + + if (!savedRegistrar + .getIpAddressAllowList() + .equals(registrarParameter.getIpAddressAllowList())) { + updatedRegistrarBuilder.setIpAddressAllowList(registrarParameter.getIpAddressAllowList()); + updates.add("IP_CHANGE"); + } + if (hasHostnames) { + checkArgument( + !registrarParameter.getAllowedEppClientCertificateHostnames().isEmpty() + || savedRegistrar.getAllowedEppClientCertificateHostnames().isEmpty(), + "Cannot clear allowed EPP client certificate hostnames once configured"); + updatedRegistrarBuilder.setAllowedEppClientCertificateHostnames( + registrarParameter.getAllowedEppClientCertificateHostnames()); + } + if (hasRevokedHashes) { + updatedRegistrarBuilder.setRevokedClientCertificateHashes( + registrarParameter.getRevokedClientCertificateHashes()); + } if (!savedRegistrar .getClientCertificate() .equals(registrarParameter.getClientCertificate())) { @@ -116,12 +148,22 @@ private void setResponse(Registrar savedRegistrar) { updates.add("FAILOVER_SSL_CERT_CHANGE"); } } - } catch (InsecureCertificateException e) { + } catch (InsecureCertificateException | IllegalArgumentException | JsonSyntaxException e) { setFailedResponse(e.getMessage(), SC_BAD_REQUEST); return; } Registrar updatedRegistrar = updatedRegistrarBuilder.build(); + if (!savedRegistrar + .getAllowedEppClientCertificateHostnames() + .equals(updatedRegistrar.getAllowedEppClientCertificateHostnames())) { + updates.add("EPP_CERT_HOSTNAMES_CHANGE"); + } + if (!savedRegistrar + .getRevokedClientCertificateHashes() + .equals(updatedRegistrar.getRevokedClientCertificateHashes())) { + updates.add("REVOKED_CERTS_CHANGE"); + } tm().put(updatedRegistrar); finishAndPersistConsoleUpdateHistory( new ConsoleUpdateHistory.Builder() @@ -134,4 +176,21 @@ private void setResponse(Registrar savedRegistrar) { EmailInfo.create(savedRegistrar, updatedRegistrar, ImmutableSet.of(), ImmutableSet.of())); consoleApiParams.response().setStatus(SC_OK); } + + private static boolean isFieldPresent(JsonObject jsonObject, String fieldName) { + return jsonObject.has(fieldName) && !jsonObject.get(fieldName).isJsonNull(); + } + + private static void checkStringArrayElements( + JsonObject jsonObject, String fieldName, String nullElementErrorMessage) { + JsonElement field = jsonObject.get(fieldName); + checkArgument(field.isJsonArray(), "'%s' must be a JSON array", fieldName); + for (JsonElement element : field.getAsJsonArray()) { + checkArgument(!element.isJsonNull(), nullElementErrorMessage); + checkArgument( + element.isJsonPrimitive() && element.getAsJsonPrimitive().isString(), + "'%s' elements must be strings", + fieldName); + } + } } diff --git a/core/src/test/java/google/registry/model/registrar/RegistrarTest.java b/core/src/test/java/google/registry/model/registrar/RegistrarTest.java index b92ef9cdcc3..e0dacc2bd2d 100644 --- a/core/src/test/java/google/registry/model/registrar/RegistrarTest.java +++ b/core/src/test/java/google/registry/model/registrar/RegistrarTest.java @@ -46,9 +46,11 @@ import google.registry.model.tld.Tlds; import google.registry.testing.DatabaseHelper; import google.registry.util.CidrAddressBlock; +import google.registry.util.DiffUtils; import google.registry.util.SerializeUtils; import java.math.BigDecimal; import java.time.Instant; +import java.util.Arrays; import org.joda.money.CurrencyUnit; import org.joda.money.Money; import org.junit.jupiter.api.BeforeEach; @@ -802,4 +804,306 @@ void testSuccess_toJsonMap_includesExpiryAccessPeriodEnabled() { Registrar modified = registrar.asBuilder().setExpiryAccessPeriodEnabled(true).build(); assertThat(modified.toJsonMap()).containsEntry("expiryAccessPeriodEnabled", true); } + + @Test + void testSuccess_eppClientCertificateHostnames_defaultEmpty() { + assertThat(registrar.getAllowedEppClientCertificateHostnames()).isEmpty(); + assertThat(registrar.toJsonMap()) + .containsEntry("allowedEppClientCertificateHostnames", ImmutableList.of()); + } + + @Test + void testSuccess_eppClientCertificateHostnames_persistence() { + persistResource( + registrar + .asBuilder() + .setAllowedEppClientCertificateHostnames( + ImmutableList.of("epp.registrar.example", "epp2.registrar.example")) + .build()); + Registrar loaded = Registrar.loadByRegistrarId("registrar").get(); + assertThat(loaded.getAllowedEppClientCertificateHostnames()) + .containsExactly("epp.registrar.example", "epp2.registrar.example"); + assertThat((Iterable) loaded.toJsonMap().get("allowedEppClientCertificateHostnames")) + .containsExactly("epp.registrar.example", "epp2.registrar.example"); + } + + @Test + void testSuccess_eppClientCertificateHostnames_canonicalizedAndDeduplicated() { + Registrar modified = + registrar + .asBuilder() + .setAllowedEppClientCertificateHostnames( + ImmutableList.of( + "EPP.Example.COM", + "epp.example.com", + "Epp.Example.Com", + "COM.Google.Registrar.", + "b.example", + "epp.みんな")) + .build(); + assertThat(modified.getAllowedEppClientCertificateHostnames()) + .containsExactly("b.example", "com.google.registrar", "epp.example.com", "epp.xn--q9jyb4c") + .inOrder(); + } + + @Test + void testSuccess_eppClientCertificateHostnames_clearing() { + registrar = + registrar + .asBuilder() + .setAllowedEppClientCertificateHostnames(ImmutableList.of("epp.registrar.example")) + .build(); + registrar = + registrar.asBuilder().setAllowedEppClientCertificateHostnames(ImmutableList.of()).build(); + assertThat(registrar.getAllowedEppClientCertificateHostnames()).isEmpty(); + assertThat(registrar.allowedEppClientCertificateHostnames).isNull(); + } + + @Test + void testSuccess_eppClientCertificateHostnames_acceptsIdnALabelAndLongNames() { + String longLabel = "a".repeat(63); + Registrar modified = + registrar + .asBuilder() + .setAllowedEppClientCertificateHostnames( + ImmutableList.of( + "xn--q9jyb4c.registrar.example", + "epp.xn--q9jyb4c", + longLabel + ".example", + "a-b.c-d.example")) + .build(); + assertThat(modified.getAllowedEppClientCertificateHostnames()).hasSize(4); + } + + @Test + void testFailure_eppClientCertificateHostnames_invalidNames() { + ImmutableList invalid = + ImmutableList.of( + "", + "epp", + "epp.", + "*.registrar.example", + "https://epp.registrar.example", + "epp.registrar.example:700", + "epp.registrar.example/path", + "192.0.2.1", + "2001:db8::1", + "epp_1.registrar.example", + "-epp.registrar.example", + "epp-.registrar.example", + "epp.registrar.ex ample", + "a".repeat(64) + ".example", + ("a".repeat(63) + ".").repeat(4) + "example"); + for (String hostname : invalid) { + assertThrows( + IllegalArgumentException.class, + () -> + registrar + .asBuilder() + .setAllowedEppClientCertificateHostnames(ImmutableList.of(hostname))); + } + } + + @Test + void testSuccess_eppClientCertificateHostnames_maxBoundary() { + ImmutableList.Builder hostnames = new ImmutableList.Builder<>(); + for (int i = 0; i < Registrar.MAX_EPP_CLIENT_CERTIFICATE_HOSTNAMES; i++) { + hostnames.add(String.format("epp%d.registrar.example", i)); + } + Registrar modified = + registrar.asBuilder().setAllowedEppClientCertificateHostnames(hostnames.build()).build(); + assertThat(modified.getAllowedEppClientCertificateHostnames()) + .hasSize(Registrar.MAX_EPP_CLIENT_CERTIFICATE_HOSTNAMES); + } + + @Test + void testFailure_eppClientCertificateHostnames_tooMany() { + ImmutableList.Builder hostnames = new ImmutableList.Builder<>(); + for (int i = 0; i <= Registrar.MAX_EPP_CLIENT_CERTIFICATE_HOSTNAMES; i++) { + hostnames.add(String.format("epp%d.registrar.example", i)); + } + IllegalArgumentException thrown = + assertThrows( + IllegalArgumentException.class, + () -> registrar.asBuilder().setAllowedEppClientCertificateHostnames(hostnames.build())); + assertThat(thrown) + .hasMessageThat() + .contains("At most 20 EPP client certificate hostnames may be configured, got 21"); + } + + @Test + void testFailure_eppClientCertificateHostnames_null() { + assertThrows( + IllegalArgumentException.class, + () -> registrar.asBuilder().setAllowedEppClientCertificateHostnames(null)); + assertThrows( + IllegalArgumentException.class, + () -> + registrar + .asBuilder() + .setAllowedEppClientCertificateHostnames( + Arrays.asList("epp.registrar.example", null))); + } + + @Test + void testSuccess_revokedClientCertificateHashes_defaultEmpty() { + assertThat(registrar.getRevokedClientCertificateHashes()).isEmpty(); + assertThat(registrar.toJsonMap()) + .containsEntry("revokedClientCertificateHashes", ImmutableList.of()); + } + + @Test + void testSuccess_revokedClientCertificateHashes_persistence() { + persistResource( + registrar + .asBuilder() + .setRevokedClientCertificateHashes( + ImmutableList.of(SAMPLE_CERT_HASH, SAMPLE_CERT2_HASH)) + .build()); + Registrar loaded = Registrar.loadByRegistrarId("registrar").get(); + assertThat(loaded.getRevokedClientCertificateHashes()) + .containsExactly(SAMPLE_CERT_HASH, SAMPLE_CERT2_HASH); + assertThat((Iterable) loaded.toJsonMap().get("revokedClientCertificateHashes")) + .containsExactly(SAMPLE_CERT_HASH, SAMPLE_CERT2_HASH); + } + + @Test + void testSuccess_revokedClientCertificateHashes_deduplicated() { + Registrar modified = + registrar + .asBuilder() + .setRevokedClientCertificateHashes(ImmutableList.of(SAMPLE_CERT_HASH, SAMPLE_CERT_HASH)) + .build(); + assertThat(modified.getRevokedClientCertificateHashes()).containsExactly(SAMPLE_CERT_HASH); + } + + @Test + void testSuccess_revokedClientCertificateHashes_clearing() { + registrar = + registrar + .asBuilder() + .setRevokedClientCertificateHashes(ImmutableList.of(SAMPLE_CERT_HASH)) + .build(); + registrar = registrar.asBuilder().setRevokedClientCertificateHashes(ImmutableList.of()).build(); + assertThat(registrar.getRevokedClientCertificateHashes()).isEmpty(); + assertThat(registrar.revokedClientCertificateHashes).isNull(); + } + + @Test + void testSuccess_revokedClientCertificateHashes_maxBoundary() { + ImmutableList.Builder hashes = new ImmutableList.Builder<>(); + for (int i = 0; i < Registrar.MAX_REVOKED_CLIENT_CERTIFICATE_HASHES; i++) { + hashes.add((char) ('A' + i) + SAMPLE_CERT_HASH.substring(1)); + } + Registrar modified = + registrar.asBuilder().setRevokedClientCertificateHashes(hashes.build()).build(); + assertThat(modified.getRevokedClientCertificateHashes()) + .hasSize(Registrar.MAX_REVOKED_CLIENT_CERTIFICATE_HASHES); + } + + @Test + void testFailure_revokedClientCertificateHashes_tooMany() { + ImmutableList.Builder hashes = new ImmutableList.Builder<>(); + for (int i = 0; i <= Registrar.MAX_REVOKED_CLIENT_CERTIFICATE_HASHES; i++) { + // Vary the first character to produce distinct, well-formed hashes. + hashes.add((char) ('A' + i) + SAMPLE_CERT_HASH.substring(1)); + } + IllegalArgumentException thrown = + assertThrows( + IllegalArgumentException.class, + () -> registrar.asBuilder().setRevokedClientCertificateHashes(hashes.build())); + assertThat(thrown) + .hasMessageThat() + .contains("At most 20 revoked client certificates may be configured, got 21"); + } + + @Test + void testFailure_revokedClientCertificateHashes_null() { + assertThrows( + IllegalArgumentException.class, + () -> registrar.asBuilder().setRevokedClientCertificateHashes(null)); + assertThrows( + IllegalArgumentException.class, + () -> + registrar + .asBuilder() + .setRevokedClientCertificateHashes(Arrays.asList(SAMPLE_CERT_HASH, null))); + } + + @Test + void testFailure_revokedClientCertificateHashes_invalidFormat() { + ImmutableList invalidHashes = + ImmutableList.of( + "", + "not-base64!", + "AAAA", + SAMPLE_CERT_HASH + "=", + "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAB", + "AA:BB:CC:DD:EE:FF:00:11:22:33:44:55:66:77:88:99:AA:BB:CC:DD:EE:FF:00:11:22:33:44:55:66:77:88:99", + SAMPLE_CERT); + for (String invalidHash : invalidHashes) { + IllegalArgumentException thrown = + assertThrows( + IllegalArgumentException.class, + () -> + registrar + .asBuilder() + .setRevokedClientCertificateHashes(ImmutableList.of(invalidHash))); + assertThat(thrown).hasMessageThat().contains("Invalid base64 SHA-256 certificate hash"); + } + } + + @Test + void testSuccess_eppClientCertificateHostnamesAndRevokedHashes_diffableFieldMap() { + assertThat(registrar.toDiffableFieldMap()) + .containsEntry("allowedEppClientCertificateHostnames", ImmutableSortedSet.of()); + assertThat(registrar.toDiffableFieldMap()) + .containsEntry("revokedClientCertificateHashes", ImmutableSortedSet.of()); + Registrar modified = + registrar + .asBuilder() + .setAllowedEppClientCertificateHostnames(ImmutableList.of("epp.registrar.example")) + .setRevokedClientCertificateHashes(ImmutableList.of(SAMPLE_CERT_HASH)) + .build(); + String diff = + DiffUtils.prettyPrintDiffedMap( + DiffUtils.deepDiff(registrar.toDiffableFieldMap(), modified.toDiffableFieldMap(), true), + null); + assertThat(diff) + .contains( + """ + allowedEppClientCertificateHostnames: + ADDED: [epp.registrar.example] + FINAL CONTENTS: [epp.registrar.example] + """); + assertThat(diff) + .contains( + String.format( + """ + revokedClientCertificateHashes: + ADDED: [%s] + FINAL CONTENTS: [%s] + """, + SAMPLE_CERT_HASH, SAMPLE_CERT_HASH)); + String reverseDiff = + DiffUtils.prettyPrintDiffedMap( + DiffUtils.deepDiff(modified.toDiffableFieldMap(), registrar.toDiffableFieldMap(), true), + null); + assertThat(reverseDiff) + .contains( + """ + allowedEppClientCertificateHostnames: + REMOVED: [epp.registrar.example] + FINAL CONTENTS: [] + """); + assertThat(reverseDiff) + .contains( + String.format( + """ + revokedClientCertificateHashes: + REMOVED: [%s] + FINAL CONTENTS: [] + """, + SAMPLE_CERT_HASH)); + } } diff --git a/core/src/test/java/google/registry/schema/registrar/RegistrarDaoTest.java b/core/src/test/java/google/registry/schema/registrar/RegistrarDaoTest.java index fcec4726e71..ed9dec9eddc 100644 --- a/core/src/test/java/google/registry/schema/registrar/RegistrarDaoTest.java +++ b/core/src/test/java/google/registry/schema/registrar/RegistrarDaoTest.java @@ -15,6 +15,7 @@ package google.registry.schema.registrar; import static com.google.common.truth.Truth.assertThat; +import static google.registry.testing.CertificateSamples.SAMPLE_CERT_HASH; import static google.registry.testing.DatabaseHelper.existsInDb; import static google.registry.testing.DatabaseHelper.loadByKey; import static google.registry.testing.DatabaseHelper.persistResource; @@ -59,6 +60,8 @@ void beforeEach() { .setZip("11211") .setCountryCode("US") .build()) + .setAllowedEppClientCertificateHostnames(ImmutableList.of("epp.registrar.example")) + .setRevokedClientCertificateHashes(ImmutableList.of(SAMPLE_CERT_HASH)) .build(); } @@ -97,5 +100,8 @@ void load_worksSuccessfully() { .setZip("11211") .setCountryCode("US") .build()); + assertThat(persisted.getAllowedEppClientCertificateHostnames()) + .containsExactly("epp.registrar.example"); + assertThat(persisted.getRevokedClientCertificateHashes()).containsExactly(SAMPLE_CERT_HASH); } } diff --git a/core/src/test/java/google/registry/ui/server/console/settings/SecurityActionTest.java b/core/src/test/java/google/registry/ui/server/console/settings/SecurityActionTest.java index f8436e12cf0..3a595ddbe80 100644 --- a/core/src/test/java/google/registry/ui/server/console/settings/SecurityActionTest.java +++ b/core/src/test/java/google/registry/ui/server/console/settings/SecurityActionTest.java @@ -16,14 +16,22 @@ import static com.google.common.truth.Truth.assertThat; import static google.registry.testing.CertificateSamples.SAMPLE_CERT2; +import static google.registry.testing.CertificateSamples.SAMPLE_CERT3_HASH; +import static google.registry.testing.CertificateSamples.SAMPLE_CERT_HASH; import static google.registry.testing.DatabaseHelper.loadRegistrar; import static google.registry.testing.DatabaseHelper.loadSingleton; +import static google.registry.testing.DatabaseHelper.persistResource; import static google.registry.testing.SqlHelper.saveRegistrar; import static google.registry.util.DateTimeUtils.START_INSTANT; import static jakarta.servlet.http.HttpServletResponse.SC_BAD_REQUEST; import static jakarta.servlet.http.HttpServletResponse.SC_OK; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.when; +import com.google.common.collect.ImmutableList; +import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSetMultimap; import com.google.common.collect.ImmutableSortedMap; @@ -35,10 +43,10 @@ import google.registry.request.auth.AuthenticatedRegistrarAccessor; import google.registry.testing.FakeResponse; import google.registry.ui.server.console.ConsoleActionBaseTestCase; -import google.registry.ui.server.console.ConsoleModule; +import google.registry.util.EmailMessage; +import jakarta.mail.internet.InternetAddress; import java.io.IOException; import java.time.Instant; -import java.util.Optional; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -163,14 +171,450 @@ void testFailure_validityPeriodTooLong_returnsSpecificError() throws IOException assertThat(response.getPayload()).isEqualTo(expectedError); } + @Test + void testSuccess_setAllowedEppClientCertificateHostnames() throws Exception { + SecurityAction action = + createAction( + testRegistrar.getRegistrarId(), + securityJson( + ImmutableMap.of( + "allowedEppClientCertificateHostnames", + ImmutableList.of("EPP.Example.COM", "epp2.example.com", "epp.example.com"))), + lenientChecker()); + action.run(); + assertThat(response.getStatus()).isEqualTo(SC_OK); + Registrar r = loadRegistrar(testRegistrar.getRegistrarId()); + assertThat(r.getAllowedEppClientCertificateHostnames()) + .containsExactly("epp.example.com", "epp2.example.com"); + ConsoleUpdateHistory history = loadSingleton(ConsoleUpdateHistory.class).get(); + assertThat(history.getDescription()).hasValue("registrarId|EPP_CERT_HOSTNAMES_CHANGE"); + verify(consoleApiParams.sendEmailUtils().gmailClient, times(1)) + .sendEmail( + EmailMessage.newBuilder() + .setSubject( + "Registrar New Registrar (registrarId) updated in registry unittest" + + " environment") + .setBody( + """ + The following changes were made in registry unittest environment to the\ + registrar registrarId by admin fte@email.tld: + + allowedEppClientCertificateHostnames: + ADDED: [epp.example.com, epp2.example.com] + FINAL CONTENTS: [epp.example.com, epp2.example.com] + """) + .setRecipients(ImmutableList.of(new InternetAddress("notification@test.example"))) + .build()); + } + + @Test + void testSuccess_unchangedAllowedEppClientCertificateHostnames() throws IOException { + persistResource( + testRegistrar + .asBuilder() + .setAllowedEppClientCertificateHostnames(ImmutableList.of("epp.example.com")) + .build()); + SecurityAction action = + createAction( + testRegistrar.getRegistrarId(), + securityJson( + ImmutableMap.of( + "allowedEppClientCertificateHostnames", ImmutableList.of("EPP.Example.COM."))), + lenientChecker()); + action.run(); + assertThat(response.getStatus()).isEqualTo(SC_OK); + ConsoleUpdateHistory history = loadSingleton(ConsoleUpdateHistory.class).get(); + assertThat(history.getDescription()).hasValue("registrarId|"); + verifyNoInteractions(consoleApiParams.sendEmailUtils().gmailClient); + } + + @Test + void testSuccess_omittedHostnamesAndRevokedHashes_preservesExisting() throws IOException { + persistResource( + testRegistrar + .asBuilder() + .setAllowedEppClientCertificateHostnames(ImmutableList.of("epp.example.com")) + .setRevokedClientCertificateHashes(ImmutableList.of(SAMPLE_CERT_HASH)) + .build()); + SecurityAction action = + createAction( + testRegistrar.getRegistrarId(), + securityJson(ImmutableMap.of("ipAddressAllowList", ImmutableList.of("192.168.1.1/32"))), + lenientChecker()); + action.run(); + assertThat(response.getStatus()).isEqualTo(SC_OK); + Registrar r = loadRegistrar(testRegistrar.getRegistrarId()); + assertThat(r.getAllowedEppClientCertificateHostnames()).containsExactly("epp.example.com"); + assertThat(r.getRevokedClientCertificateHashes()).containsExactly(SAMPLE_CERT_HASH); + ConsoleUpdateHistory history = loadSingleton(ConsoleUpdateHistory.class).get(); + assertThat(history.getDescription()).hasValue("registrarId|IP_CHANGE"); + } + + @Test + void testSuccess_nullHostnamesAndRevokedHashes_preservesExisting() throws IOException { + persistResource( + testRegistrar + .asBuilder() + .setAllowedEppClientCertificateHostnames(ImmutableList.of("epp.example.com")) + .setRevokedClientCertificateHashes(ImmutableList.of(SAMPLE_CERT_HASH)) + .build()); + SecurityAction action = + createAction( + testRegistrar.getRegistrarId(), + "{\"registrarId\": \"registrarId\"," + + " \"allowedEppClientCertificateHostnames\": null," + + " \"revokedClientCertificateHashes\": null," + + " \"ipAddressAllowList\": [\"192.168.1.1/32\"]}", + lenientChecker()); + action.run(); + assertThat(response.getStatus()).isEqualTo(SC_OK); + Registrar r = loadRegistrar(testRegistrar.getRegistrarId()); + assertThat(r.getAllowedEppClientCertificateHostnames()).containsExactly("epp.example.com"); + assertThat(r.getRevokedClientCertificateHashes()).containsExactly(SAMPLE_CERT_HASH); + ConsoleUpdateHistory history = loadSingleton(ConsoleUpdateHistory.class).get(); + assertThat(history.getDescription()).hasValue("registrarId|IP_CHANGE"); + } + + @Test + void testSuccess_emptyHostnamesAndRevokedHashes_whenAlreadyEmpty() throws IOException { + SecurityAction action = + createAction( + testRegistrar.getRegistrarId(), + securityJson( + ImmutableMap.of( + "allowedEppClientCertificateHostnames", + ImmutableList.of(), + "revokedClientCertificateHashes", + ImmutableList.of(), + "ipAddressAllowList", + ImmutableList.of("192.168.1.1/32"))), + lenientChecker()); + action.run(); + assertThat(response.getStatus()).isEqualTo(SC_OK); + ConsoleUpdateHistory history = loadSingleton(ConsoleUpdateHistory.class).get(); + assertThat(history.getDescription()).hasValue("registrarId|IP_CHANGE"); + } + + @Test + void testFailure_clearAllowedEppClientCertificateHostnames_whenConfigured() throws IOException { + persistResource( + testRegistrar + .asBuilder() + .setAllowedEppClientCertificateHostnames(ImmutableList.of("epp.example.com")) + .build()); + SecurityAction action = + createAction( + testRegistrar.getRegistrarId(), + securityJson( + ImmutableMap.of("allowedEppClientCertificateHostnames", ImmutableList.of())), + lenientChecker()); + action.run(); + assertThat(response.getStatus()).isEqualTo(SC_BAD_REQUEST); + assertThat(response.getPayload()) + .contains("Cannot clear allowed EPP client certificate hostnames once configured"); + assertThat( + loadRegistrar(testRegistrar.getRegistrarId()).getAllowedEppClientCertificateHostnames()) + .containsExactly("epp.example.com"); + } + + @Test + void testFailure_invalidAllowedEppClientCertificateHostname() throws IOException { + SecurityAction action = + createAction( + testRegistrar.getRegistrarId(), + securityJson( + ImmutableMap.of( + "allowedEppClientCertificateHostnames", + ImmutableList.of("epp.example.com", "*.example.com"))), + lenientChecker()); + action.run(); + assertThat(response.getStatus()).isEqualTo(SC_BAD_REQUEST); + assertThat(response.getPayload()).contains("*.example.com"); + assertThat( + loadRegistrar(testRegistrar.getRegistrarId()).getAllowedEppClientCertificateHostnames()) + .isEmpty(); + } + + @Test + void testFailure_tooManyAllowedEppClientCertificateHostnames() throws IOException { + ImmutableList.Builder hostnames = new ImmutableList.Builder<>(); + for (int i = 0; i <= Registrar.MAX_EPP_CLIENT_CERTIFICATE_HOSTNAMES; i++) { + hostnames.add(String.format("epp%d.registrar.example", i)); + } + SecurityAction action = + createAction( + testRegistrar.getRegistrarId(), + securityJson( + ImmutableMap.of("allowedEppClientCertificateHostnames", hostnames.build())), + lenientChecker()); + action.run(); + assertThat(response.getStatus()).isEqualTo(SC_BAD_REQUEST); + assertThat(response.getPayload()) + .contains("At most 20 EPP client certificate hostnames may be configured, got 21"); + assertThat( + loadRegistrar(testRegistrar.getRegistrarId()).getAllowedEppClientCertificateHostnames()) + .isEmpty(); + } + + @Test + void testFailure_nullElementInHostnamesJson() throws IOException { + SecurityAction action = + createAction( + testRegistrar.getRegistrarId(), + "{\"registrarId\": \"registrarId\"," + + " \"allowedEppClientCertificateHostnames\": [\"epp.example.com\", null]}", + lenientChecker()); + action.run(); + assertThat(response.getStatus()).isEqualTo(SC_BAD_REQUEST); + assertThat(response.getPayload()).contains("EPP client certificate hostname cannot be null"); + } + + @Test + void testFailure_nullElementInRevokedHashesJson() throws IOException { + SecurityAction action = + createAction( + testRegistrar.getRegistrarId(), + "{\"registrarId\": \"registrarId\", \"revokedClientCertificateHashes\": [null]}", + lenientChecker()); + action.run(); + assertThat(response.getStatus()).isEqualTo(SC_BAD_REQUEST); + assertThat(response.getPayload()).contains("Revoked client certificate hash cannot be null"); + } + + @Test + void testSuccess_setRevokedClientCertificateHashes() throws Exception { + SecurityAction action = + createAction( + testRegistrar.getRegistrarId(), + securityJson( + ImmutableMap.of( + "revokedClientCertificateHashes", + ImmutableList.of(SAMPLE_CERT3_HASH, SAMPLE_CERT_HASH))), + lenientChecker()); + action.run(); + assertThat(response.getStatus()).isEqualTo(SC_OK); + Registrar r = loadRegistrar(testRegistrar.getRegistrarId()); + assertThat(r.getRevokedClientCertificateHashes()) + .containsExactly(SAMPLE_CERT3_HASH, SAMPLE_CERT_HASH); + ConsoleUpdateHistory history = loadSingleton(ConsoleUpdateHistory.class).get(); + assertThat(history.getDescription()).hasValue("registrarId|REVOKED_CERTS_CHANGE"); + verify(consoleApiParams.sendEmailUtils().gmailClient, times(1)) + .sendEmail( + EmailMessage.newBuilder() + .setSubject( + "Registrar New Registrar (registrarId) updated in registry unittest" + + " environment") + .setBody( + String.format( + """ + The following changes were made in registry unittest environment to the\ + registrar registrarId by admin fte@email.tld: + + revokedClientCertificateHashes: + ADDED: [%s, %s] + FINAL CONTENTS: [%s, %s] + """, + SAMPLE_CERT3_HASH, SAMPLE_CERT_HASH, SAMPLE_CERT3_HASH, SAMPLE_CERT_HASH)) + .setRecipients(ImmutableList.of(new InternetAddress("notification@test.example"))) + .build()); + } + + @Test + void testSuccess_clearRevokedClientCertificateHashes() throws Exception { + persistResource( + testRegistrar + .asBuilder() + .setRevokedClientCertificateHashes(ImmutableList.of(SAMPLE_CERT_HASH)) + .build()); + SecurityAction action = + createAction( + testRegistrar.getRegistrarId(), + securityJson(ImmutableMap.of("revokedClientCertificateHashes", ImmutableList.of())), + lenientChecker()); + action.run(); + assertThat(response.getStatus()).isEqualTo(SC_OK); + Registrar r = loadRegistrar(testRegistrar.getRegistrarId()); + assertThat(r.getRevokedClientCertificateHashes()).isEmpty(); + ConsoleUpdateHistory history = loadSingleton(ConsoleUpdateHistory.class).get(); + assertThat(history.getDescription()).hasValue("registrarId|REVOKED_CERTS_CHANGE"); + verify(consoleApiParams.sendEmailUtils().gmailClient, times(1)) + .sendEmail( + EmailMessage.newBuilder() + .setSubject( + "Registrar New Registrar (registrarId) updated in registry unittest" + + " environment") + .setBody( + String.format( + """ + The following changes were made in registry unittest environment to the\ + registrar registrarId by admin fte@email.tld: + + revokedClientCertificateHashes: + REMOVED: [%s] + FINAL CONTENTS: [] + """, + SAMPLE_CERT_HASH)) + .setRecipients(ImmutableList.of(new InternetAddress("notification@test.example"))) + .build()); + } + + @Test + void testFailure_invalidRevokedClientCertificateHash() throws IOException { + SecurityAction action = + createAction( + testRegistrar.getRegistrarId(), + securityJson( + ImmutableMap.of( + "revokedClientCertificateHashes", ImmutableList.of("invalid-hash"))), + lenientChecker()); + action.run(); + assertThat(response.getStatus()).isEqualTo(SC_BAD_REQUEST); + assertThat(response.getPayload()).contains("Invalid base64 SHA-256 certificate hash"); + assertThat(loadRegistrar(testRegistrar.getRegistrarId()).getRevokedClientCertificateHashes()) + .isEmpty(); + } + + @Test + void testSuccess_unchangedRevokedClientCertificateHashes() throws IOException { + persistResource( + testRegistrar + .asBuilder() + .setRevokedClientCertificateHashes(ImmutableList.of(SAMPLE_CERT_HASH)) + .build()); + SecurityAction action = + createAction( + testRegistrar.getRegistrarId(), + securityJson( + ImmutableMap.of( + "revokedClientCertificateHashes", + ImmutableList.of(SAMPLE_CERT_HASH), + "ipAddressAllowList", + ImmutableList.of("192.168.1.1/32"))), + lenientChecker()); + action.run(); + assertThat(response.getStatus()).isEqualTo(SC_OK); + ConsoleUpdateHistory history = loadSingleton(ConsoleUpdateHistory.class).get(); + assertThat(history.getDescription()).hasValue("registrarId|IP_CHANGE"); + } + + @Test + void testFailure_tooManyRevokedClientCertificateHashes() throws IOException { + ImmutableList.Builder hashes = new ImmutableList.Builder<>(); + for (int i = 0; i <= Registrar.MAX_REVOKED_CLIENT_CERTIFICATE_HASHES; i++) { + hashes.add((char) ('A' + i) + SAMPLE_CERT_HASH.substring(1)); + } + SecurityAction action = + createAction( + testRegistrar.getRegistrarId(), + securityJson(ImmutableMap.of("revokedClientCertificateHashes", hashes.build())), + lenientChecker()); + action.run(); + assertThat(response.getStatus()).isEqualTo(SC_BAD_REQUEST); + assertThat(response.getPayload()) + .contains("At most 20 revoked client certificates may be configured, got 21"); + assertThat(loadRegistrar(testRegistrar.getRegistrarId()).getRevokedClientCertificateHashes()) + .isEmpty(); + } + + @Test + void testFailure_emptyPayload() throws IOException { + SecurityAction action = createAction(testRegistrar.getRegistrarId(), "", lenientChecker()); + action.run(); + assertThat(response.getStatus()).isEqualTo(SC_BAD_REQUEST); + assertThat(response.getPayload()).contains("'registrar' parameter is not present"); + } + + @Test + void testFailure_nonObjectJsonPayload() throws IOException { + SecurityAction action = createAction(testRegistrar.getRegistrarId(), "[]", lenientChecker()); + action.run(); + assertThat(response.getStatus()).isEqualTo(SC_BAD_REQUEST); + assertThat(response.getPayload()).contains("'registrar' parameter must be a JSON object"); + } + + @Test + void testFailure_nonArrayFieldJson() throws IOException { + SecurityAction action = + createAction( + testRegistrar.getRegistrarId(), + "{\"registrarId\": \"registrarId\"," + + " \"revokedClientCertificateHashes\": \"not-an-array\"}", + lenientChecker()); + action.run(); + assertThat(response.getStatus()).isEqualTo(SC_BAD_REQUEST); + assertThat(response.getPayload()) + .contains("'revokedClientCertificateHashes' must be a JSON array"); + } + + @Test + void testFailure_nonStringNumberElementInHostnamesJson() throws IOException { + SecurityAction action = + createAction( + testRegistrar.getRegistrarId(), + "{\"registrarId\": \"registrarId\", \"allowedEppClientCertificateHostnames\": [1.2e3]}", + lenientChecker()); + action.run(); + assertThat(response.getStatus()).isEqualTo(SC_BAD_REQUEST); + assertThat(response.getPayload()) + .contains("'allowedEppClientCertificateHostnames' elements must be strings"); + } + + @Test + void testFailure_nonStringObjectElementInRevokedHashesJson() throws IOException { + SecurityAction action = + createAction( + testRegistrar.getRegistrarId(), + "{\"registrarId\": \"registrarId\", \"revokedClientCertificateHashes\": [{}]}", + lenientChecker()); + action.run(); + assertThat(response.getStatus()).isEqualTo(SC_BAD_REQUEST); + assertThat(response.getPayload()) + .contains("'revokedClientCertificateHashes' elements must be strings"); + } + + @Test + void testFailure_malformedFieldType_returnsBadRequest() throws IOException { + SecurityAction action = + createAction( + testRegistrar.getRegistrarId(), + "{\"registrarId\": \"registrarId\", \"ipAddressAllowList\": \"not-an-array\"}", + lenientChecker()); + action.run(); + assertThat(response.getStatus()).isEqualTo(SC_BAD_REQUEST); + } + + /** Builds the JSON body the console sends: the registrar ID plus the given security fields. */ + private static String securityJson(ImmutableMap fields) { + return GSON.toJson( + ImmutableMap.builder().put("registrarId", "registrarId").putAll(fields).build()); + } + + private CertificateChecker lenientChecker() { + clock.setTo(Instant.parse("2020-11-01T00:00:00Z")); + return new CertificateChecker( + ImmutableSortedMap.of(START_INSTANT, 20825, Instant.parse("2020-09-01T00:00:00Z"), 398), + 30, + 15, + 2048, + ImmutableSet.of("secp256r1", "secp384r1"), + clock); + } + private SecurityAction createAction( String registrarId, String jsonBody, CertificateChecker certificateChecker) throws IOException { when(consoleApiParams.request().getMethod()).thenReturn(Action.Method.POST.toString()); - Optional maybeRegistrar = - ConsoleModule.provideRegistrar(GSON, RequestModule.provideJsonBody(jsonBody, GSON)); + when(consoleApiParams.request().getInputStream()) + .thenReturn(createServletInputStream(jsonBody)); + byte[] payloadBytes = RequestModule.providePayloadAsBytes(consoleApiParams.request()); + String payloadString = + RequestModule.providePayloadAsString(payloadBytes, consoleApiParams.request()); return new SecurityAction( - consoleApiParams, certificateChecker, registrarAccessor, registrarId, maybeRegistrar); + consoleApiParams, + certificateChecker, + registrarAccessor, + registrarId, + RequestModule.provideJsonBody(payloadString, GSON)); } private SecurityAction createAction(String registrarId, CertificateChecker certificateChecker) diff --git a/db/src/main/resources/sql/schema/db-schema.sql.generated b/db/src/main/resources/sql/schema/db-schema.sql.generated index d10fbb5f3fd..64b0146c5e3 100644 --- a/db/src/main/resources/sql/schema/db-schema.sql.generated +++ b/db/src/main/resources/sql/schema/db-schema.sql.generated @@ -504,6 +504,7 @@ create table "Registrar" ( registrar_id text not null, last_update_time timestamp(6) with time zone not null, + allowed_epp_client_certificate_hostnames text[], allowed_tlds text[], billing_account_map hstore, block_premium_names boolean not null, @@ -545,6 +546,7 @@ rdap_base_urls text[], registrar_name text not null, registry_lock_allowed boolean not null, + revoked_client_certificate_hashes text[], password_salt text, state text check ((state in ('PENDING','ACTIVE','SUSPENDED','DISABLED'))), type text not null check ((type in ('REAL','OTE','PDT','EXTERNAL_MONITORING','INTERNAL','MONITORING','TEST'))), diff --git a/util/src/main/java/google/registry/util/DomainNameUtils.java b/util/src/main/java/google/registry/util/DomainNameUtils.java index 16311facc70..8a42ec9f6e5 100644 --- a/util/src/main/java/google/registry/util/DomainNameUtils.java +++ b/util/src/main/java/google/registry/util/DomainNameUtils.java @@ -18,6 +18,7 @@ import static google.registry.util.PreconditionsUtils.checkArgumentNotNull; import com.google.common.base.Ascii; +import com.google.common.base.CharMatcher; import com.google.common.base.Joiner; import com.google.common.base.Splitter; import com.google.common.base.Strings; @@ -28,6 +29,10 @@ /** Utility methods related to domain names. */ public final class DomainNameUtils { + /** Strict validator for ASCII lowercase letters, digits, and "-", allowing "." as a separator. */ + public static final CharMatcher ALLOWED_CHARS = + CharMatcher.inRange('a', 'z').or(CharMatcher.inRange('0', '9').or(CharMatcher.anyOf("-."))); + /** Prefix for unicode domain name parts. */ public static final String ACE_PREFIX = "xn--"; public static final String ACE_PREFIX_REGEX = "^xn--"; @@ -71,6 +76,25 @@ public static String canonicalizeHostname(String label) { return sb.toString(); } + /** + * Canonicalizes and validates a fully qualified DNS hostname (lowercased A-label punycode, strict + * ASCII LDH characters, at least two labels, and any trailing dot stripped). + * + * @throws IllegalArgumentException if {@code hostname} is null or not a valid multi-label DNS + * hostname + */ + public static String canonicalizeAndValidateHostname(String hostname) { + checkArgumentNotNull(hostname, "Hostname cannot be null"); + InternetDomainName domainName = InternetDomainName.from(canonicalizeHostname(hostname)); + // InternetDomainName allows underscores and single-label names; require strict ASCII LDH + // characters and at least two labels. + checkArgument( + ALLOWED_CHARS.matchesAllOf(domainName.toString()) && domainName.hasParent(), + "Not a valid fully qualified hostname: %s", + hostname); + return domainName.toString(); + } + /** * Returns the canonicalized TLD part of a valid fully-qualified domain name by stripping off the * leftmost part. diff --git a/util/src/test/java/google/registry/util/DomainNameUtilsTest.java b/util/src/test/java/google/registry/util/DomainNameUtilsTest.java index 75b73e1f6eb..6b79971c1fe 100644 --- a/util/src/test/java/google/registry/util/DomainNameUtilsTest.java +++ b/util/src/test/java/google/registry/util/DomainNameUtilsTest.java @@ -15,10 +15,12 @@ package google.registry.util; import static com.google.common.truth.Truth.assertThat; +import static google.registry.util.DomainNameUtils.canonicalizeAndValidateHostname; import static google.registry.util.DomainNameUtils.canonicalizeHostname; import static google.registry.util.DomainNameUtils.getSecondLevelDomain; import static org.junit.jupiter.api.Assertions.assertThrows; +import com.google.common.collect.ImmutableList; import org.junit.jupiter.api.Test; /** Unit tests for {@link DomainNameUtils}. */ @@ -83,6 +85,65 @@ void testCanonicalizeHostname_acePrefixUnicodeChars() { assertThrows(IllegalArgumentException.class, () -> canonicalizeHostname("xn--みんな")); } + @Test + void testCanonicalizeAndValidateHostname_succeeds() { + assertThat(canonicalizeAndValidateHostname("b.example")).isEqualTo("b.example"); + assertThat(canonicalizeAndValidateHostname("EPP.Registrar.Example")) + .isEqualTo("epp.registrar.example"); + assertThat(canonicalizeAndValidateHostname("COM.Google.Registrar.")) + .isEqualTo("com.google.registrar"); + assertThat(canonicalizeAndValidateHostname("epp.みんな")).isEqualTo("epp.xn--q9jyb4c"); + assertThat(canonicalizeAndValidateHostname("みんな.registrar.example")) + .isEqualTo("xn--q9jyb4c.registrar.example"); + assertThat(canonicalizeAndValidateHostname("XN--Q9JYB4C.Registrar.Example")) + .isEqualTo("xn--q9jyb4c.registrar.example"); + assertThat(canonicalizeAndValidateHostname("epp-01.c-d.example")) + .isEqualTo("epp-01.c-d.example"); + String maxLabel = "a".repeat(63); + assertThat(canonicalizeAndValidateHostname(maxLabel + ".example")) + .isEqualTo(maxLabel + ".example"); + String maxHostname = + "a".repeat(63) + "." + "b".repeat(63) + "." + "c".repeat(63) + "." + "d".repeat(61); + assertThat(maxHostname).hasLength(253); + assertThat(canonicalizeAndValidateHostname(maxHostname)).isEqualTo(maxHostname); + } + + @Test + void testCanonicalizeAndValidateHostname_invalid() { + assertThrows(IllegalArgumentException.class, () -> canonicalizeAndValidateHostname(null)); + for (String invalid : + ImmutableList.of( + "", + ".", + "localhost", + "localhost.", + ".registrar.example", + "epp..registrar.example", + "epp.registrar.example..", + "*.registrar.example", + "epp_1.registrar.example", + "-epp.registrar.example", + "epp-.registrar.example", + "ab--cd.registrar.example", + "xn--みんな.example", + "192.0.2.1", + "2001:db8::1", + "[2001:db8::1]", + "https://epp.registrar.example", + "epp.registrar.example:700", + "epp.registrar.example/path", + " epp.registrar.example", + "epp.registrar.example ", + "epp.registrar.ex ample", + "a".repeat(64) + ".example", + "a".repeat(63) + "." + "b".repeat(63) + "." + "c".repeat(63) + "." + "d".repeat(62))) { + assertThrows( + IllegalArgumentException.class, + () -> canonicalizeAndValidateHostname(invalid), + "Expected IllegalArgumentException for: " + invalid); + } + } + @Test void testGetSecondLevelDomain_returnsProperDomain() { assertThat(getSecondLevelDomain("foo.bar", "bar")).isEqualTo("foo.bar");