1
0
mirror of https://github.com/google/nomulus synced 2026-07-10 18:13:02 +00:00

Compare commits

...

7 Commits

Author SHA1 Message Date
Pavlo Tkach 1096f201cd Add GKE readiness probe (#2735) 2025-04-04 21:33:43 +00:00
gbrodman 9dc3215624 Redirect an empty RDAP path to the /help response (#2722)
The behavior when someone hits the plain RDAP base URL isn't specified
by the spec. Currently we just return a plain 404 which isn't
particularly nice or helpful -- so it would probably be nicer to just
redirect to the /help response instead.

tested on alpha,
https://pubapi-dot-domain-registry-alpha.appspot.com/rdap redirects to https://pubapi-dot-domain-registry-alpha.appspot.com/rdap/help
2025-04-03 15:37:23 +00:00
Lai Jiang af321fb65e Make frontend deployment auto scale (#2736)
Now that we have effective global sessions thanks to #2734, there is no
longer a need to keep the number of pods on the EPP service static.

We are also not vulnerable to random pod restarts. K8s never guarantees
perpetual pod lifetime anyway, and not having to be at its mercy is
certainly a relief.
2025-04-02 18:58:52 +00:00
Lai Jiang c5132c04be Use pipe as extension URI separator (#2737)
It turns out period can be used in the URI, such as in
"urn:ietf:params:xml:ns:fee-0.12". I don't think pipe is used, at least
not according to EPP URI namespace naming convention.

Ideally we'd use serialization, but using the default serialization runs
the risk of it being platform/JDK dependent, so a new deployment might
not be able to deserialize existing cookies. A custom serializer that
guarantees stability would have been needed.
2025-04-02 13:21:13 +00:00
Lai Jiang a64dc21f96 make the deploy task deploy to GKE (#2734)
Also always pulls the latest images from repos instead of relying on
local cases. This makes it so that a local docker build is always fresh.
2025-03-31 22:38:53 +00:00
Pavlo Tkach 0381533a35 Set grace period to 1s for immediate pods restart (#2733) 2025-03-31 19:15:13 +00:00
Lai Jiang 4999a72d96 Save session data directly in a cookie (#2732) 2025-03-31 16:21:50 +00:00
28 changed files with 691 additions and 95 deletions
-1
View File
@@ -90,7 +90,6 @@ explodeWar.doLast {
appengineDeployAll.mustRunAfter ':console-webapp:deploy'
appengineDeployAll.finalizedBy ':deployCloudSchedulerAndQueue'
rootProject.deploy.dependsOn appengineDeployAll
rootProject.stage.dependsOn appengineStage
tasks['war'].dependsOn ':core:processResources'
-7
View File
@@ -101,16 +101,9 @@ task checkFormatting(type: Exec) {
args 'run', 'prettify:check'
}
task deploy(type: Exec) {
workingDir "${consoleDir}/staged"
executable 'gcloud'
args 'app', 'deploy', "${projectParam}", '--quiet'
}
tasks.buildConsoleWebapp.dependsOn(tasks.npmInstallDeps)
tasks.runConsoleWebappUnitTests.dependsOn(tasks.npmInstallDeps)
tasks.applyFormatting.dependsOn(tasks.npmInstallDeps)
tasks.checkFormatting.dependsOn(tasks.npmInstallDeps)
tasks.build.dependsOn(tasks.checkFormatting)
tasks.build.dependsOn(tasks.runConsoleWebappUnitTests)
tasks.deploy.dependsOn(tasks.buildConsoleWebapp)
@@ -0,0 +1,155 @@
// Copyright 2025 The Nomulus Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package google.registry.flows;
import static java.nio.charset.StandardCharsets.US_ASCII;
import com.google.common.base.Joiner;
import com.google.common.base.Splitter;
import com.google.common.collect.ImmutableSet;
import com.google.common.flogger.FluentLogger;
import com.google.common.io.BaseEncoding;
import google.registry.request.Response;
import jakarta.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* A metadata class that saves the data directly in cookies.
*
* <p>Unlike {@link HttpSessionMetadata}, this class does not rely on a session manager to translate
* an opaque session cookie into the metadata. This means that the locality of the session manager
* is irrelevant and as long as the client (the proxy) respects the {@code Set-Cookie} headers and
* sets the respective cookies in subsequent requests in a session, the metadata will be available
* to all servers, not just the one that created the session.
*
* <p>The string representation of the metadata is saved in Base64 URL-safe format in a cookie named
* {@code SESSION_INFO}.
*/
public class CookieSessionMetadata extends SessionMetadata {
protected static final String COOKIE_NAME = "SESSION_INFO";
protected static final String REGISTRAR_ID = "clientId";
protected static final String SERVICE_EXTENSIONS = "serviceExtensionUris";
protected static final String FAILED_LOGIN_ATTEMPTS = "failedLoginAttempts";
private static final Pattern COOKIE_PATTERN = Pattern.compile("SESSION_INFO=([^;\\s]+)?");
private static final Pattern REGISTRAR_ID_PATTERN = Pattern.compile("clientId=([^,\\s]+)?");
private static final Pattern SERVICE_EXTENSIONS_PATTERN =
Pattern.compile("serviceExtensionUris=([^,\\s}]+)?");
private static final Pattern FAILED_LOGIN_ATTEMPTS_PATTERN =
Pattern.compile("failedLoginAttempts=([^,\\s]+)?");
private static final FluentLogger logger = FluentLogger.forEnclosingClass();
private final Map<String, String> data = new HashMap<>();
public CookieSessionMetadata(HttpServletRequest request) {
Optional.ofNullable(request.getHeader("Cookie"))
.ifPresent(
cookie -> {
Matcher matcher = COOKIE_PATTERN.matcher(cookie);
if (matcher.find()) {
String sessionInfo = decode(matcher.group(1));
logger.atInfo().log("SESSION INFO: %s", sessionInfo);
matcher = REGISTRAR_ID_PATTERN.matcher(sessionInfo);
if (matcher.find()) {
String registrarId = matcher.group(1);
if (!registrarId.equals("null")) {
data.put(REGISTRAR_ID, registrarId);
}
}
matcher = SERVICE_EXTENSIONS_PATTERN.matcher(sessionInfo);
if (matcher.find()) {
String serviceExtensions = matcher.group(1);
if (serviceExtensions != null) {
data.put(SERVICE_EXTENSIONS, serviceExtensions);
}
}
matcher = FAILED_LOGIN_ATTEMPTS_PATTERN.matcher(sessionInfo);
if (matcher.find()) {
String failedLoginAttempts = matcher.group(1);
data.put(FAILED_LOGIN_ATTEMPTS, failedLoginAttempts);
}
}
});
}
@Override
public void invalidate() {
data.clear();
}
@Override
public String getRegistrarId() {
return data.getOrDefault(REGISTRAR_ID, null);
}
@Override
public Set<String> getServiceExtensionUris() {
return Optional.ofNullable(data.getOrDefault(SERVICE_EXTENSIONS, null))
.map(s -> Splitter.on(URI_SEPARATOR).splitToList(s))
.map(ImmutableSet::copyOf)
.orElse(ImmutableSet.of());
}
@Override
public int getFailedLoginAttempts() {
return Optional.ofNullable(data.getOrDefault(FAILED_LOGIN_ATTEMPTS, null))
.map(Integer::parseInt)
.orElse(0);
}
@Override
public void setRegistrarId(String registrarId) {
data.put(REGISTRAR_ID, registrarId);
}
@Override
public void setServiceExtensionUris(Set<String> serviceExtensionUris) {
if (serviceExtensionUris == null || serviceExtensionUris.isEmpty()) {
data.remove(SERVICE_EXTENSIONS);
} else {
data.put(SERVICE_EXTENSIONS, Joiner.on(URI_SEPARATOR).join(serviceExtensionUris));
}
}
@Override
public void incrementFailedLoginAttempts() {
data.put(FAILED_LOGIN_ATTEMPTS, String.valueOf(getFailedLoginAttempts() + 1));
}
@Override
public void resetFailedLoginAttempts() {
data.remove(FAILED_LOGIN_ATTEMPTS);
}
@Override
public void save(Response response) {
String value = encode(toString());
response.setHeader("Set-Cookie", COOKIE_NAME + "=" + value);
}
protected static String encode(String plainText) {
return BaseEncoding.base64Url().encode(plainText.getBytes(US_ASCII));
}
protected static String decode(String cipherText) {
return new String(BaseEncoding.base64Url().decode(cipherText), US_ASCII);
}
}
@@ -78,6 +78,8 @@ public class EppRequestHandler {
} catch (Exception e) {
logger.atWarning().withCause(e).log("handleEppCommand general exception.");
response.setStatus(SC_BAD_REQUEST);
} finally {
sessionMetadata.save(response);
}
}
}
@@ -20,7 +20,7 @@ import google.registry.request.Action.Method;
import google.registry.request.Payload;
import google.registry.request.auth.Auth;
import jakarta.inject.Inject;
import jakarta.servlet.http.HttpSession;
import jakarta.servlet.http.HttpServletRequest;
/**
* Establishes a transport for EPP+TLS over HTTP. All commands and responses are EPP XML according
@@ -35,18 +35,18 @@ public class EppTlsAction implements Runnable {
@Inject @Payload byte[] inputXmlBytes;
@Inject TlsCredentials tlsCredentials;
@Inject HttpSession session;
@Inject HttpServletRequest request;
@Inject EppRequestHandler eppRequestHandler;
@Inject EppTlsAction() {}
@Override
public void run() {
eppRequestHandler.executeEpp(
new HttpSessionMetadata(session),
new CookieSessionMetadata(request),
tlsCredentials,
EppRequestSource.TLS,
false, // This endpoint is never a dry run.
false, // This endpoint is never a superuser.
false, // This endpoint is never a dry run.
false, // This endpoint is never a superuser.
inputXmlBytes);
}
}
@@ -14,16 +14,14 @@
package google.registry.flows;
import static com.google.common.base.MoreObjects.toStringHelper;
import static google.registry.util.CollectionUtils.nullToEmpty;
import com.google.common.base.Joiner;
import jakarta.servlet.http.HttpSession;
import java.util.Optional;
import java.util.Set;
/** A metadata class that is a wrapper around {@link HttpSession}. */
public class HttpSessionMetadata implements SessionMetadata {
public class HttpSessionMetadata extends SessionMetadata {
private static final String REGISTRAR_ID = "REGISTRAR_ID";
private static final String SERVICE_EXTENSIONS = "SERVICE_EXTENSIONS";
@@ -75,13 +73,4 @@ public class HttpSessionMetadata implements SessionMetadata {
public void resetFailedLoginAttempts() {
session.removeAttribute(FAILED_LOGIN_ATTEMPTS);
}
@Override
public String toString() {
return toStringHelper(getClass())
.add("clientId", getRegistrarId())
.add("failedLoginAttempts", getFailedLoginAttempts())
.add("serviceExtensionUris", Joiner.on('.').join(nullToEmpty(getServiceExtensionUris())))
.toString();
}
}
@@ -14,29 +14,49 @@
package google.registry.flows;
import static com.google.common.base.MoreObjects.toStringHelper;
import static google.registry.util.CollectionUtils.nullToEmpty;
import com.google.common.base.Joiner;
import google.registry.request.Response;
import java.util.Set;
/** Object to allow setting and retrieving session information in flows. */
public interface SessionMetadata {
public abstract class SessionMetadata {
protected static final char URI_SEPARATOR = '|';
/**
* Invalidates the session. A new instance must be created after this for future sessions.
* Attempts to invoke methods of this class after this method has been called will throw
* {@code IllegalStateException}.
* Attempts to invoke methods of this class after this method has been called will throw {@code
* IllegalStateException}.
*/
void invalidate();
public abstract void invalidate();
String getRegistrarId();
public abstract String getRegistrarId();
Set<String> getServiceExtensionUris();
public abstract Set<String> getServiceExtensionUris();
int getFailedLoginAttempts();
public abstract int getFailedLoginAttempts();
void setRegistrarId(String registrarId);
public abstract void setRegistrarId(String registrarId);
void setServiceExtensionUris(Set<String> serviceExtensionUris);
public abstract void setServiceExtensionUris(Set<String> serviceExtensionUris);
void incrementFailedLoginAttempts();
public abstract void incrementFailedLoginAttempts();
void resetFailedLoginAttempts();
public abstract void resetFailedLoginAttempts();
@Override
public String toString() {
return toStringHelper(getClass())
.add("clientId", getRegistrarId())
.add("failedLoginAttempts", getFailedLoginAttempts())
.add(
"serviceExtensionUris",
Joiner.on(URI_SEPARATOR).join(nullToEmpty(getServiceExtensionUris())))
.toString();
}
public void save(Response response) {}
}
@@ -14,16 +14,13 @@
package google.registry.flows;
import static com.google.common.base.MoreObjects.toStringHelper;
import static com.google.common.base.Preconditions.checkNotNull;
import static google.registry.util.CollectionUtils.nullToEmpty;
import com.google.common.base.Joiner;
import com.google.common.collect.ImmutableSet;
import java.util.Set;
/** A read-only {@link SessionMetadata} that doesn't support login/logout. */
public class StatelessRequestSessionMetadata implements SessionMetadata {
public class StatelessRequestSessionMetadata extends SessionMetadata {
private final String registrarId;
private final ImmutableSet<String> serviceExtensionUris;
@@ -74,13 +71,6 @@ public class StatelessRequestSessionMetadata implements SessionMetadata {
throw new UnsupportedOperationException();
}
@Override
public String toString() {
return toStringHelper(getClass())
.add("clientId", getRegistrarId())
.add("failedLoginAttempts", getFailedLoginAttempts())
.add("serviceExtensionUris", Joiner.on('.').join(nullToEmpty(getServiceExtensionUris())))
.toString();
}
}
@@ -0,0 +1,96 @@
// Copyright 2025 The Nomulus Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package google.registry.module;
import static google.registry.persistence.transaction.TransactionManagerFactory.tm;
import static jakarta.servlet.http.HttpServletResponse.SC_OK;
import com.google.common.flogger.FluentLogger;
import google.registry.request.Action;
import google.registry.request.Action.GaeService;
import google.registry.request.Action.GkeService;
import google.registry.request.auth.Auth;
import jakarta.inject.Inject;
import jakarta.servlet.http.HttpServletResponse;
public class ReadinessProbeAction implements Runnable {
private static final FluentLogger logger = FluentLogger.forEnclosingClass();
private final HttpServletResponse rsp;
public ReadinessProbeAction(HttpServletResponse rsp) {
this.rsp = rsp;
}
/**
* Executes the readiness check.
*
* <p>Performs a simple database query and sets the HTTP response status to OK (200) upon
* successful completion. Throws a runtime exception if the database query fails.
*/
@Override
public final void run() {
logger.atInfo().log("Performing readiness check database query...");
try {
tm().transact(() -> tm().query("SELECT version()", Void.class));
rsp.setStatus(SC_OK);
logger.atInfo().log("Readiness check successful.");
} catch (Exception e) {
logger.atWarning().withCause(e).log("Readiness check failed:");
throw new RuntimeException("Readiness check failed during database query", e);
}
}
@Action(
service = GaeService.DEFAULT,
gkeService = GkeService.CONSOLE,
path = ReadinessProbeConsoleAction.PATH,
auth = Auth.AUTH_PUBLIC)
public static class ReadinessProbeConsoleAction extends ReadinessProbeAction {
public static final String PATH = "/ready/console";
@Inject
public ReadinessProbeConsoleAction(HttpServletResponse rsp) {
super(rsp);
}
}
@Action(
service = GaeService.PUBAPI,
gkeService = GkeService.PUBAPI,
path = ReadinessProbeActionPubApi.PATH,
auth = Auth.AUTH_PUBLIC)
public static class ReadinessProbeActionPubApi extends ReadinessProbeAction {
public static final String PATH = "/ready/pubapi";
@Inject
public ReadinessProbeActionPubApi(HttpServletResponse rsp) {
super(rsp);
}
}
@Action(
service = GaeService.DEFAULT,
gkeService = GkeService.FRONTEND,
path = ReadinessProbeActionFrontend.PATH,
auth = Auth.AUTH_PUBLIC)
public static final class ReadinessProbeActionFrontend extends ReadinessProbeAction {
public static final String PATH = "/ready/frontend";
@Inject
public ReadinessProbeActionFrontend(HttpServletResponse rsp) {
super(rsp);
}
}
}
@@ -58,10 +58,14 @@ import google.registry.flows.TlsCredentials.EppTlsModule;
import google.registry.flows.custom.CustomLogicModule;
import google.registry.loadtest.LoadTestAction;
import google.registry.loadtest.LoadTestModule;
import google.registry.module.ReadinessProbeAction.ReadinessProbeActionFrontend;
import google.registry.module.ReadinessProbeAction.ReadinessProbeActionPubApi;
import google.registry.module.ReadinessProbeAction.ReadinessProbeConsoleAction;
import google.registry.monitoring.whitebox.WhiteboxModule;
import google.registry.rdap.RdapAutnumAction;
import google.registry.rdap.RdapDomainAction;
import google.registry.rdap.RdapDomainSearchAction;
import google.registry.rdap.RdapEmptyAction;
import google.registry.rdap.RdapEntityAction;
import google.registry.rdap.RdapEntitySearchAction;
import google.registry.rdap.RdapHelpAction;
@@ -255,12 +259,20 @@ interface RequestComponent {
PublishSpec11ReportAction publishSpec11ReportAction();
ReadinessProbeConsoleAction readinessProbeConsoleAction();
ReadinessProbeActionPubApi readinessProbeActionPubApi();
ReadinessProbeActionFrontend readinessProbeActionFrontend();
RdapAutnumAction rdapAutnumAction();
RdapDomainAction rdapDomainAction();
RdapDomainSearchAction rdapDomainSearchAction();
RdapEmptyAction rdapEmptyAction();
RdapEntityAction rdapEntityAction();
RdapEntitySearchAction rdapEntitySearchAction();
@@ -21,6 +21,8 @@ import google.registry.dns.DnsModule;
import google.registry.flows.EppTlsAction;
import google.registry.flows.FlowComponent;
import google.registry.flows.TlsCredentials.EppTlsModule;
import google.registry.module.ReadinessProbeAction.ReadinessProbeActionFrontend;
import google.registry.module.ReadinessProbeAction.ReadinessProbeConsoleAction;
import google.registry.monitoring.whitebox.WhiteboxModule;
import google.registry.request.RequestComponentBuilder;
import google.registry.request.RequestModule;
@@ -82,6 +84,10 @@ public interface FrontendRequestComponent {
FlowComponent.Builder flowComponentBuilder();
ReadinessProbeActionFrontend readinessProbeActionFrontend();
ReadinessProbeConsoleAction readinessProbeConsoleAction();
RegistrarsAction registrarsAction();
SecurityAction securityAction();
@@ -20,10 +20,12 @@ import google.registry.dns.DnsModule;
import google.registry.flows.CheckApiAction;
import google.registry.flows.CheckApiAction.CheckApiModule;
import google.registry.flows.TlsCredentials.EppTlsModule;
import google.registry.module.ReadinessProbeAction.ReadinessProbeActionPubApi;
import google.registry.monitoring.whitebox.WhiteboxModule;
import google.registry.rdap.RdapAutnumAction;
import google.registry.rdap.RdapDomainAction;
import google.registry.rdap.RdapDomainSearchAction;
import google.registry.rdap.RdapEmptyAction;
import google.registry.rdap.RdapEntityAction;
import google.registry.rdap.RdapEntitySearchAction;
import google.registry.rdap.RdapHelpAction;
@@ -55,12 +57,16 @@ public interface PubApiRequestComponent {
RdapAutnumAction rdapAutnumAction();
RdapDomainAction rdapDomainAction();
RdapDomainSearchAction rdapDomainSearchAction();
RdapEmptyAction rdapEmptyAction();
RdapEntityAction rdapEntityAction();
RdapEntitySearchAction rdapEntitySearchAction();
RdapHelpAction rdapHelpAction();
RdapIpAction rdapDefaultAction();
RdapNameserverAction rdapNameserverAction();
RdapNameserverSearchAction rdapNameserverSearchAction();
ReadinessProbeActionPubApi readinessProbeActionPubApi();
WhoisHttpAction whoisHttpAction();
WhoisAction whoisAction();
@@ -0,0 +1,54 @@
// Copyright 2025 The Nomulus Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package google.registry.rdap;
import static google.registry.request.Action.Method.GET;
import static google.registry.request.Action.Method.HEAD;
import google.registry.request.Action;
import google.registry.request.Response;
import google.registry.request.auth.Auth;
import jakarta.inject.Inject;
import java.io.IOException;
/**
* RDAP action that serves the empty string, redirecting to the help page.
*
* <p>This isn't technically required, but if someone requests the base url it seems nice to give
* them the help response.
*/
@Action(
service = Action.GaeService.PUBAPI,
path = "/rdap/",
method = {GET, HEAD},
auth = Auth.AUTH_PUBLIC)
public class RdapEmptyAction implements Runnable {
private final Response response;
@Inject
public RdapEmptyAction(Response response) {
this.response = response;
}
@Override
public void run() {
try {
response.sendRedirect(RdapHelpAction.PATH);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
@@ -31,12 +31,14 @@ import java.util.Optional;
/** RDAP (new WHOIS) action for help requests. */
@Action(
service = GaeService.PUBAPI,
path = "/rdap/help",
path = RdapHelpAction.PATH,
method = {GET, HEAD},
isPrefix = true,
auth = Auth.AUTH_PUBLIC)
public class RdapHelpAction extends RdapActionBase {
public static final String PATH = "/rdap/help";
/** The help path for the RDAP terms of service. */
public static final String TOS_PATH = "/tos";
@@ -143,8 +143,11 @@ public class RequestHandler<C> {
GkeService service = Action.ServiceGetter.get(route.get().action());
String expectedDomain = RegistryConfig.getServiceUrl(service).getHost();
String actualDomain = req.getServerName();
// If the hostname is "localhost", it must have come from the sidecar proxy.
if (!Objects.equals("localhost", actualDomain)
// If the request doesn't come from GKE readiness prober
String maybeUserAgent = Optional.ofNullable(req.getHeader("User-Agent")).orElse("");
if (!maybeUserAgent.startsWith("kube-probe")
// If the hostname is "localhost", it must have come from the sidecar proxy.
&& !Objects.equals("localhost", actualDomain)
&& !Objects.equals(actualDomain, expectedDomain)) {
logger.atWarning().log(
"Actual domain %s does not match expected domain %s", actualDomain, expectedDomain);
@@ -0,0 +1,212 @@
// Copyright 2025 The Nomulus Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package google.registry.flows;
import static com.google.common.truth.Truth.assertThat;
import static google.registry.flows.CookieSessionMetadata.COOKIE_NAME;
import static google.registry.flows.CookieSessionMetadata.decode;
import static google.registry.flows.CookieSessionMetadata.encode;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import com.google.common.collect.ImmutableSet;
import google.registry.testing.FakeResponse;
import jakarta.servlet.http.HttpServletRequest;
import org.junit.jupiter.api.Test;
/** Unit tests for {@link CookieSessionMetadata}. */
public class CookieSessionMetadataTest {
private HttpServletRequest request = mock(HttpServletRequest.class);
private FakeResponse response = new FakeResponse();
private CookieSessionMetadata cookieSessionMetadata = new CookieSessionMetadata(request);
@Test
void testNoCookie() {
assertThat(cookieSessionMetadata.getRegistrarId()).isNull();
assertThat(cookieSessionMetadata.getFailedLoginAttempts()).isEqualTo(0);
assertThat(cookieSessionMetadata.getServiceExtensionUris()).isEmpty();
}
@Test
void testCookieWithAllFields() {
when(request.getHeader("Cookie"))
.thenReturn(
"THIS_COOKIE=foo; SESSION_INFO="
+ encode(
"CookieSessionMetadata{clientId=test_registrar, failedLoginAttempts=5, "
+ " serviceExtensionUris=A|B|C}")
+ "; THAT_COOKIE=bar");
cookieSessionMetadata = new CookieSessionMetadata(request);
assertThat(cookieSessionMetadata.getRegistrarId()).isEqualTo("test_registrar");
assertThat(cookieSessionMetadata.getFailedLoginAttempts()).isEqualTo(5);
assertThat(cookieSessionMetadata.getServiceExtensionUris()).containsExactly("A", "B", "C");
}
@Test
void testCookieWithNullRegistrar() {
when(request.getHeader("Cookie"))
.thenReturn(
"SESSION_INFO="
+ encode(
"CookieSessionMetadata{clientId=null, failedLoginAttempts=5, "
+ " serviceExtensionUris=A|B|C}"));
cookieSessionMetadata = new CookieSessionMetadata(request);
assertThat(cookieSessionMetadata.getRegistrarId()).isNull();
assertThat(cookieSessionMetadata.getFailedLoginAttempts()).isEqualTo(5);
assertThat(cookieSessionMetadata.getServiceExtensionUris()).containsExactly("A", "B", "C");
}
@Test
void testCookieWithEmptyExtension() {
when(request.getHeader("Cookie"))
.thenReturn(
"SESSION_INFO="
+ encode(
"CookieSessionMetadata{clientId=test_registrar, failedLoginAttempts=5, "
+ " serviceExtensionUris=}"));
cookieSessionMetadata = new CookieSessionMetadata(request);
assertThat(cookieSessionMetadata.getRegistrarId()).isEqualTo("test_registrar");
assertThat(cookieSessionMetadata.getFailedLoginAttempts()).isEqualTo(5);
assertThat(cookieSessionMetadata.getServiceExtensionUris()).isEmpty();
}
@Test
void testCookieWithSingleExtension() {
when(request.getHeader("Cookie"))
.thenReturn(
"SESSION_INFO="
+ encode(
"CookieSessionMetadata{clientId=test_registrar, failedLoginAttempts=5, "
+ " serviceExtensionUris=Foo}"));
cookieSessionMetadata = new CookieSessionMetadata(request);
assertThat(cookieSessionMetadata.getRegistrarId()).isEqualTo("test_registrar");
assertThat(cookieSessionMetadata.getFailedLoginAttempts()).isEqualTo(5);
assertThat(cookieSessionMetadata.getServiceExtensionUris()).containsExactly("Foo");
}
@Test
void testIncrementFailedLoginAttempts() {
when(request.getHeader("Cookie"))
.thenReturn(
"SESSION_INFO="
+ encode(
"CookieSessionMetadata{clientId=test_registrar, failedLoginAttempts=5, "
+ " serviceExtensionUris=Foo}"));
cookieSessionMetadata = new CookieSessionMetadata(request);
cookieSessionMetadata.incrementFailedLoginAttempts();
assertThat(cookieSessionMetadata.getRegistrarId()).isEqualTo("test_registrar");
assertThat(cookieSessionMetadata.getFailedLoginAttempts()).isEqualTo(6);
assertThat(cookieSessionMetadata.getServiceExtensionUris()).containsExactly("Foo");
}
@Test
void testResetFailedLoginAttempts() {
when(request.getHeader("Cookie"))
.thenReturn(
"SESSION_INFO="
+ encode(
"CookieSessionMetadata{clientId=test_registrar, failedLoginAttempts=5, "
+ " serviceExtensionUris=Foo}"));
cookieSessionMetadata = new CookieSessionMetadata(request);
cookieSessionMetadata.resetFailedLoginAttempts();
assertThat(cookieSessionMetadata.getRegistrarId()).isEqualTo("test_registrar");
assertThat(cookieSessionMetadata.getFailedLoginAttempts()).isEqualTo(0);
assertThat(cookieSessionMetadata.getServiceExtensionUris()).containsExactly("Foo");
}
@Test
void testSetRegistrarId() {
when(request.getHeader("Cookie"))
.thenReturn(
"SESSION_INFO="
+ encode(
"CookieSessionMetadata{clientId=test_registrar, failedLoginAttempts=5, "
+ " serviceExtensionUris=Foo}"));
cookieSessionMetadata = new CookieSessionMetadata(request);
cookieSessionMetadata.setRegistrarId("new_registrar");
assertThat(cookieSessionMetadata.getRegistrarId()).isEqualTo("new_registrar");
assertThat(cookieSessionMetadata.getFailedLoginAttempts()).isEqualTo(5);
assertThat(cookieSessionMetadata.getServiceExtensionUris()).containsExactly("Foo");
}
@Test
void testSetExtensions() {
when(request.getHeader("Cookie"))
.thenReturn(
"SESSION_INFO="
+ encode(
"CookieSessionMetadata{clientId=test_registrar, failedLoginAttempts=5, "
+ " serviceExtensionUris=Foo}"));
cookieSessionMetadata = new CookieSessionMetadata(request);
cookieSessionMetadata.setServiceExtensionUris(ImmutableSet.of("Bar", "Baz", "foo:bar:baz-1.3"));
assertThat(cookieSessionMetadata.getRegistrarId()).isEqualTo("test_registrar");
assertThat(cookieSessionMetadata.getFailedLoginAttempts()).isEqualTo(5);
assertThat(cookieSessionMetadata.getServiceExtensionUris())
.containsExactly("Bar", "Baz", "foo:bar:baz-1.3");
}
@Test
void testSetEmptyExtensions() {
when(request.getHeader("Cookie"))
.thenReturn(
"SESSION_INFO="
+ encode(
"CookieSessionMetadata{clientId=test_registrar, failedLoginAttempts=5, "
+ " serviceExtensionUris=Foo}"));
cookieSessionMetadata = new CookieSessionMetadata(request);
cookieSessionMetadata.setServiceExtensionUris(ImmutableSet.of());
assertThat(cookieSessionMetadata.getRegistrarId()).isEqualTo("test_registrar");
assertThat(cookieSessionMetadata.getFailedLoginAttempts()).isEqualTo(5);
assertThat(cookieSessionMetadata.getServiceExtensionUris()).isEmpty();
}
@Test
void testInvalidate() {
when(request.getHeader("Cookie"))
.thenReturn(
"SESSION_INFO="
+ encode(
"CookieSessionMetadata{clientId=test_registrar, failedLoginAttempts=5, "
+ " serviceExtensionUris=Foo}"));
cookieSessionMetadata = new CookieSessionMetadata(request);
cookieSessionMetadata.invalidate();
assertThat(cookieSessionMetadata.getRegistrarId()).isNull();
assertThat(cookieSessionMetadata.getFailedLoginAttempts()).isEqualTo(0);
assertThat(cookieSessionMetadata.getServiceExtensionUris()).isEmpty();
}
@Test
void testSave() {
cookieSessionMetadata.save(response);
String value =
decode(
response.getHeaders().get("Set-Cookie").toString().substring(COOKIE_NAME.length() + 1));
assertThat(value)
.isEqualTo(
"CookieSessionMetadata{clientId=null, failedLoginAttempts=0, serviceExtensionUris=}");
cookieSessionMetadata.setRegistrarId("new_registrar");
cookieSessionMetadata.setServiceExtensionUris(ImmutableSet.of("Bar", "Baz"));
cookieSessionMetadata.incrementFailedLoginAttempts();
cookieSessionMetadata.save(response);
value =
decode(
response.getHeaders().get("Set-Cookie").toString().substring(COOKIE_NAME.length() + 1));
assertThat(value)
.isEqualTo(
"CookieSessionMetadata{clientId=new_registrar, failedLoginAttempts=1,"
+ " serviceExtensionUris=Bar|Baz}");
}
}
@@ -12,17 +12,19 @@
// See the License for the specific language governing permissions and
// limitations under the License.
package google.registry.flows;
import static com.google.common.truth.Truth.assertThat;
import static java.nio.charset.StandardCharsets.US_ASCII;
import static java.nio.charset.StandardCharsets.UTF_8;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.ArgumentMatchers.same;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import google.registry.testing.FakeHttpSession;
import com.google.common.io.BaseEncoding;
import jakarta.servlet.http.HttpServletRequest;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
@@ -36,18 +38,22 @@ class EppTlsActionTest {
EppTlsAction action = new EppTlsAction();
action.inputXmlBytes = INPUT_XML_BYTES;
action.tlsCredentials = mock(TlsCredentials.class);
action.session = new FakeHttpSession();
action.session.setAttribute("REGISTRAR_ID", "ClientIdentifier");
action.request = mock(HttpServletRequest.class);
when(action.request.getHeader("Cookie"))
.thenReturn(
"SESSION_INFO="
+ BaseEncoding.base64Url().encode("clientId=ClientIdentifier".getBytes(US_ASCII)));
action.eppRequestHandler = mock(EppRequestHandler.class);
action.run();
ArgumentCaptor<SessionMetadata> captor = ArgumentCaptor.forClass(SessionMetadata.class);
verify(action.eppRequestHandler).executeEpp(
captor.capture(),
same(action.tlsCredentials),
eq(EppRequestSource.TLS),
eq(false),
eq(false),
eq(INPUT_XML_BYTES));
verify(action.eppRequestHandler)
.executeEpp(
captor.capture(),
same(action.tlsCredentials),
eq(EppRequestSource.TLS),
eq(false),
eq(false),
eq(INPUT_XML_BYTES));
assertThat(captor.getValue().getRegistrarId()).isEqualTo("ClientIdentifier");
}
}
@@ -0,0 +1,42 @@
// Copyright 2025 The Nomulus Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package google.registry.rdap;
import static com.google.common.truth.Truth.assertThat;
import google.registry.testing.FakeResponse;
import jakarta.servlet.http.HttpServletResponse;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
/** Tests for {@link RdapEmptyAction}. */
public class RdapEmptyActionTest {
private FakeResponse fakeResponse;
private RdapEmptyAction action;
@BeforeEach
void beforeEach() {
fakeResponse = new FakeResponse();
action = new RdapEmptyAction(fakeResponse);
}
@Test
void testRedirect() {
action.run();
assertThat(fakeResponse.getStatus()).isEqualTo(HttpServletResponse.SC_FOUND);
assertThat(fakeResponse.getPayload()).isEqualTo("Redirected to /rdap/help");
}
}
@@ -1,5 +1,6 @@
SERVICE PATH CLASS METHODS OK MIN USER_POLICY
FRONTEND /_dr/epp EppTlsAction POST n APP ADMIN
FRONTEND /ready/frontend ReadinessProbeActionFrontend GET n NONE PUBLIC
CONSOLE /console-api/bulk-domain ConsoleBulkDomainAction POST n USER PUBLIC
CONSOLE /console-api/domain ConsoleDomainGetAction GET n USER PUBLIC
CONSOLE /console-api/domain-list ConsoleDomainListAction GET n USER PUBLIC
@@ -15,3 +16,4 @@ CONSOLE /console-api/settings/security SecurityAction POST
CONSOLE /console-api/settings/whois-fields WhoisRegistrarFieldsAction POST n USER PUBLIC
CONSOLE /console-api/userdata ConsoleUserDataAction GET n USER PUBLIC
CONSOLE /console-api/users ConsoleUsersAction GET,POST,DELETE,PUT n USER PUBLIC
CONSOLE /ready/console ReadinessProbeConsoleAction GET n NONE PUBLIC
@@ -1,6 +1,7 @@
SERVICE PATH CLASS METHODS OK MIN USER_POLICY
PUBAPI /_dr/whois WhoisAction POST n APP ADMIN
PUBAPI /check CheckApiAction GET n NONE PUBLIC
PUBAPI /rdap/ RdapEmptyAction GET,HEAD n NONE PUBLIC
PUBAPI /rdap/autnum/(*) RdapAutnumAction GET,HEAD n NONE PUBLIC
PUBAPI /rdap/domain/(*) RdapDomainAction GET,HEAD n NONE PUBLIC
PUBAPI /rdap/domains RdapDomainSearchAction GET,HEAD n NONE PUBLIC
@@ -10,4 +11,5 @@ PUBAPI /rdap/help(*) RdapHelpAction GET,HEAD n NONE PUBLIC
PUBAPI /rdap/ip/(*) RdapIpAction GET,HEAD n NONE PUBLIC
PUBAPI /rdap/nameserver/(*) RdapNameserverAction GET,HEAD n NONE PUBLIC
PUBAPI /rdap/nameservers RdapNameserverSearchAction GET,HEAD n NONE PUBLIC
PUBAPI /ready/pubapi ReadinessProbeActionPubApi GET n NONE PUBLIC
PUBAPI /whois/(*) WhoisHttpAction GET n NONE PUBLIC
@@ -1,5 +1,6 @@
SERVICE PATH CLASS METHODS OK MIN USER_POLICY
FRONTEND /_dr/epp EppTlsAction POST n APP ADMIN
FRONTEND /ready/frontend ReadinessProbeActionFrontend GET n NONE PUBLIC
BACKEND /_dr/admin/createGroups CreateGroupsAction POST n APP ADMIN
BACKEND /_dr/admin/list/domains ListDomainsAction GET,POST n APP ADMIN
BACKEND /_dr/admin/list/hosts ListHostsAction GET,POST n APP ADMIN
@@ -56,6 +57,7 @@ BACKEND /_dr/task/uploadBsaUnavailableNames UploadBsaUnavailable
BACKEND /_dr/task/wipeOutContactHistoryPii WipeOutContactHistoryPiiAction GET n APP ADMIN
PUBAPI /_dr/whois WhoisAction POST n APP ADMIN
PUBAPI /check CheckApiAction GET n NONE PUBLIC
PUBAPI /rdap/ RdapEmptyAction GET,HEAD n NONE PUBLIC
PUBAPI /rdap/autnum/(*) RdapAutnumAction GET,HEAD n NONE PUBLIC
PUBAPI /rdap/domain/(*) RdapDomainAction GET,HEAD n NONE PUBLIC
PUBAPI /rdap/domains RdapDomainSearchAction GET,HEAD n NONE PUBLIC
@@ -65,6 +67,7 @@ PUBAPI /rdap/help(*) RdapHelpAction
PUBAPI /rdap/ip/(*) RdapIpAction GET,HEAD n NONE PUBLIC
PUBAPI /rdap/nameserver/(*) RdapNameserverAction GET,HEAD n NONE PUBLIC
PUBAPI /rdap/nameservers RdapNameserverSearchAction GET,HEAD n NONE PUBLIC
PUBAPI /ready/pubapi ReadinessProbeActionPubApi GET n NONE PUBLIC
PUBAPI /whois/(*) WhoisHttpAction GET n NONE PUBLIC
CONSOLE /console-api/bulk-domain ConsoleBulkDomainAction POST n USER PUBLIC
CONSOLE /console-api/domain ConsoleDomainGetAction GET n USER PUBLIC
@@ -81,3 +84,4 @@ CONSOLE /console-api/settings/security SecurityAction
CONSOLE /console-api/settings/whois-fields WhoisRegistrarFieldsAction POST n USER PUBLIC
CONSOLE /console-api/userdata ConsoleUserDataAction GET n USER PUBLIC
CONSOLE /console-api/users ConsoleUsersAction GET,POST,DELETE,PUT n USER PUBLIC
CONSOLE /ready/console ReadinessProbeConsoleAction GET n NONE PUBLIC
+2 -1
View File
@@ -50,7 +50,7 @@ tasks.register('stage') {
}
tasks.register('buildNomulusImage', Exec) {
commandLine 'docker', 'build', '-t', 'nomulus', '.'
commandLine 'docker', 'build', '-t', 'nomulus', '.', '--pull'
dependsOn(tasks.named('stage'))
}
@@ -137,3 +137,4 @@ tasks.register('getEndpoints', Exec) {
}
project.build.dependsOn(tasks.named('buildNomulusImage'))
rootProject.deploy.dependsOn(tasks.named('deployNomulus'))
+2 -13
View File
@@ -39,7 +39,7 @@ do
sed s/ENVIRONMENT/"${environment}"/g | \
sed s/PROXY_ENV/"${environment}"/g | \
sed s/EPP/"epp"/g | \
kubectl apply -f -
kubectl apply --grace-period=1 -f -
kubectl rollout restart deployment/${service}
# canary
sed s/GCP_PROJECT/"${project}"/g "./kubernetes/nomulus-${service}.yaml" | \
@@ -47,7 +47,7 @@ do
sed s/PROXY_ENV/"${environment}_canary"/g | \
sed s/EPP/"epp-canary"/g | \
sed s/"${service}"/"${service}-canary"/g | \
kubectl apply -f -
kubectl apply --grace-period=1 -f -
kubectl rollout restart deployment/${service}-canary
done
kubectl apply -f "./kubernetes/gateway/nomulus-gateway.yaml"
@@ -62,15 +62,4 @@ do
kubectl apply -f -
done
# Restart proxies
while read line
do
parts=(${line})
echo "Updating cluster ${parts[0]} in location ${parts[1]}..."
gcloud container clusters get-credentials ${parts[0]} \
--project ${project} --location ${parts[1]}
kubectl rollout restart deployment/proxy-deployment
kubectl rollout restart deployment/proxy-deployment-canary
done < <(gcloud container clusters list --project ${project} | grep proxy-cluster)
kubectl config use-context "$current_context"
+9
View File
@@ -20,6 +20,15 @@ spec:
ports:
- containerPort: 8080
name: http
startupProbe:
httpGet:
port: 8080
path: /ready/console
initialDelaySeconds: 1
timeoutSeconds: 60
successThreshold: 1
failureThreshold: 3
periodSeconds: 30
resources:
requests:
# explicit pod-slots 0 is required in order to downgrade node
+2 -2
View File
@@ -82,8 +82,8 @@ spec:
apiVersion: apps/v1
kind: Deployment
name: frontend
minReplicas: 15
maxReplicas: 15
minReplicas: 5
maxReplicas: 20
metrics:
- type: Resource
resource:
+18 -9
View File
@@ -20,6 +20,15 @@ spec:
ports:
- containerPort: 8080
name: http
startupProbe:
httpGet:
port: 8080
path: /ready/pubapi
initialDelaySeconds: 1
timeoutSeconds: 60
successThreshold: 1
failureThreshold: 3
periodSeconds: 30
resources:
requests:
# explicit pod-slots 0 is required in order to downgrade node
@@ -62,12 +71,12 @@ spec:
minReplicas: 5
maxReplicas: 15
metrics:
- type: Resource
resource:
name: cpu
target:
type: Utilization
averageUtilization: 100
- type: Resource
resource:
name: cpu
target:
type: Utilization
averageUtilization: 100
---
apiVersion: v1
kind: Service
@@ -77,9 +86,9 @@ spec:
selector:
service: pubapi
ports:
- port: 80
targetPort: http
name: http
- port: 80
targetPort: http
name: http
---
apiVersion: net.gke.io/v1
kind: ServiceExport
@@ -42,7 +42,6 @@ import java.security.cert.CertificateException;
import java.security.cert.CertificateExpiredException;
import java.security.cert.CertificateNotYetValidException;
import java.security.cert.X509Certificate;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.stream.Stream;
@@ -272,17 +271,11 @@ class SslServerInitializerTest {
getClientHandler(
sslProvider, serverSsc.cert(), clientSsc.key(), clientSsc.cert(), "TLSv1.1", null));
ImmutableList<Integer> jdkVersion =
Arrays.stream(System.getProperty("java.version").split("\\."))
.map(Integer::parseInt)
.collect(ImmutableList.toImmutableList());
// In JDK v11.0.11 and above, TLS 1.1 is not supported anymore, in which case attempting to
// connect with TLS 1.1 results in a ClosedChannelException instead of a SSLHandShakeException.
// See https://www.oracle.com/java/technologies/javase/11-0-11-relnotes.html#JDK-8202343
Class<? extends Exception> rootCause =
sslProvider == SslProvider.JDK
&& compareSemanticVersion(jdkVersion, ImmutableList.of(11, 0, 11))
? ClosedChannelException.class
: SSLHandshakeException.class;
+1 -1
View File
@@ -15,7 +15,7 @@
createUberJar('deployJar', 'proxy_server', 'google.registry.proxy.ProxyServer')
task buildProxyImage(dependsOn: deployJar, type: Exec) {
commandLine 'docker', 'build', '-t', 'proxy', '.'
commandLine 'docker', 'build', '-t', 'proxy', '.', '--pull'
}
task tagProxyImage(dependsOn: buildProxyImage, type: Exec) {