1
0
mirror of https://github.com/google/nomulus synced 2026-07-09 17:46:52 +00:00

Compare commits

...

4 Commits

Author SHA1 Message Date
gbrodman 7ce37147c0 Refactor the license check to be a generic presubmit check (#131)
* Refactor the license check to be a generic presubmit check

This includes all of the old presubmits that were in our METADATA file
that are still valid.

* Responses to CR

Added docstrings, refactored the file finder, changed variable names,
and formatted the file

* More respones to CR
2019-06-27 10:08:27 -04:00
Shicong Huang 661e348fcb Stop provisioning RegistryEnvironment from Dagger (#140)
We found that some webdriver tests failed because RegistryEnvironment
was set to 'production' by other test and was carried over to the
webdriver test, and it was nontrivial to fix them because the instance
of RegistryEnvironment was injected into the testing web server.

Also, to eliminate this problem from potential victims, we stopped
provisioning RegistryEnvironment from Dagger. Instead, we just use
RegistryEnvironment.get() function to get the instance, which indeed
retrives the value from system property every time. If any test case
needs to run the test with other environment, it can just simply use
the existing SystemPropertyRule and RegistryEnvironment.${ENV}.setup
to change it.
2019-06-26 16:57:19 -04:00
Lai Jiang 33a7808e9e Disable Javadoc and tests in Java 12 (#135)
The API is deprecated and removed in Java 12. Do not build these
classes when using Java 12, till we migrate to the new API.
2019-06-25 22:19:36 -04:00
gbrodman 16b0c420a2 Use strict versions in NPM versioning (#132)
It'll reduce surprise version changes
2019-06-25 16:10:04 -04:00
21 changed files with 346 additions and 147 deletions
+3 -3
View File
@@ -108,9 +108,9 @@ allprojects {
}
}
task licenseCheck(type: Exec) {
task runPresubmits(type: Exec) {
executable '/usr/bin/python'
args('config/check_license.py')
args('config/presubmits.py')
}
subprojects {
@@ -169,7 +169,7 @@ subprojects {
if (project.name == 'third_party') return
project.tasks.test.dependsOn licenseCheck
project.tasks.test.dependsOn runPresubmits
// Path to code generated with annotation processors. Note that this path is
// chosen by the 'net.ltgt.apt' plugin, and may change if IDE-specific plugins
-47
View File
@@ -1,47 +0,0 @@
# Copyright 2019 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.
import os
import sys
import re
license = r".*Copyright \d{4} The Nomulus Authors\. All Rights Reserved\."
extensions = ("java", "js", "soy", "sql", "py", "sh")
non_included_patterns = {".git", "/build/", "/generated/", "node_modules/", "JUnitBackports.java", }
def should_include_path(path):
for pattern in non_included_patterns:
if pattern in path: return False
return path.endswith(extensions)
def get_files():
result = []
for root, dirnames, filenames in os.walk("."):
paths = [os.path.join(root, filename) for filename in filenames]
result.extend(filter(should_include_path, paths))
return result
if __name__ == "__main__":
all_files = get_files()
failed_files = []
for file in all_files:
with open(file, 'r') as f:
file_content = f.read()
if not re.match(license, file_content, re.DOTALL):
failed_files.append(file)
if failed_files:
print("The following files did not match the license header: " + str(failed_files))
sys.exit(1)
+180
View File
@@ -0,0 +1,180 @@
# Copyright 2019 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.
"""Google-style presubmits for the Nomulus project.
These aren't built in to the static code analysis tools we use (e.g. Checkstyle,
Error Prone) so we must write them manually.
"""
import os
import sys
import re
# We should never analyze any generated files
UNIVERSALLY_SKIPPED_PATTERNS = {"/build/", "/out/"}
# We can't rely on CI to have the Enum package installed so we do this instead.
FORBIDDEN = 1
REQUIRED = 2
class PresubmitCheck:
def __init__(self,
regex,
included_extensions,
skipped_patterns,
regex_type=FORBIDDEN):
"""Define a presubmit check for a particular set of files,
The provided prefix should always or never be included in the files.
Args:
regex: the regular expression to forbid or require
included_extensions: a tuple of extensions that define which files
we run over
skipped_patterns: a set of patterns that will cause any files that
include them to be skipped
regex_type: either FORBIDDEN or REQUIRED--whether or not the regex
must be present or cannot be present.
"""
self.regex = regex
self.included_extensions = included_extensions
self.skipped_patterns = UNIVERSALLY_SKIPPED_PATTERNS.union(skipped_patterns)
self.regex_type = regex_type
def fails(self, file):
""" Determine whether or not this file fails the regex check.
Args:
file: the full path of the file to check
"""
if not file.endswith(self.included_extensions):
return False
for pattern in self.skipped_patterns:
if pattern in file:
return False
with open(file, "r") as f:
file_content = f.read()
matches = re.match(self.regex, file_content, re.DOTALL)
if self.regex_type == FORBIDDEN:
return matches
return not matches
PRESUBMITS = {
# License check
PresubmitCheck(
r".*Copyright 20\d{2} The Nomulus Authors\. All Rights Reserved\.",
("java", "js", "soy", "sql", "py", "sh"), {
".git", "/build/", "/generated/", "node_modules/",
"JUnitBackports.java"
}, REQUIRED):
"File did not include the license header.",
# System.(out|err).println should only appear in tools/
PresubmitCheck(
r".*\bSystem\.(out|err)\.print", "java", {
"StackdriverDashboardBuilder.java", "/tools/", "/example/",
"RegistryTestServerMain.java", "TestServerRule.java",
"FlowDocumentationTool.java"
}):
"System.(out|err).println is only allowed in tools/ packages. Please "
"use a logger instead.",
# Various Soy linting checks
PresubmitCheck(
r".* (/\*)?\* {?@param ",
"soy",
{},
):
"In SOY please use the ({@param name: string} /** User name. */) style"
" parameter passing instead of the ( * @param name User name.) style "
"parameter pasing.",
PresubmitCheck(
r'.*\{[^}]+\w+:\s+"',
"soy",
{},
):
"Please don't use double-quoted string literals in Soy parameters",
PresubmitCheck(
r'.*autoescape\s*=\s*"[^s]',
"soy",
{},
):
"All soy templates must use strict autoescaping",
PresubmitCheck(
r".*noAutoescape",
"soy",
{},
):
"All soy templates must use strict autoescaping",
# various JS linting checks
PresubmitCheck(
r".*goog\.base\(",
"js",
{"/node_modules/"},
):
"Use of goog.base is not allowed.",
PresubmitCheck(
r".*goog\.dom\.classes",
"js",
{"/node_modules/"},
):
"Instead of goog.dom.classes, use goog.dom.classlist which is smaller "
"and faster.",
PresubmitCheck(
r".*goog\.getMsg",
"js",
{"/node_modules/"},
):
"Put messages in Soy, instead of using goog.getMsg().",
PresubmitCheck(
r".*(innerHTML|outerHTML)\s*(=|[+]=)([^=]|$)",
"js",
{"/node_modules/"},
):
"Do not assign directly to the dom. Use goog.dom.setTextContent to set"
" to plain text, goog.dom.removeChildren to clear, or "
"soy.renderElement to render anything else",
PresubmitCheck(
r".*console\.(log|info|warn|error)",
"js",
{"/node_modules/", "google/registry/ui/js/util.js"},
):
"JavaScript files should not include console logging."
}
def get_files():
result = []
for root, dirnames, filenames in os.walk("."):
for filename in filenames:
yield os.path.join(root, filename)
if __name__ == "__main__":
failed = False
for file in get_files():
error_messages = []
for presubmit, error_message in PRESUBMITS.items():
if presubmit.fails(file):
error_messages.append(error_message)
if error_messages:
failed = True
print("%s had errors: \n %s" % (file, "\n ".join(error_messages)))
if failed:
sys.exit(1)
+12
View File
@@ -58,12 +58,24 @@ sourceSets {
main {
java {
srcDirs += generatedDir
// Javadoc API is deprecated and removed in Java 12.
// TODO(jianglai): re-enable after migrating to the new Javadoc API
if ((JavaVersion.current().majorVersion as Integer) > 11) {
exclude 'google/registry/documentation/**'
}
}
resources {
exclude '**/*.xjb'
}
}
test {
java {
// Javadoc API is deprecated and removed in Java 12.
// TODO(jianglai): re-enable after migrating to the new Javadoc API
if ((JavaVersion.current().majorVersion as Integer) > 11) {
exclude 'google/registry/documentation/**'
}
}
resources {
exclude '**/*.xjb', '**/*.xsd'
}
@@ -73,7 +73,6 @@ public class DeleteLoadTestDataAction implements Runnable {
@Inject MapreduceRunner mrRunner;
@Inject Response response;
@Inject RegistryEnvironment registryEnvironment;
@Inject
DeleteLoadTestDataAction() {}
@@ -84,7 +83,8 @@ public class DeleteLoadTestDataAction implements Runnable {
// run on production. On other environments, data is fully wiped out occasionally anyway, so
// having some broken data that isn't referred to isn't the end of the world.
checkState(
registryEnvironment != PRODUCTION, "This mapreduce is not safe to run on PRODUCTION.");
!RegistryEnvironment.get().equals(PRODUCTION),
"This mapreduce is not safe to run on PRODUCTION.");
mrRunner
.setJobName("Delete load test data")
@@ -17,6 +17,7 @@ package google.registry.batch;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkState;
import static com.google.common.collect.ImmutableSet.toImmutableSet;
import static google.registry.config.RegistryEnvironment.PRODUCTION;
import static google.registry.mapreduce.MapreduceRunner.PARAM_DRY_RUN;
import static google.registry.model.ResourceTransferUtils.updateForeignKeyIndexDeletionTime;
import static google.registry.model.ofy.ObjectifyService.ofy;
@@ -77,7 +78,6 @@ public class DeleteProberDataAction implements Runnable {
@Inject @Config("registryAdminClientId") String registryAdminClientId;
@Inject MapreduceRunner mrRunner;
@Inject Response response;
@Inject RegistryEnvironment registryEnvironment;
@Inject DeleteProberDataAction() {}
@Override
@@ -96,7 +96,7 @@ public class DeleteProberDataAction implements Runnable {
private ImmutableSet<String> getProberRoidSuffixes() {
checkArgument(
!RegistryEnvironment.PRODUCTION.equals(registryEnvironment)
!PRODUCTION.equals(RegistryEnvironment.get())
|| tlds.stream().allMatch(tld -> tld.endsWith(".test")),
"On production, can only work on TLDs that end with .test");
ImmutableSet<String> deletableTlds =
@@ -727,7 +727,7 @@ public class BigqueryConnection implements AutoCloseable {
.setProjectId(getProjectId())
.setDatasetId(datasetName)))
.execute();
System.err.printf("Created dataset: %s:%s\n", getProjectId(), datasetName);
logger.atInfo().log("Created dataset: %s:%s\n", getProjectId(), datasetName);
return true;
}
return false;
@@ -94,13 +94,6 @@ public final class RegistryConfig {
@Module
public static final class ConfigModule {
private static final RegistryEnvironment REGISTRY_ENVIRONMENT = RegistryEnvironment.get();
@Provides
public static RegistryEnvironment provideRegistryEnvironment() {
return REGISTRY_ENVIRONMENT;
}
@Provides
@Config("projectId")
public static String provideProjectId(RegistryConfigSettings config) {
@@ -14,6 +14,8 @@
package google.registry.dns;
import static google.registry.config.RegistryEnvironment.PRODUCTION;
import com.google.common.collect.ImmutableSet;
import com.google.monitoring.metrics.DistributionFitter;
import com.google.monitoring.metrics.EventMetric;
@@ -180,8 +182,6 @@ public class DnsMetrics {
LABEL_DESCRIPTORS_FOR_LATENCY,
EXPONENTIAL_FITTER);
@Inject RegistryEnvironment registryEnvironment;
@Inject
DnsMetrics() {}
@@ -225,7 +225,7 @@ public class DnsMetrics {
hostsCommittedCount.incrementBy(numberOfHosts, tld, status.name(), dnsWriter);
// We don't want to record the following metrics in production, as they are quite expensive
if (registryEnvironment == RegistryEnvironment.PRODUCTION) {
if (RegistryEnvironment.get().equals(PRODUCTION)) {
return;
}
@@ -17,6 +17,7 @@ package google.registry.ui.server.registrar;
import static com.google.common.base.Preconditions.checkState;
import static com.google.common.net.HttpHeaders.LOCATION;
import static com.google.common.net.HttpHeaders.X_FRAME_OPTIONS;
import static google.registry.config.RegistryEnvironment.PRODUCTION;
import static javax.servlet.http.HttpServletResponse.SC_FORBIDDEN;
import static javax.servlet.http.HttpServletResponse.SC_MOVED_TEMPORARILY;
@@ -70,25 +71,20 @@ import javax.servlet.http.HttpServletRequest;
auth = Auth.AUTH_PUBLIC)
public final class ConsoleOteSetupAction implements Runnable {
private static final int PASSWORD_LENGTH = 16;
private static final FluentLogger logger = FluentLogger.forEnclosingClass();
public static final String PATH = "/registrar-ote-setup";
@VisibleForTesting // webdriver and screenshot tests need this
public static final Supplier<SoyCssRenamingMap> CSS_RENAMING_MAP_SUPPLIER =
SoyTemplateUtils.createCssRenamingMapSupplier(
Resources.getResource("google/registry/ui/css/registrar_bin.css.js"),
Resources.getResource("google/registry/ui/css/registrar_dbg.css.js"));
private static final int PASSWORD_LENGTH = 16;
private static final FluentLogger logger = FluentLogger.forEnclosingClass();
private static final Supplier<SoyTofu> TOFU_SUPPLIER =
SoyTemplateUtils.createTofuSupplier(
google.registry.ui.soy.ConsoleSoyInfo.getInstance(),
google.registry.ui.soy.FormsSoyInfo.getInstance(),
google.registry.ui.soy.AnalyticsSoyInfo.getInstance(),
google.registry.ui.soy.registrar.OteSetupConsoleSoyInfo.getInstance());
@VisibleForTesting // webdriver and screenshot tests need this
public static final Supplier<SoyCssRenamingMap> CSS_RENAMING_MAP_SUPPLIER =
SoyTemplateUtils.createCssRenamingMapSupplier(
Resources.getResource("google/registry/ui/css/registrar_bin.css.js"),
Resources.getResource("google/registry/ui/css/registrar_dbg.css.js"));
@Inject HttpServletRequest req;
@Inject @RequestMethod Method method;
@Inject Response response;
@@ -96,27 +92,49 @@ public final class ConsoleOteSetupAction implements Runnable {
@Inject UserService userService;
@Inject XsrfTokenManager xsrfTokenManager;
@Inject AuthResult authResult;
@Inject RegistryEnvironment registryEnvironment;
@Inject SendEmailUtils sendEmailUtils;
@Inject @Config("logoFilename") String logoFilename;
@Inject @Config("productName") String productName;
@Inject @Config("analyticsConfig") Map<String, Object> analyticsConfig;
@Inject @Named("base58StringGenerator") StringGenerator passwordGenerator;
@Inject @Parameter("clientId") Optional<String> clientId;
@Inject @Parameter("email") Optional<String> email;
@Inject @Parameter("password") Optional<String> optionalPassword;
@Inject ConsoleOteSetupAction() {}
@Inject
@Config("logoFilename")
String logoFilename;
@Inject
@Config("productName")
String productName;
@Inject
@Config("analyticsConfig")
Map<String, Object> analyticsConfig;
@Inject
@Named("base58StringGenerator")
StringGenerator passwordGenerator;
@Inject
@Parameter("clientId")
Optional<String> clientId;
@Inject
@Parameter("email")
Optional<String> email;
@Inject
@Parameter("password")
Optional<String> optionalPassword;
@Inject
ConsoleOteSetupAction() {}
@Override
public void run() {
response.setHeader(X_FRAME_OPTIONS, "SAMEORIGIN"); // Disallow iframing.
response.setHeader("X-Ui-Compatible", "IE=edge"); // Ask IE not to be silly.
response.setHeader(X_FRAME_OPTIONS, "SAMEORIGIN"); // Disallow iframing.
response.setHeader("X-Ui-Compatible", "IE=edge"); // Ask IE not to be silly.
logger.atInfo().log(
"User %s is accessing the OT&E setup page. Method= %s",
registrarAccessor.userIdForLogging(), method);
checkState(registryEnvironment != RegistryEnvironment.PRODUCTION, "Can't create OT&E in prod");
checkState(
!RegistryEnvironment.get().equals(PRODUCTION), "Can't create OT&E in prod");
if (!authResult.userAuthInfo().isPresent()) {
response.setStatus(SC_MOVED_TEMPORARILY);
String location;
@@ -201,11 +219,11 @@ public final class ConsoleOteSetupAction implements Runnable {
data.put("errorMessage", e.getMessage());
response.setPayload(
TOFU_SUPPLIER
.get()
.newRenderer(OteSetupConsoleSoyInfo.FORM_PAGE)
.setCssRenamingMap(CSS_RENAMING_MAP_SUPPLIER.get())
.setData(data)
.render());
.get()
.newRenderer(OteSetupConsoleSoyInfo.FORM_PAGE)
.setCssRenamingMap(CSS_RENAMING_MAP_SUPPLIER.get())
.setData(data)
.render());
}
}
@@ -223,12 +241,11 @@ public final class ConsoleOteSetupAction implements Runnable {
.render());
}
private void sendExternalUpdates(ImmutableMap<String, String> clientIdToTld) {
if (!sendEmailUtils.hasRecipients()) {
return;
}
String environment = Ascii.toLowerCase(String.valueOf(registryEnvironment));
String environment = Ascii.toLowerCase(String.valueOf(RegistryEnvironment.get()));
StringBuilder builder = new StringBuilder();
builder.append(
String.format(
@@ -240,10 +257,7 @@ public final class ConsoleOteSetupAction implements Runnable {
String.format(" Registrar %s with access to TLD %s\n", clientId, tld)));
builder.append(String.format("Gave user %s web access to these Registrars\n", email.get()));
sendEmailUtils.sendEmail(
String.format(
"OT&E for registrar %s created in %s",
clientId.get(),
environment),
String.format("OT&E for registrar %s created in %s", clientId.get(), environment),
builder.toString());
}
}
@@ -107,7 +107,6 @@ public final class ConsoleRegistrarCreatorAction implements Runnable {
@Inject UserService userService;
@Inject XsrfTokenManager xsrfTokenManager;
@Inject AuthResult authResult;
@Inject RegistryEnvironment registryEnvironment;
@Inject SendEmailUtils sendEmailUtils;
@Inject @Config("logoFilename") String logoFilename;
@Inject @Config("productName") String productName;
@@ -354,7 +353,7 @@ public final class ConsoleRegistrarCreatorAction implements Runnable {
if (!sendEmailUtils.hasRecipients()) {
return;
}
String environment = Ascii.toLowerCase(String.valueOf(registryEnvironment));
String environment = Ascii.toLowerCase(String.valueOf(RegistryEnvironment.get()));
String body =
String.format(
"The following registrar was created in %s by %s:\n",
@@ -66,7 +66,7 @@ public final class ConsoleUiAction implements Runnable {
google.registry.ui.soy.registrar.ConsoleSoyInfo.getInstance(),
google.registry.ui.soy.AnalyticsSoyInfo.getInstance());
@VisibleForTesting // webdriver and screenshot tests need this
@VisibleForTesting // webdriver and screenshot tests need this
public static final Supplier<SoyCssRenamingMap> CSS_RENAMING_MAP_SUPPLIER =
SoyTemplateUtils.createCssRenamingMapSupplier(
Resources.getResource("google/registry/ui/css/registrar_bin.css.js"),
@@ -79,18 +79,49 @@ public final class ConsoleUiAction implements Runnable {
@Inject UserService userService;
@Inject XsrfTokenManager xsrfTokenManager;
@Inject AuthResult authResult;
@Inject RegistryEnvironment environment;
@Inject @Config("logoFilename") String logoFilename;
@Inject @Config("productName") String productName;
@Inject @Config("integrationEmail") String integrationEmail;
@Inject @Config("supportEmail") String supportEmail;
@Inject @Config("announcementsEmail") String announcementsEmail;
@Inject @Config("supportPhoneNumber") String supportPhoneNumber;
@Inject @Config("technicalDocsUrl") String technicalDocsUrl;
@Inject @Config("registrarConsoleEnabled") boolean enabled;
@Inject @Config("analyticsConfig") Map<String, Object> analyticsConfig;
@Inject @Parameter(PARAM_CLIENT_ID) Optional<String> paramClientId;
@Inject ConsoleUiAction() {}
@Inject
@Config("logoFilename")
String logoFilename;
@Inject
@Config("productName")
String productName;
@Inject
@Config("integrationEmail")
String integrationEmail;
@Inject
@Config("supportEmail")
String supportEmail;
@Inject
@Config("announcementsEmail")
String announcementsEmail;
@Inject
@Config("supportPhoneNumber")
String supportPhoneNumber;
@Inject
@Config("technicalDocsUrl")
String technicalDocsUrl;
@Inject
@Config("registrarConsoleEnabled")
boolean enabled;
@Inject
@Config("analyticsConfig")
Map<String, Object> analyticsConfig;
@Inject
@Parameter(PARAM_CLIENT_ID)
Optional<String> paramClientId;
@Inject
ConsoleUiAction() {}
@Override
public void run() {
@@ -113,8 +144,8 @@ public final class ConsoleUiAction implements Runnable {
}
User user = authResult.userAuthInfo().get().user();
response.setContentType(MediaType.HTML_UTF_8);
response.setHeader(X_FRAME_OPTIONS, "SAMEORIGIN"); // Disallow iframing.
response.setHeader("X-Ui-Compatible", "IE=edge"); // Ask IE not to be silly.
response.setHeader(X_FRAME_OPTIONS, "SAMEORIGIN"); // Disallow iframing.
response.setHeader("X-Ui-Compatible", "IE=edge"); // Ask IE not to be silly.
SoyMapData data = new SoyMapData();
data.put("logoFilename", logoFilename);
data.put("productName", productName);
@@ -127,7 +158,8 @@ public final class ConsoleUiAction implements Runnable {
if (!enabled) {
response.setStatus(SC_SERVICE_UNAVAILABLE);
response.setPayload(
TOFU_SUPPLIER.get()
TOFU_SUPPLIER
.get()
.newRenderer(ConsoleSoyInfo.DISABLED)
.setCssRenamingMap(CSS_RENAMING_MAP_SUPPLIER.get())
.setData(data)
@@ -139,7 +171,7 @@ public final class ConsoleUiAction implements Runnable {
data.put("xsrfToken", xsrfTokenManager.generateToken(user.getEmail()));
ImmutableSetMultimap<String, Role> roleMap = registrarAccessor.getAllClientIdWithRoles();
data.put("allClientIds", roleMap.keySet());
data.put("environment", environment.toString());
data.put("environment", RegistryEnvironment.get().toString());
// We set the initial value to the value that will show if guessClientId throws.
String clientId = "<null>";
try {
@@ -161,7 +193,8 @@ public final class ConsoleUiAction implements Runnable {
"User %s doesn't have access to registrar console.", authResult.userIdForLogging());
response.setStatus(SC_FORBIDDEN);
response.setPayload(
TOFU_SUPPLIER.get()
TOFU_SUPPLIER
.get()
.newRenderer(ConsoleSoyInfo.WHOAREYOU)
.setCssRenamingMap(CSS_RENAMING_MAP_SUPPLIER.get())
.setData(data)
@@ -175,7 +208,9 @@ public final class ConsoleUiAction implements Runnable {
throw e;
}
String payload = TOFU_SUPPLIER.get()
String payload =
TOFU_SUPPLIER
.get()
.newRenderer(ConsoleSoyInfo.MAIN)
.setCssRenamingMap(CSS_RENAMING_MAP_SUPPLIER.get())
.setData(data)
@@ -18,6 +18,7 @@ import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.collect.ImmutableList.toImmutableList;
import static com.google.common.collect.ImmutableSet.toImmutableSet;
import static com.google.common.collect.Sets.difference;
import static google.registry.config.RegistryEnvironment.PRODUCTION;
import static google.registry.export.sheet.SyncRegistrarsSheetAction.enqueueRegistrarSheetSync;
import static google.registry.model.ofy.ObjectifyService.ofy;
import static google.registry.security.JsonResponseHelper.Status.ERROR;
@@ -92,7 +93,6 @@ public class RegistrarSettingsAction implements Runnable, JsonActionRunner.JsonA
@Inject SendEmailUtils sendEmailUtils;
@Inject AuthenticatedRegistrarAccessor registrarAccessor;
@Inject AuthResult authResult;
@Inject RegistryEnvironment registryEnvironment;
@Inject RegistrarSettingsAction() {}
@@ -334,7 +334,7 @@ public class RegistrarSettingsAction implements Runnable, JsonActionRunner.JsonA
// If a REAL registrar isn't in compliance with regards to having an abuse contact set,
// prevent addition of allowed TLDs until that's fixed.
if (Registrar.Type.REAL.equals(initialRegistrar.getType())
&& RegistryEnvironment.PRODUCTION.equals(registryEnvironment)) {
&& PRODUCTION.equals(RegistryEnvironment.get())) {
checkArgumentPresent(
initialRegistrar.getWhoisAbuseContact(),
"Cannot add allowed TLDs if there is no WHOIS abuse contact set.");
@@ -496,7 +496,7 @@ public class RegistrarSettingsAction implements Runnable, JsonActionRunner.JsonA
return;
}
enqueueRegistrarSheetSync(appEngineServiceUtils.getCurrentVersionHostname("backend"));
String environment = Ascii.toLowerCase(String.valueOf(registryEnvironment));
String environment = Ascii.toLowerCase(String.valueOf(RegistryEnvironment.get()));
sendEmailUtils.sendEmail(
String.format(
"Registrar %s (%s) updated in registry %s environment",
@@ -46,12 +46,14 @@ import google.registry.model.registry.Registry;
import google.registry.model.registry.Registry.TldType;
import google.registry.model.reporting.HistoryEntry;
import google.registry.testing.FakeResponse;
import google.registry.testing.SystemPropertyRule;
import google.registry.testing.mapreduce.MapreduceTestCase;
import java.util.Optional;
import java.util.Set;
import org.joda.money.Money;
import org.joda.time.DateTime;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
@@ -62,6 +64,9 @@ public class DeleteProberDataActionTest extends MapreduceTestCase<DeleteProberDa
private static final DateTime DELETION_TIME = DateTime.parse("2010-01-01T00:00:00.000Z");
@Rule
public final SystemPropertyRule systemPropertyRule = new SystemPropertyRule();
@Before
public void init() {
// Entities in these two should not be touched.
@@ -90,8 +95,8 @@ public class DeleteProberDataActionTest extends MapreduceTestCase<DeleteProberDa
action.response = new FakeResponse();
action.isDryRun = false;
action.tlds = ImmutableSet.of();
action.registryEnvironment = RegistryEnvironment.SANDBOX;
action.registryAdminClientId = "TheRegistrar";
RegistryEnvironment.SANDBOX.setup(systemPropertyRule);
}
private void runMapreduce() throws Exception {
@@ -153,7 +158,7 @@ public class DeleteProberDataActionTest extends MapreduceTestCase<DeleteProberDa
@Test
public void testFail_givenNonDotTestTldOnProd() {
action.tlds = ImmutableSet.of("example");
action.registryEnvironment = RegistryEnvironment.PRODUCTION;
RegistryEnvironment.PRODUCTION.setup(systemPropertyRule);
IllegalArgumentException thrown =
assertThrows(IllegalArgumentException.class, this::runMapreduce);
assertThat(thrown)
@@ -41,6 +41,7 @@ import google.registry.testing.AppEngineRule;
import google.registry.testing.DeterministicStringGenerator;
import google.registry.testing.FakeClock;
import google.registry.testing.FakeResponse;
import google.registry.testing.SystemPropertyRule;
import google.registry.ui.server.SendEmailUtils;
import google.registry.util.EmailMessage;
import google.registry.util.SendEmailService;
@@ -67,6 +68,9 @@ public final class ConsoleOteSetupActionTest {
@Rule public final MockitoRule mocks = MockitoJUnit.rule();
@Rule
public final SystemPropertyRule systemPropertyRule = new SystemPropertyRule();
private final FakeResponse response = new FakeResponse();
private final ConsoleOteSetupAction action = new ConsoleOteSetupAction();
private final User user = new User("marla.singer@example.com", "gmail.com", "12345");
@@ -87,7 +91,6 @@ public final class ConsoleOteSetupActionTest {
action.userService = UserServiceFactory.getUserService();
action.xsrfTokenManager = new XsrfTokenManager(new FakeClock(), action.userService);
action.authResult = AuthResult.create(AuthLevel.USER, UserAuthInfo.create(user, false));
action.registryEnvironment = RegistryEnvironment.UNITTEST;
action.sendEmailUtils =
new SendEmailUtils(
new InternetAddress("outgoing@registry.example"),
@@ -122,7 +125,7 @@ public final class ConsoleOteSetupActionTest {
@Test
public void testGet_authorized_onProduction() {
action.registryEnvironment = RegistryEnvironment.PRODUCTION;
RegistryEnvironment.PRODUCTION.setup(systemPropertyRule);
assertThrows(IllegalStateException.class, action::run);
}
@@ -42,6 +42,7 @@ import google.registry.testing.AppEngineRule;
import google.registry.testing.DeterministicStringGenerator;
import google.registry.testing.FakeClock;
import google.registry.testing.FakeResponse;
import google.registry.testing.SystemPropertyRule;
import google.registry.ui.server.SendEmailUtils;
import google.registry.util.EmailMessage;
import google.registry.util.SendEmailService;
@@ -69,6 +70,9 @@ public final class ConsoleRegistrarCreatorActionTest {
@Rule public final MockitoRule mocks = MockitoJUnit.rule();
@Rule
public final SystemPropertyRule systemPropertyRule = new SystemPropertyRule();
private final FakeResponse response = new FakeResponse();
private final ConsoleRegistrarCreatorAction action = new ConsoleRegistrarCreatorAction();
private final User user = new User("marla.singer@example.com", "gmail.com", "12345");
@@ -89,7 +93,6 @@ public final class ConsoleRegistrarCreatorActionTest {
action.userService = UserServiceFactory.getUserService();
action.xsrfTokenManager = new XsrfTokenManager(new FakeClock(), action.userService);
action.authResult = AuthResult.create(AuthLevel.USER, UserAuthInfo.create(user, false));
action.registryEnvironment = RegistryEnvironment.UNITTEST;
action.sendEmailUtils =
new SendEmailUtils(
new InternetAddress("outgoing@registry.example"),
@@ -142,7 +145,7 @@ public final class ConsoleRegistrarCreatorActionTest {
@Test
public void testGet_authorized_onProduction() {
action.registryEnvironment = RegistryEnvironment.PRODUCTION;
RegistryEnvironment.PRODUCTION.setup(systemPropertyRule);
action.run();
assertThat(response.getPayload()).contains("<h1>Create Registrar</h1>");
assertThat(response.getPayload()).contains("gtag('config', 'sampleId')");
@@ -28,7 +28,6 @@ import com.google.appengine.api.users.UserServiceFactory;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSetMultimap;
import com.google.common.net.MediaType;
import google.registry.config.RegistryEnvironment;
import google.registry.request.auth.AuthLevel;
import google.registry.request.auth.AuthResult;
import google.registry.request.auth.AuthenticatedRegistrarAccessor;
@@ -52,10 +51,11 @@ import org.junit.runners.JUnit4;
public class ConsoleUiActionTest {
@Rule
public final AppEngineRule appEngineRule = AppEngineRule.builder()
.withDatastore()
.withUserService(UserInfo.create("marla.singer@example.com", "12345"))
.build();
public final AppEngineRule appEngineRule =
AppEngineRule.builder()
.withDatastore()
.withUserService(UserInfo.create("marla.singer@example.com", "12345"))
.build();
private final HttpServletRequest request = mock(HttpServletRequest.class);
private final FakeResponse response = new FakeResponse();
@@ -79,7 +79,6 @@ public class ConsoleUiActionTest {
action.xsrfTokenManager = new XsrfTokenManager(new FakeClock(), action.userService);
action.paramClientId = Optional.empty();
action.authResult = AuthResult.create(AuthLevel.USER, UserAuthInfo.create(user, false));
action.environment = RegistryEnvironment.UNITTEST;
action.analyticsConfig = ImmutableMap.of("googleAnalyticsId", "sampleId");
action.registrarAccessor =
@@ -36,6 +36,7 @@ import google.registry.model.registrar.Registrar;
import google.registry.request.auth.AuthenticatedRegistrarAccessor;
import google.registry.request.auth.AuthenticatedRegistrarAccessor.Role;
import google.registry.testing.CertificateSamples;
import google.registry.testing.SystemPropertyRule;
import google.registry.testing.TaskQueueHelper.TaskMatcher;
import google.registry.util.CidrAddressBlock;
import google.registry.util.EmailMessage;
@@ -44,6 +45,7 @@ import java.util.function.BiFunction;
import java.util.function.Function;
import org.json.simple.JSONValue;
import org.json.simple.parser.ParseException;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
@@ -53,6 +55,9 @@ import org.mockito.ArgumentCaptor;
@RunWith(JUnit4.class)
public class RegistrarSettingsActionTest extends RegistrarSettingsActionTestCase {
@Rule
public final SystemPropertyRule systemPropertyRule = new SystemPropertyRule();
@Test
public void testSuccess_updateRegistrarInfo_andSendsNotificationEmail() throws Exception {
String expectedEmailBody = loadFile(getClass(), "update_registrar_email.txt");
@@ -393,7 +398,7 @@ public class RegistrarSettingsActionTest extends RegistrarSettingsActionTestCase
@Test
public void testUpdate_allowedTlds_failedWhenNoWhoisAbuseContactExists() {
setUserAdmin();
action.registryEnvironment = RegistryEnvironment.PRODUCTION;
RegistryEnvironment.PRODUCTION.setup(systemPropertyRule);
Map<String, Object> args = Maps.newHashMap(loadRegistrar(CLIENT_ID).toJsonMap());
args.put("allowedTlds", ImmutableList.of("newtld", "currenttld"));
@@ -33,7 +33,6 @@ import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.ImmutableSetMultimap;
import com.google.common.truth.Truth;
import google.registry.config.RegistryEnvironment;
import google.registry.model.ofy.Ofy;
import google.registry.model.registrar.RegistrarContact;
import google.registry.request.JsonActionRunner;
@@ -116,7 +115,6 @@ public abstract class RegistrarSettingsActionTestCase {
getGSuiteOutgoingEmailDisplayName(),
ImmutableList.of("notification@test.example", "notification2@test.example"),
emailService);
action.registryEnvironment = RegistryEnvironment.get();
action.registrarConsoleMetrics = new RegistrarConsoleMetrics();
action.authResult =
AuthResult.create(
+4 -4
View File
@@ -2278,9 +2278,9 @@
"dev": true
},
"process-nextick-args": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/process-nextick-args/-/process-nextick-args-2.0.0.tgz",
"integrity": "sha512-MtEC1TqN0EU5nephaJ4rAtThHtC86dNN9qCuEhtshvpVBkAW5ZO7BASN9REnF9eoXGcRub+pFuKEpOHE+HbEMw==",
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/process-nextick-args/-/process-nextick-args-2.0.1.tgz",
"integrity": "sha512-3ouUOpQhtgrbOa17J7+uxOTpITYWaGP7/AhoR3+A+/1e9skrzelGi/dXzEYyvbxubEF6Wn2ypscTKiKJFFn1ag==",
"dev": true
},
"progress": {
@@ -2376,7 +2376,7 @@
"core-util-is": "1.0.2",
"inherits": "2.0.3",
"isarray": "1.0.0",
"process-nextick-args": "2.0.0",
"process-nextick-args": "2.0.1",
"safe-buffer": "5.1.2",
"string_decoder": "1.1.1",
"util-deprecate": "1.0.2"
+4 -4
View File
@@ -20,11 +20,11 @@
"google-closure-library": "20190325.0.0"
},
"devDependencies": {
"jasmine-core": "^3.4.0",
"jasmine-core": "3.4.0",
"karma": "3.0.0",
"karma-chrome-launcher": "^2.2.0",
"karma-closure": "^0.1.3",
"karma-jasmine": "^2.0.1",
"karma-chrome-launcher": "2.2.0",
"karma-closure": "0.1.3",
"karma-jasmine": "2.0.1",
"puppeteer": "1.17.0"
}
}