Delete admin console

-------------
Created by MOE: https://github.com/google/moe
MOE_MIGRATED_REVID=116894352
This commit is contained in:
jart 2016-03-10 12:07:55 -08:00 committed by Ben McIlwain
parent 6772b2ef80
commit f2116093b1
33 changed files with 2 additions and 2912 deletions

View file

@ -81,40 +81,6 @@
<url-pattern>/registrar-payment</url-pattern> <url-pattern>/registrar-payment</url-pattern>
</servlet-mapping> </servlet-mapping>
<!-- Admin Console -->
<servlet>
<display-name>Admin UI Servlet</display-name>
<servlet-name>admin-ui</servlet-name>
<servlet-class>com.google.domain.registry.ui.server.admin.AdminUiServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>admin-ui</servlet-name>
<url-pattern>/_dr/admin</url-pattern>
</servlet-mapping>
<servlet>
<display-name>Registry Admin</display-name>
<servlet-name>registry-admin</servlet-name>
<servlet-class>com.google.domain.registry.ui.server.admin.RegistryServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>registry-admin</servlet-name>
<url-pattern>/_dr/admin/registry/*</url-pattern>
</servlet-mapping>
<servlet>
<display-name>Registrar Admin</display-name>
<servlet-name>registrar-admin</servlet-name>
<servlet-class>com.google.domain.registry.ui.server.admin.RegistrarServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>registrar-admin</servlet-name>
<url-pattern>/_dr/admin/registrar/*</url-pattern>
</servlet-mapping>
<!-- WHOIS --> <!-- WHOIS -->
<servlet> <servlet>
<description> <description>
@ -281,26 +247,6 @@
</security-constraint> </security-constraint>
<!-- TODO(b/26776367): Move these files to /assets/sources. --> <!-- TODO(b/26776367): Move these files to /assets/sources. -->
<security-constraint>
<web-resource-collection>
<web-resource-name>admin-bin-js-map</web-resource-name>
<description>No soup for you!</description>
<url-pattern>/assets/js/admin_bin.js.map</url-pattern>
</web-resource-collection>
<auth-constraint>
<role-name>admin</role-name>
</auth-constraint>
</security-constraint>
<security-constraint>
<web-resource-collection>
<web-resource-name>admin-dbg-js</web-resource-name>
<description>No soup for you!</description>
<url-pattern>/assets/js/admin_dbg.js</url-pattern>
</web-resource-collection>
<auth-constraint>
<role-name>admin</role-name>
</auth-constraint>
</security-constraint>
<security-constraint> <security-constraint>
<web-resource-collection> <web-resource-collection>
<web-resource-name>registrar-bin-js-map</web-resource-name> <web-resource-name>registrar-bin-js-map</web-resource-name>
@ -331,16 +277,6 @@
<role-name>admin</role-name> <role-name>admin</role-name>
</auth-constraint> </auth-constraint>
</security-constraint> </security-constraint>
<security-constraint>
<web-resource-collection>
<web-resource-name>admin-dbg-css</web-resource-name>
<description>No soup for you!</description>
<url-pattern>/assets/css/admin_dbg.css</url-pattern>
</web-resource-collection>
<auth-constraint>
<role-name>admin</role-name>
</auth-constraint>
</security-constraint>
<security-constraint> <security-constraint>
<web-resource-collection> <web-resource-collection>
<web-resource-name>registrar-dbg-css</web-resource-name> <web-resource-name>registrar-dbg-css</web-resource-name>

View file

@ -37,7 +37,6 @@ java_binary(
runtime_deps = [ runtime_deps = [
":frontend", ":frontend",
"//java/com/google/domain/registry/monitoring/whitebox", # MetricsTaskServlet "//java/com/google/domain/registry/monitoring/whitebox", # MetricsTaskServlet
"//java/com/google/domain/registry/ui/server/admin", # AdminUiServlet, etc.
"//java/com/google/domain/registry/ui/server/api", # CheckApiServlet "//java/com/google/domain/registry/ui/server/api", # CheckApiServlet
"//java/com/google/domain/registry/ui/server/registrar", # ConsoleUiServlet, etc. "//java/com/google/domain/registry/ui/server/registrar", # ConsoleUiServlet, etc.
], ],

View file

@ -38,6 +38,5 @@ java_binary(
create_executable = 0, create_executable = 0,
runtime_deps = [ runtime_deps = [
":tools", ":tools",
"//java/com/google/domain/registry/ui/server/admin", # VerifyOteServlet
], ],
) )

View file

@ -15,10 +15,8 @@ filegroup(
name = "js_files_recursive", name = "js_files_recursive",
srcs = [ srcs = [
"//java/com/google/domain/registry/ui/js:js_files", "//java/com/google/domain/registry/ui/js:js_files",
"//java/com/google/domain/registry/ui/js/admin:js_files",
"//java/com/google/domain/registry/ui/js/registrar:js_files", "//java/com/google/domain/registry/ui/js/registrar:js_files",
"//java/com/google/domain/registry/ui/soy:js_files", "//java/com/google/domain/registry/ui/soy:js_files",
"//java/com/google/domain/registry/ui/soy/admin:js_files",
"//java/com/google/domain/registry/ui/soy/api:js_files", "//java/com/google/domain/registry/ui/soy/api:js_files",
"//java/com/google/domain/registry/ui/soy/registrar:js_files", "//java/com/google/domain/registry/ui/soy/registrar:js_files",
], ],
@ -27,15 +25,12 @@ filegroup(
filegroup( filegroup(
name = "runfiles", name = "runfiles",
srcs = [ srcs = [
"admin_bin.js",
"admin_bin_map.js",
"brain_bin.js", "brain_bin.js",
"brain_bin_map.js", "brain_bin_map.js",
"registrar_bin.js", "registrar_bin.js",
"registrar_bin_map.js", "registrar_bin_map.js",
":assets_recursive", ":assets_recursive",
"//java/com/google/domain/registry/ui:deps-runfiles.js", "//java/com/google/domain/registry/ui:deps-runfiles.js",
"//java/com/google/domain/registry/ui/css:admin_bin.css",
"//java/com/google/domain/registry/ui/css:registrar_bin.css", "//java/com/google/domain/registry/ui/css:registrar_bin.css",
"//java/com/google/domain/registry/ui/html:html_files", "//java/com/google/domain/registry/ui/html:html_files",
"//javascript/closure:js_files_recursive", "//javascript/closure:js_files_recursive",
@ -73,7 +68,6 @@ closure_js_deps(
name = "deps", name = "deps",
srcs = [ srcs = [
"//java/com/google/domain/registry/ui/js", "//java/com/google/domain/registry/ui/js",
"//java/com/google/domain/registry/ui/js/admin",
"//java/com/google/domain/registry/ui/js/registrar", "//java/com/google/domain/registry/ui/js/registrar",
], ],
) )
@ -83,8 +77,7 @@ SOURCEMAP_SCRUB = (" -e 's@b....-out/[^/]*/bin/@@g'" +
" -e 's@\"java/@\"/assets/sources/java/@g'" + " -e 's@\"java/@\"/assets/sources/java/@g'" +
" -e 's@\"javascript/@\"/assets/sources/javascript/@g'" + " -e 's@\"javascript/@\"/assets/sources/javascript/@g'" +
" -e 's@\"third_party/@\"/assets/sources/third_party/@g'" + " -e 's@\"third_party/@\"/assets/sources/third_party/@g'" +
" -e 's@\"external/@\"/assets/sources/external/@g'" + " -e 's@\"external/@\"/assets/sources/external/@g'")
" -e 's@sources/java/.*/admin_bin.js@js/admin_bin_map.js@g'")
################################################################################ ################################################################################
## Registrar Console ## Registrar Console
@ -164,43 +157,3 @@ genrule(
cmd = "cat $(location brain_bin.js) >$@ && " + cmd = "cat $(location brain_bin.js) >$@ && " +
"echo '//# sourceMappingURL=brain_bin.js.map' >>$@", "echo '//# sourceMappingURL=brain_bin.js.map' >>$@",
) )
################################################################################
## Admin Console
closure_js_binary(
name = "admin_bin",
externs_list = ["//java/com/google/domain/registry/ui/externs"],
main = "registry.admin.main",
deps = [
"//java/com/google/domain/registry/ui/css:admin_bin",
"//java/com/google/domain/registry/ui/js/admin",
],
)
genrule(
name = "admin_bin_sourcemap",
srcs = ["admin_bin.sourcemap"],
outs = ["admin_bin.js.map"],
cmd = "sed $(location admin_bin.sourcemap) " + SOURCEMAP_SCRUB + " >$@",
)
genrule(
name = "admin_mapped",
srcs = ["admin_bin.js"],
outs = ["admin_bin_map.js"],
cmd = "cat $(location admin_bin.js) >$@ && " +
"echo '//# sourceMappingURL=admin_bin.js.map' >>$@",
)
closure_js_binary(
name = "admin_dbg",
debug = 1,
externs_list = ["//java/com/google/domain/registry/ui/externs"],
formatting = "PRETTY_PRINT",
main = "registry.admin.main",
deps = [
"//java/com/google/domain/registry/ui/css:admin_dbg",
"//java/com/google/domain/registry/ui/js/admin",
],
)

View file

@ -48,23 +48,3 @@ closure_css_binary(
debug = 1, debug = 1,
deps = [":registrar_lib"], deps = [":registrar_lib"],
) )
closure_css_library(
name = "admin_lib",
srcs = [
"admin-console.css",
"forms.css",
],
deps = [":registry_lib"],
)
closure_css_binary(
name = "admin_bin",
deps = [":admin_lib"],
)
closure_css_binary(
name = "admin_dbg",
debug = 1,
deps = [":admin_lib"],
)

View file

@ -1,18 +0,0 @@
textarea#clientCertificate {
font-family: monospace;
height: 260px;
white-space: nowrap;
}
/* Registry. */
input#tldStateTransition.tldStateTransition {
width: 40em;
}
tr.section-lead th {
padding-top: 4em;
padding: 1em 0;
border-bottom: solid 1px #ebebeb;
font-size: 1.1em;
font-weight: bold;
}

View file

@ -1,5 +0,0 @@
@import 'kd_components.css';
@import 'registry.css';
@import 'console.css';
@import 'forms.css';
@import 'admin-console.css';

View file

@ -1,20 +0,0 @@
package(default_visibility = ["//java/com/google/domain/registry:registry_project"])
load("//third_party/closure/compiler:closure_js_library.bzl", "closure_js_library")
filegroup(
name = "js_files",
srcs = glob(["*.js"]),
)
closure_js_library(
name = "admin",
srcs = [":js_files"],
deps = [
"//java/com/google/domain/registry/ui/js",
"//java/com/google/domain/registry/ui/soy/admin:Registrar",
"//java/com/google/domain/registry/ui/soy/admin:Registry",
"//javascript/closure",
],
)

View file

@ -1,62 +0,0 @@
// Copyright 2016 Google Inc. 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.
goog.provide('registry.admin.Console');
goog.require('registry.Console');
goog.require('registry.admin.Registrar');
goog.require('registry.admin.Registry');
/**
* The Admin Console.
* @param {string} xsrfToken Populated by server-side soy template.
* @constructor
* @extends {registry.Console}
* @final
*/
registry.admin.Console = function(xsrfToken) {
registry.admin.Console.base(this, 'constructor', null);
/** @type {string} */
this.xsrfToken = xsrfToken;
// XXX: Parent carries session but currently unused. Just using this class to
// get history, butter, etc.
// XXX: This was in parent ctor but was triggering event dispatching before
// ready here.
this.history.setEnabled(true);
};
goog.inherits(registry.admin.Console, registry.Console);
/** @override */
registry.admin.Console.prototype.handleHashChange = function() {
var hashToken = this.history.getToken();
var collection = hashToken.split('/');
var id = null;
// XXX: Should be generalized to deeper paths?
if (collection.length == 2) {
id = collection[1];
}
// Either the path is a registrar type, or default to registry.
if (collection[0] == 'registrar') {
new registry.admin.Registrar(
this, this.xsrfToken, id).bindToDom(hashToken);
} else {
new registry.admin.Registry(
this, this.xsrfToken, id).bindToDom(hashToken);
}
};

View file

@ -1,33 +0,0 @@
// Copyright 2016 Google Inc. 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.
/**
* @fileoverview Entry point for Admin Console.
*/
goog.provide('registry.admin.main');
goog.require('registry.admin.Console');
/**
* Instantiates a registry object, which syncs with the server.
* Sub-templates are invoked based on location/pathname, to choose
* either Registry or Registrar pages.
* @param {string} xsrfToken populated by server-side soy template.
* @export
*/
registry.admin.main = function(xsrfToken) {
new registry.admin.Console(xsrfToken);
};

View file

@ -1,136 +0,0 @@
// Copyright 2016 Google Inc. 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.
goog.provide('registry.admin.Registrar');
goog.require('goog.Uri');
goog.require('goog.dom');
goog.require('goog.events');
goog.require('goog.events.EventType');
goog.require('goog.soy');
goog.require('registry.Resource');
goog.require('registry.ResourceComponent');
goog.require('registry.soy.admin.registrar');
goog.require('registry.util');
/**
* The Registrar class represents server state for registrars and
* binds UI CRUD operations on them.
* @param {!registry.Console} console console singleton.
* @param {string} xsrfToken Security token to pass back to the server.
* @param {?string} registrarName Optional target registrar name.
* @constructor
* @extends {registry.ResourceComponent}
* @final
*/
registry.admin.Registrar = function(console, xsrfToken, registrarName) {
registry.admin.Registrar.base(
this, 'constructor',
console,
new registry.Resource(
new goog.Uri('/_dr/admin/registrar' +
(registrarName ? ('/' + registrarName) : '')),
xsrfToken),
registry.soy.admin.registrar.registrar,
goog.bind(this.renderSet, this));
};
goog.inherits(registry.admin.Registrar, registry.ResourceComponent);
/**
* Show the list of registrars.
* @param {!Element} parentElt In which to render this template.
* @param {!Object} rspObj Result object from server to show.
*/
registry.admin.Registrar.prototype.renderSet = function(parentElt, rspObj) {
goog.soy.renderElement(parentElt,
registry.soy.admin.registrar.registrars,
rspObj);
goog.events.listen(goog.dom.getElement('create-button'),
goog.events.EventType.CLICK,
goog.bind(this.sendCreate, this));
};
/** @override */
registry.admin.Registrar.prototype.renderItem = function(objArgs) {
goog.soy.renderElement(goog.dom.getRequiredElement('reg-content'),
this.itemTmpl,
{
item: objArgs,
readonly: objArgs.readonly
});
};
/** @override */
registry.admin.Registrar.prototype.sendCreate = function() {
var args = registry.util.parseForm('create');
this.resource.create(args,
goog.bind(this.handleUpdateResponse, this),
args['clientIdentifier']);
};
/** @override */
registry.admin.Registrar.prototype.setupEditor = function(objArgs) {
goog.events.listen(goog.dom.getRequiredElement('add-contact-button'),
goog.events.EventType.CLICK,
goog.bind(this.addContactInputForm_, this));
var childNodes = goog.dom.getChildren(
goog.dom.getRequiredElement('contacts'));
for (var i = 0; i < childNodes.length; i++) {
this.enableRemoveButton(childNodes[i]);
}
};
/** @override */
registry.admin.Registrar.prototype.prepareUpdate = function(modelCopy) {
var form = registry.util.parseForm('item');
for (var ndx in form) {
modelCopy[ndx] = form[ndx];
}
var apply = function(obj, ndx, func) {
if (goog.isDefAndNotNull(obj[ndx])) {
obj[ndx] = func(obj[ndx]);
}
};
var splitter = function(val) {
return val.split(',');
};
apply(modelCopy, 'billingIdentifier', parseInt);
apply(modelCopy, 'ianaIdentifier', parseInt);
apply(modelCopy, 'allowedTlds', splitter);
apply(modelCopy, 'ipAddressWhitelist', splitter);
};
/**
* Add a contact input entry form to the page.
* @private
*/
registry.admin.Registrar.prototype.addContactInputForm_ = function() {
var contactsContainer =
goog.dom.getRequiredElement('contacts');
var childCount = contactsContainer.childNodes.length;
var newContactDiv = goog.soy.renderAsElement(
registry.soy.admin.registrar.contactInfo, {
namePrefix: 'contacts[' + childCount + '].'
});
goog.dom.appendChild(contactsContainer, newContactDiv);
this.enableRemoveButton(newContactDiv);
};

View file

@ -1,139 +0,0 @@
// Copyright 2016 Google Inc. 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.
goog.provide('registry.admin.Registry');
goog.require('goog.Uri');
goog.require('goog.dom');
goog.require('goog.events');
goog.require('goog.events.EventType');
goog.require('goog.soy');
goog.require('registry.Resource');
goog.require('registry.ResourceComponent');
goog.require('registry.soy.admin.registry');
goog.require('registry.util');
/**
* The Registry class respresents server state for registries and
* binds UI CRUD operations on them.
* @param {!registry.Console} console console singleton.
* @param {string} xsrfToken Security token to pass back to the server.
* @param {?string} tld Optional target target tld.
* @constructor
* @extends {registry.ResourceComponent}
* @final
*/
registry.admin.Registry = function(console, xsrfToken, tld) {
// XXX: A couple of these args for not complete yet..
registry.admin.Registry.base(
this, 'constructor',
console,
new registry.Resource(
new goog.Uri('/_dr/admin/registry' + (tld ? ('/' + tld) : '')),
xsrfToken),
registry.soy.admin.registry.registry,
goog.bind(this.renderSet, this));
};
goog.inherits(registry.admin.Registry, registry.ResourceComponent);
/** @override */
registry.admin.Registry.prototype.renderItem = function(objArgs) {
goog.soy.renderElement(goog.dom.getRequiredElement('reg-content'),
this.itemTmpl,
{
item: objArgs,
readonly: objArgs.readonly
});
};
/** @override */
registry.admin.Registry.prototype.processItem = function() {
// XXX: Server response syntax should be improved.
var tldStateTransitions = this.model['tldStateTransitions'];
if (tldStateTransitions) {
var transArr = tldStateTransitions.split(',');
tldStateTransitions = '';
for (var i = 0; i < transArr.length; i++) {
var trans = transArr[i];
var parts = trans.split('=');
var dateTime = parts[0].replace(/[ {}]/, '');
// XXX: ACTUALLY improve parsing with server response syntax.
if (parts.length == 1) {
registry.util.butter('pmy needs to fix this CL');
continue;
}
var state = parts[1].replace(/[ {}]/, '');
tldStateTransitions += state + ',' + dateTime;
if (i < transArr.length - 1) {
tldStateTransitions += ';';
}
}
this.model['tldStateTransitions'] = tldStateTransitions;
}
};
/**
* @param {!Element} parentElt In which to render this template.
* @param {!Object} rspObj Result object from server to show.
*/
registry.admin.Registry.prototype.renderSet = function(parentElt, rspObj) {
goog.soy.renderElement(parentElt,
registry.soy.admin.registry.registries,
rspObj);
goog.events.listen(goog.dom.getElement('create-button'),
goog.events.EventType.CLICK,
goog.bind(this.sendCreate, this));
};
/** @override */
registry.admin.Registry.prototype.sendCreate = function() {
var args = registry.util.parseForm('create');
this.resource.create(args,
goog.bind(this.handleUpdateResponse, this),
args['newTldName']);
};
/** @override */
registry.admin.Registry.prototype.prepareUpdate = function(modelCopy) {
var form = registry.util.parseForm('item');
for (var ndx in form) {
modelCopy[ndx] = form[ndx];
}
var apply = function(obj, ndx, func) {
if (obj[ndx]) {
obj[ndx] = func(obj[ndx]);
}
};
var parseStateTransitions = function(s) {
var transitions = s.split(';');
var transArr = [];
for (var i = 0; i < transitions.length; i++) {
var trans = transitions[i];
var parts = trans.split(',');
var args = {};
args['tldState'] = parts[0];
args['transitionTime'] = parts[1];
transArr.push(args);
}
return transArr;
};
apply(modelCopy, 'tldStateTransitions', parseStateTransitions);
};

View file

@ -38,8 +38,6 @@ goog.require('registry.util');
* |-ui/js/resource_component.js - JSON resources * |-ui/js/resource_component.js - JSON resources
* | ^ * | ^
* | \ * | \
* | |- ui/js/admin/registrar.js
* | |- ui/js/admin/registry.js
* | |- ui/js/registrar/settings.js * | |- ui/js/registrar/settings.js
* | * |
* |-ui/js/registrar/xml_resource_component.js - EPP resources * |-ui/js/registrar/xml_resource_component.js - EPP resources

View file

@ -6,8 +6,6 @@ java_library(
srcs = glob(["*.java"]), srcs = glob(["*.java"]),
resources = [ resources = [
"//java/com/google/domain/registry/ui:globals.txt", "//java/com/google/domain/registry/ui:globals.txt",
"//java/com/google/domain/registry/ui/css:admin_bin.css.js",
"//java/com/google/domain/registry/ui/css:admin_dbg.css.js",
"//java/com/google/domain/registry/ui/css:registrar_bin.css.js", "//java/com/google/domain/registry/ui/css:registrar_bin.css.js",
"//java/com/google/domain/registry/ui/css:registrar_dbg.css.js", "//java/com/google/domain/registry/ui/css:registrar_dbg.css.js",
], ],

View file

@ -1,131 +0,0 @@
// Copyright 2016 Google Inc. 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 com.google.domain.registry.ui.server.admin;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Optional;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.domain.registry.config.RegistryConfig;
import com.google.domain.registry.config.RegistryEnvironment;
import com.google.domain.registry.request.HttpException.NotFoundException;
import com.google.domain.registry.security.JsonResponseHelper;
import com.google.domain.registry.security.JsonTransportServlet;
import com.google.domain.registry.ui.forms.FormFieldException;
import java.util.Map;
import javax.annotation.Nullable;
import javax.servlet.http.HttpServletRequest;
/** A servlet for callbacks that manipulate resources. */
public abstract class AdminResourceServlet extends JsonTransportServlet {
private static final RegistryConfig CONFIG = RegistryEnvironment.get().config();
public static final String XSRF_SCOPE = "admin";
public AdminResourceServlet() {
super(XSRF_SCOPE, true);
}
@Override
public Map<String, Object> doJsonPost(HttpServletRequest req, Map<String, ?> params) {
String op = Optional.fromNullable((String) params.get("op")).or("read");
@SuppressWarnings("unchecked")
Map<String, ?> args = (Map<String, Object>) Optional.<Object>fromNullable(params.get("args"))
.or(ImmutableMap.of());
try {
switch (op) {
case "create":
return create(req, args);
case "update":
return update(req, args);
case "delete":
return delete(req, args);
case "read":
return read(req, args);
default:
throw new UnsupportedOperationException("Unknown operation: " + op);
}
} catch (FormFieldException e) {
return JsonResponseHelper.createFormFieldError(e.getMessage(), e.getFieldName());
}
}
@SuppressWarnings("unused")
Map<String, Object> create(HttpServletRequest req, Map<String, ?> args) {
throw new UnsupportedOperationException();
}
@SuppressWarnings("unused")
Map<String, Object> read(HttpServletRequest req, Map<String, ?> args) {
throw new UnsupportedOperationException();
}
@SuppressWarnings("unused")
Map<String, Object> update(HttpServletRequest req, Map<String, ?> args) {
throw new UnsupportedOperationException();
}
@SuppressWarnings("unused")
Map<String, Object> delete(HttpServletRequest req, Map<String, ?> args) {
throw new UnsupportedOperationException();
}
@SuppressWarnings("unchecked")
protected static <T> ImmutableList<T> getParamList(Map<String, ?> map, String identifier) {
return ImmutableList.copyOf(
Optional.fromNullable((Iterable<T>) map.get(identifier)).or(ImmutableList.<T>of()));
}
/** Like checkNotNull, but throws NotFoundException if given arg is null. */
protected static <T> T checkExists(@Nullable T obj, String msg) {
if (obj == null) {
throw new NotFoundException(msg);
}
return obj;
}
protected static String getValAsString(Map<String, ?> map, String identifier) {
return (String) map.get(identifier);
}
/** Returns the last path element or null if no path separator exists. */
@VisibleForTesting
String parsePath(HttpServletRequest req) {
String uri = req.getRequestURI();
String prefix = CONFIG.getAdminServletPathPrefix() + "/";
checkArgument(
uri.startsWith(prefix),
"Request URI must start with: %s",
prefix);
return uri.substring(prefix.length());
}
/** @return the last path element or null if no path separator exists. */
@Nullable
protected String parseId(HttpServletRequest req) {
String[] pathParts = parsePath(req).split("/");
return pathParts.length < 2 ? null : pathParts[pathParts.length - 1];
}
/** Like parseId but path must contain at least one path separator. */
protected String checkParseId(HttpServletRequest req) {
return checkNotNull(parseId(req), "Path must be of the form (/<collection>)+/<id>");
}
}

View file

@ -1,48 +0,0 @@
// Copyright 2016 Google Inc. 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 com.google.domain.registry.ui.server.admin;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Supplier;
import com.google.common.io.Resources;
import com.google.domain.registry.ui.server.AbstractUiServlet;
import com.google.domain.registry.ui.server.SoyTemplateUtils;
import com.google.domain.registry.ui.soy.admin.ConsoleSoyInfo;
import com.google.template.soy.shared.SoyCssRenamingMap;
import com.google.template.soy.tofu.SoyTofu;
/** UI for Registry operations. */
public class AdminUiServlet extends AbstractUiServlet {
@VisibleForTesting
static final Supplier<SoyTofu> TOFU_SUPPLIER =
SoyTemplateUtils.createTofuSupplier(
com.google.domain.registry.ui.soy.ConsoleSoyInfo.getInstance(),
com.google.domain.registry.ui.soy.admin.ConsoleSoyInfo.getInstance());
public static final Supplier<SoyCssRenamingMap> CSS_RENAMING_MAP_SUPPLIER =
SoyTemplateUtils.createCssRenamingMapSupplier(
Resources.getResource("com/google/domain/registry/ui/css/admin_bin.css.js"),
Resources.getResource("com/google/domain/registry/ui/css/admin_dbg.css.js"));
@Override
protected String get() {
return TOFU_SUPPLIER.get()
.newRenderer(ConsoleSoyInfo.MAIN)
.setCssRenamingMap(CSS_RENAMING_MAP_SUPPLIER.get())
.setData(getTemplateArgs(AdminResourceServlet.XSRF_SCOPE))
.render();
}
}

View file

@ -1,36 +0,0 @@
package(default_visibility = ["//java/com/google/domain/registry:registry_project"])
java_library(
name = "admin",
srcs = glob(["*.java"]),
resources = [
"//java/com/google/domain/registry/ui/css:admin_bin.css.js",
"//java/com/google/domain/registry/ui/css:admin_dbg.css.js",
],
deps = [
"//java/com/google/common/annotations",
"//java/com/google/common/base",
"//java/com/google/common/collect",
"//java/com/google/common/io",
"//java/com/google/domain/registry/config",
"//java/com/google/domain/registry/export/sheet",
"//java/com/google/domain/registry/flows",
"//java/com/google/domain/registry/model",
"//java/com/google/domain/registry/request",
"//java/com/google/domain/registry/security",
"//java/com/google/domain/registry/security:servlets",
"//java/com/google/domain/registry/ui/forms",
"//java/com/google/domain/registry/ui/server",
"//java/com/google/domain/registry/ui/server/registrar",
"//java/com/google/domain/registry/ui/soy:soy_java_wrappers",
"//java/com/google/domain/registry/ui/soy/admin:soy_java_wrappers",
"//java/com/google/domain/registry/util",
"//third_party/java/joda_time",
"//third_party/java/jsr305_annotations",
"//third_party/java/objectify:objectify-v4_1",
"//third_party/java/servlet/servlet_api",
"//third_party/closure/templates",
],
)

View file

@ -1,165 +0,0 @@
// Copyright 2016 Google Inc. 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 com.google.domain.registry.ui.server.admin;
import static com.google.domain.registry.model.ofy.ObjectifyService.ofy;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.domain.registry.export.sheet.SyncRegistrarsSheetTask;
import com.google.domain.registry.model.registrar.Registrar;
import com.google.domain.registry.model.registrar.RegistrarContact;
import com.google.domain.registry.ui.forms.FormFields;
import com.google.domain.registry.ui.server.RegistrarFormFields;
import com.googlecode.objectify.VoidWork;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.servlet.http.HttpServletRequest;
/**
* Admin servlet that allows creating or updating a registrar. Deletes are not allowed so as to
* preserve history.
*/
public class RegistrarServlet extends AdminResourceServlet {
@Override
public Map<String, Object> create(HttpServletRequest req, final Map<String, ?> args) {
final String clientIdentifier = FormFields.CLID.convert(parseId(req)).get();
ofy().transact(new VoidWork() {
@Override
public void vrun() {
Registrar registrar = new Registrar.Builder()
.setClientIdentifier(clientIdentifier)
.setRegistrarName(clientIdentifier)
.setType(Registrar.Type.TEST)
.setState(Registrar.State.ACTIVE)
.setAllowedTlds(ImmutableSet.<String>of())
.build();
Registrar.Builder builder = registrar.asBuilder();
Set<RegistrarContact> contacts = update(registrar, builder, args);
registrar = builder.build();
ofy().save().entity(registrar);
if (!contacts.isEmpty()) {
RegistrarContact.updateContacts(registrar, contacts);
}
}});
return ImmutableMap.<String, Object>of("results", ImmutableList.of(clientIdentifier + ": ok"));
}
@Override
public Map<String, Object> read(HttpServletRequest req, Map<String, ?> args) {
String clientIdentifier = parseId(req);
if (clientIdentifier == null) {
List<Map<String, ?>> registrars = new ArrayList<>();
for (Registrar registrar : Registrar.loadAll()) {
registrars.add(registrar.toJsonMap());
}
return ImmutableMap.<String, Object>of("set", registrars);
}
Registrar registrar = Registrar.loadByClientId(clientIdentifier);
checkExists(registrar, "No registrar exists with the given client id: " + clientIdentifier);
return ImmutableMap.<String, Object>of("item", registrar.toJsonMap());
}
@Override
public Map<String, Object> update(HttpServletRequest req, final Map<String, ?> args) {
final String clientIdentifier = checkParseId(req);
ofy().transact(new VoidWork() {
@Override
public void vrun() {
Registrar registrar = Registrar.loadByClientId(clientIdentifier);
Registrar.Builder builder = checkExists(
registrar,
"No registrar exists with the given client id: " + clientIdentifier)
.asBuilder();
Set<RegistrarContact> updatedContacts = update(registrar, builder, args);
if (!updatedContacts.isEmpty()) {
builder.setContactsRequireSyncing(true);
}
Registrar updatedRegistrar = builder.build();
ofy().save().entity(updatedRegistrar);
if (!updatedContacts.isEmpty()) {
RegistrarContact.updateContacts(updatedRegistrar, updatedContacts);
}
SyncRegistrarsSheetTask.enqueueBackendTask();
}});
return ImmutableMap.<String, Object>of("results", ImmutableList.of(clientIdentifier + ": ok"));
}
/**
* Admin fields are updated and then a chained call is made to
* {@link com.google.domain.registry.ui.server.registrar.RegistrarServlet#update(
* Registrar, Registrar.Builder, Map)}
* for the shared fields.
*/
private static Set<RegistrarContact> update(
Registrar existingRegistrarObj, Registrar.Builder builder, Map<String, ?> args) {
// Admin only settings
for (Registrar.State state :
RegistrarFormFields.STATE_FIELD.extractUntyped(args).asSet()) {
builder.setState(state);
}
builder.setAllowedTlds(
RegistrarFormFields.ALLOWED_TLDS_FIELD.extractUntyped(args).or(ImmutableSet.<String>of()));
Boolean blockPremiumNames =
RegistrarFormFields.BLOCK_PREMIUM_NAMES_FIELD.extractUntyped(args).orNull();
builder.setBlockPremiumNames(blockPremiumNames == null ? false : blockPremiumNames);
for (String password :
RegistrarFormFields.PASSWORD_FIELD.extractUntyped(args).asSet()) {
builder.setPassword(password);
}
for (Long billingIdentifier :
RegistrarFormFields.BILLING_IDENTIFIER_FIELD.extractUntyped(args).asSet()) {
builder.setBillingIdentifier(billingIdentifier);
}
// Resources
for (String driveFolderId :
RegistrarFormFields.DRIVE_FOLDER_ID_FIELD.extractUntyped(args).asSet()) {
builder.setDriveFolderId(driveFolderId);
}
// WHOIS
for (String registrarName :
RegistrarFormFields.NAME_FIELD.extractUntyped(args).asSet()) {
builder.setRegistrarName(registrarName);
}
for (Long ianaIdentifier :
RegistrarFormFields.IANA_IDENTIFIER_FIELD.extractUntyped(args).asSet()) {
builder.setIanaIdentifier(ianaIdentifier);
}
builder.setIcannReferralEmail(
RegistrarFormFields.ICANN_REFERRAL_EMAIL_FIELD.extractUntyped(args).get());
// Security
for (String phonePasscode :
RegistrarFormFields.PHONE_PASSCODE_FIELD.extractUntyped(args).asSet()) {
builder.setPhonePasscode(phonePasscode);
}
// Will this ever get used?
builder.setUrl(
RegistrarFormFields.URL_FIELD.extractUntyped(args).orNull());
return com.google.domain.registry.ui.server.registrar.RegistrarServlet.update(
existingRegistrarObj, builder, args);
}
}

View file

@ -1,172 +0,0 @@
// Copyright 2016 Google Inc. 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 com.google.domain.registry.ui.server.admin;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.domain.registry.model.ofy.ObjectifyService.ofy;
import static com.google.domain.registry.model.registry.Registries.getTlds;
import static com.google.domain.registry.util.DomainNameUtils.canonicalizeDomainName;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSortedMap;
import com.google.common.collect.Ordering;
import com.google.domain.registry.model.registry.Registry;
import com.google.domain.registry.model.registry.Registry.TldState;
import com.google.domain.registry.util.SystemClock;
import com.googlecode.objectify.VoidWork;
import org.joda.time.DateTime;
import org.joda.time.Duration;
import org.joda.time.Seconds;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import javax.servlet.http.HttpServletRequest;
/**
* RESTful CRUD bindings for Registry objects.
*/
public class RegistryServlet extends AdminResourceServlet {
private static final SystemClock CLOCK = new SystemClock();
@Override
Map<String, Object> create(HttpServletRequest req, Map<String, ?> args) {
final String tld = checkParseId(req);
checkArgument(tld.equals(canonicalizeDomainName(tld)));
try {
ofy().transact(new VoidWork() {
@Override
public void vrun() {
ofy().save().entity(new Registry.Builder().setTldStr(tld).build());
}});
return ImmutableMap.<String, Object>of("results", ImmutableList.of(tld + ": ok"));
} catch (Exception e) {
return ImmutableMap.<String, Object>of("results", ImmutableList.of(tld + ": " + e));
}
}
@Override
Map<String, Object> read(HttpServletRequest req, Map<String, ?> args) {
String id = parseId(req);
if (id != null) {
return readTld(id);
}
// Collection request; if no item specified, return all.
return ImmutableMap.<String, Object>of("set", readTlds(getTlds()));
}
Map<String, Object> readTld(String tld) {
return ImmutableMap.<String, Object>of("item", toResultObject(
checkExists(Registry.get(tld), "No registry exists for the given tld: " + tld)));
}
List<Map<String, ?>> readTlds(Set<String> tlds) {
List<Map<String, ?>> registries = new ArrayList<>();
for (String tld : tlds) {
registries.add(toResultObject(Registry.get(tld)));
}
return registries;
}
Map<String, Object> toResultObject(Registry r) {
return new ImmutableSortedMap.Builder<String, Object>(Ordering.natural())
.put("name", r.getTld().toString())
.put("state", r.getTldState(CLOCK.nowUtc()).toString())
.put("tldStateTransitions", r.getTldStateTransitions().toString())
.put("creationTime", Objects.toString(r.getCreationTime(), ""))
.put("lastUpdateTime", Objects.toString(r.getUpdateAutoTimestamp().getTimestamp(), ""))
.put("addGracePeriod", r.getAddGracePeriodLength().toStandardSeconds().toString())
.put("autoRenewGracePeriod", r.getAutoRenewGracePeriodLength().toStandardSeconds().toString())
.put("redemptionGracePeriod", r.getRedemptionGracePeriodLength().toStandardSeconds().toString())
.put("renewGracePeriod", r.getRenewGracePeriodLength().toStandardSeconds().toString())
.put("transferGracePeriod", r.getTransferGracePeriodLength().toStandardSeconds().toString())
.put("automaticTransferLength", r.getAutomaticTransferLength().toStandardSeconds().toString())
.put("pendingDeleteLength", r.getPendingDeleteLength().toStandardSeconds().toString())
.build();
}
ImmutableSortedMap<DateTime, TldState> getTldStateTransitions(Map<String, ?> args) {
ImmutableSortedMap.Builder<DateTime, TldState> builder = ImmutableSortedMap.naturalOrder();
for (Map<String, ?> tldStateTransition
: AdminResourceServlet.<Map<String, ?>>getParamList(args, "tldStateTransitions")) {
builder.put(
DateTime.parse(getValAsString(tldStateTransition, "transitionTime")),
TldState.valueOf(getValAsString(tldStateTransition, "tldState")));
}
return builder.build();
}
Duration getValAsDuration(Map<String, ?> map, String identifier) {
return Seconds.parseSeconds(getValAsString(map, identifier)).toStandardDuration();
}
@Override
Map<String, Object> update(HttpServletRequest req, Map<String, ?> args) {
String tld = checkParseId(req);
ImmutableSortedMap<DateTime, TldState> tldStateTransitions =
getTldStateTransitions(args);
Duration addGracePeriodLength = getValAsDuration(args, "addGracePeriod");
Duration autoRenewGracePeriodLength = getValAsDuration(args, "autoRenewGracePeriod");
Duration redemptionGracePeriodLength = getValAsDuration(args, "redemptionGracePeriod");
Duration renewGracePeriodLength = getValAsDuration(args, "renewGracePeriod");
Duration transferGracePeriodLength = getValAsDuration(args, "transferGracePeriod");
Duration automaticTransferLength = getValAsDuration(args, "automaticTransferLength");
Duration pendingDeleteLength = getValAsDuration(args, "pendingDeleteLength");
try {
final Registry.Builder registry = Registry.get(tld).asBuilder();
if (!tldStateTransitions.isEmpty()) {
registry.setTldStateTransitions(tldStateTransitions);
}
if (!addGracePeriodLength.equals(Duration.ZERO)) {
registry.setAddGracePeriodLength(addGracePeriodLength);
}
if (!autoRenewGracePeriodLength.equals(Duration.ZERO)) {
registry.setAutoRenewGracePeriodLength(autoRenewGracePeriodLength);
}
if (!redemptionGracePeriodLength.equals(Duration.ZERO)) {
registry.setRedemptionGracePeriodLength(redemptionGracePeriodLength);
}
if (!renewGracePeriodLength.equals(Duration.ZERO)) {
registry.setRenewGracePeriodLength(renewGracePeriodLength);
}
if (!transferGracePeriodLength.equals(Duration.ZERO)) {
registry.setTransferGracePeriodLength(transferGracePeriodLength);
}
if (!automaticTransferLength.equals(Duration.ZERO)) {
registry.setAutomaticTransferLength(automaticTransferLength);
}
if (!pendingDeleteLength.equals(Duration.ZERO)) {
registry.setPendingDeleteLength(pendingDeleteLength);
}
ofy().transact(new VoidWork(){
@Override
public void vrun() {
ofy().save().entity(registry.build());
}});
return ImmutableMap.<String, Object>of("results", "OK");
} catch (Exception e) {
return ImmutableMap.<String, Object>of("results", e.toString());
}
}
}

View file

@ -1,16 +0,0 @@
// Copyright 2016 Google Inc. 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.
@javax.annotation.ParametersAreNonnullByDefault
package com.google.domain.registry.ui.server.admin;

View file

@ -1,41 +0,0 @@
package(default_visibility = ["//java/com/google/domain/registry:registry_project"])
load("//third_party/closure/templates:closure_template_java_library.bzl", "closure_template_java_library")
load("//third_party/closure/templates:closure_template_js_library.bzl", "closure_template_js_library")
filegroup(
name = "js_files",
srcs = [
"Console.soy.js",
"Registrar.soy.js",
"Registry.soy.js",
],
)
closure_template_java_library(
name = "soy_java_wrappers",
srcs = glob(["*.soy"]),
java_package = "com.google.domain.registry.ui.soy.admin",
)
closure_template_js_library(
name = "Console",
srcs = ["Console.soy"],
globals = "//java/com/google/domain/registry/ui:globals.txt",
deps = ["//java/com/google/domain/registry/ui/soy:Console"],
)
closure_template_js_library(
name = "Registrar",
srcs = ["Registrar.soy"],
globals = "//java/com/google/domain/registry/ui:globals.txt",
deps = ["//java/com/google/domain/registry/ui/soy:Forms"],
)
closure_template_js_library(
name = "Registry",
srcs = ["Registry.soy"],
globals = "//java/com/google/domain/registry/ui:globals.txt",
deps = ["//java/com/google/domain/registry/ui/soy:Forms"],
)

View file

@ -1,60 +0,0 @@
{namespace registry.soy.admin.console autoescape="strict"}
/**
* Main admin page. Content is filled in dynamically via JS rendering
* of other templates in this directory.
*/
{template .main}
{@param user: map<string, ?>} /** Passed to googlebar. */
{@param xsrfToken: string} /** Token for callbacks to the server. */
{call registry.soy.console.header}
{param app: 'admin' /}
{param subtitle: 'Admin Console' /}
{/call}
{call registry.soy.console.googlebar data="all" /}
<div id="reg-app">
<div id="reg-appbar" class="{css kd-appbar}"></div>
{call .navbar_ /}
<div id="reg-content-and-footer">
<div id="reg-content">
<!-- Dynamic content goes here. -->
</div>
<div class="{css pageFooter}">
Here's lookin' at you, <a href="http://memegen.googleplex.com">.meme</a>!.
</div>
</div>
<div id="debug"></div>
</div>
{switch DEBUG}
{case com.google.domain.registry.ui.ConsoleDebug.PRODUCTION}
<script src="/assets/js/admin_bin_map.js"></script>
{case com.google.domain.registry.ui.ConsoleDebug.DEBUG}
<script src="/assets/js/admin_dbg.js"></script>
{case com.google.domain.registry.ui.ConsoleDebug.RAW}
<script src="/assets/sources/external/closure_library/closure/goog/base.js">
</script>
<script src="/assets/sources/deps-runfiles.js"></script>
<script>goog.require('registry.admin.main');</script>
{/switch}
{if isNonnull(DEBUG)}
<script>registry.admin.main({$xsrfToken});</script>
{/if}
{/template}
/**
* Navigation bar.
*/
{template .navbar_ private="true"}
<div id="reg-nav" class="{css kd-content-sidebar}">
<ul id="reg-navlist">
<li class="{css kd-sidebarlistitem}">
<a href="/_dr/admin#registry">Registries</a>
</li>
<li class="{css kd-sidebarlistitem}">
<a href="/_dr/admin#registrar">Registrars</a>
</li>
</ul>
</div>
{/template}

View file

@ -1,360 +0,0 @@
{namespace registry.soy.admin.registrar autoescape="strict"}
/**
* Set view for registrars.
* @param set
*/
{template .registrars}
<div class="{css set}">
<h1>Registrars</h1>
<table id="registrars">
<tr>
<th>Name</th>
<th>Status</th>
<th>TLDs</th>
</tr>
{foreach $registrar in $set}
<tr>
<td class="{css client-identifier}">
<a href="/_dr/admin#registrar/{$registrar['clientIdentifier']}">
{$registrar['clientIdentifier']}</a>
</td>
<td>
{$registrar.state}
</td>
<td>
{if isNonnull($registrar.allowedTlds)}
{length($registrar.allowedTlds)}
{else}
0
{/if}
</td>
</tr>
{/foreach}
</table>
<form name="create">
<h2>New Registrar</h2>
<table>
{call registry.soy.forms.inputFieldRow}
{param label: 'Registrar ID (clientIdentifier)' /}
{param name: 'clientIdentifier' /}
{/call}
{call registry.soy.forms.inputFieldRow}
{param name: 'registrarName' /}
{/call}
{call registry.soy.forms.inputFieldRow}
{param name: 'icannReferralEmail' /}
{/call}
{call registry.soy.forms.inputFieldRow}
{param name: 'emailAddress' /}
{/call}
{call registry.soy.forms.inputFieldRow}
{param label: 'Street' /}
{param name: 'localizedAddress.street[0]' /}
{/call}
{call registry.soy.forms.inputFieldRow}
{param label: 'City' /}
{param name: 'localizedAddress.city' /}
{/call}
{call registry.soy.forms.inputFieldRow}
{param label: 'Country code' /}
{param name: 'localizedAddress.countryCode' /}
{/call}
</table>
<button type="button"
id="create-button"
class="{css kd-button} {css kd-button-submit}">Create</button>
</form>
</div>
{/template}
/**
* Item view for registrar.
* @param item
*/
{template .registrar}
<form name="item" class="{css item} {css registrar}">
<h1>{$item['clientIdentifier']}</h1>
<table>
{call .registrarAdminFields_ data="all" /}
{call .registrarResourcesFields_ data="all" /}
{call .registrarWhoisFields_ data="all" /}
{call .registrarSecurityFields_ data="all" /}
{call .registrarContactFields_ data="all" /}
{call .registrarMiscFields_ data="all" /}
</table>
</form>
{/template}
/**
* Administrative-only fields.
* @private
*/
{template .registrarAdminFields_}
{@param item: map<string, ?>}
<tr class="{css section-lead}">
<th colspan="2">Admin settings - Admin Visible only</th>
{call registry.soy.forms.selectRow data="all"}
{param label: 'State' /}
{param name: 'state' /}
{param description: 'model: state' /}
{param options: ['PENDING', 'ACTIVE', 'SUSPENDED'] /}
{param selected: $item['state'] /}
{/call}
{call registry.soy.forms.inputFieldRow data="all"}
{param label: 'Allowed TLDs' /}
{param name: 'allowedTlds' /}
{param placeholder: 'e.g. foo,bar' /}
{param description: 'model: allowedTlds' /}
{/call}
{call registry.soy.forms.inputFieldRow data="all"}
{param label: 'New EPP password' /}
{param name: 'password' /}
{param description: 'model: password' /}
{/call}
{call registry.soy.forms.inputCheckboxRow data="all"}
{param label: 'Block premium names' /}
{param name: 'blockPremiumNames' /}
{param checked: $item['blockPremiumNames'] ? true : null /}
{param description: 'model: blockPremiumNames' /}
{/call}
{/template}
/**
* Public WHOIS fields.
* @private
*/
{template .registrarResourcesFields_}
{@param item: map<string, ?>}
<tr class="{css section-lead}">
<th colspan="2">Resources settings - Admin &amp; Registrar Visible</th>
{call registry.soy.forms.inputFieldRow data="all"}
{param label: 'Drive Folder ID' /}
{param name: 'driveFolderId' /}
{param description: 'model: driveFolderId' /}
{/call}
{/template}
/**
* Public WHOIS fields.
* @private
*/
{template .registrarWhoisFields_}
{@param item: map<string, ?>}
<tr class="{css section-lead}">
<th colspan="2">WHOIS settings - Admin &amp; Registrar Visible</th>
{call registry.soy.forms.inputFieldRow data="all"}
{param label: 'Name' /}
{param name: 'registrarName' /}
{param description: 'model: registrarName' /}
{/call}
{call registry.soy.forms.inputFieldRow data="all"}
{param label: 'IANA ID' /}
{param name: 'ianaIdentifier' /}
{param description: 'model: ianaIdentifier' /}
{/call}
{call registry.soy.forms.inputFieldRow data="all"}
{param label: 'ICANN referral email' /}
{param name: 'icannReferralEmail' /}
{param description: 'model: icannReferralEmail' /}
{/call}
{call registry.soy.forms.inputFieldRow data="all"}
{param label: 'Email' /}
{param name: 'emailAddress' /}
{param description: 'model: emailAddress' /}
{/call}
{call registry.soy.forms.inputFieldRow data="all"}
{param label: 'Phone' /}
{param name: 'phoneNumber' /}
{param description: 'model: phoneNumber' /}
{/call}
{call registry.soy.forms.inputFieldRow data="all"}
{param label: 'Fax' /}
{param name: 'faxNumber' /}
{param description: 'model: faxNumber' /}
{/call}
{call registry.soy.forms.inputFieldRowWithValue data="all"}
{param label: 'Street 1' /}
{param name: 'localizedAddress.street[0]' /}
{param value: $item['localizedAddress'].street[0] /}
{param description: 'model: localizedAddress.street[0]' /}
{/call}
{call registry.soy.forms.inputFieldRowWithValue data="all"}
{param label: 'Street 2' /}
{param name: 'localizedAddress.street[1]' /}
{param value: $item['localizedAddress'].street[1] /}
{param description: 'model: localizedAddress.street[1]' /}
{/call}
{call registry.soy.forms.inputFieldRowWithValue data="all"}
{param label: 'Street 3' /}
{param name: 'localizedAddress.street[2]' /}
{param value: $item['localizedAddress'].street[2] /}
{param description: 'model: localizedAddress.street[2]' /}
{/call}
{call registry.soy.forms.inputFieldRowWithValue data="all"}
{param label: 'City' /}
{param name: 'localizedAddress.city' /}
{param value: $item['localizedAddress'].city /}
{param description: 'model: localizedAddress.city' /}
{/call}
{call registry.soy.forms.inputFieldRowWithValue data="all"}
{param label: 'State/Region' /}
{param name: 'localizedAddress.state' /}
{param value: $item['localizedAddress'].state /}
{param description: 'model: localizedAddress.state' /}
{/call}
{call registry.soy.forms.inputFieldRowWithValue data="all"}
{param label: 'Zip/Postal code' /}
{param name: 'localizedAddress.zip' /}
{param value: $item['localizedAddress'].zip /}
{param description: 'model: localizedAddress.zip' /}
{/call}
{call registry.soy.forms.inputFieldRowWithValue data="all"}
{param label: 'Country code' /}
{param name: 'localizedAddress.countryCode' /}
{param value: $item['localizedAddress'].countryCode /}
{param description: 'model: localizedAddress.countryCode' /}
{/call}
<tr class="{css section-lead}">
<th colspan="2"><em>These are filled in by default to google servers</em></th>
{call registry.soy.forms.inputFieldRow data="all"}
{param label: 'WHOIS server' /}
{param name: 'whoisServer' /}
{param description: 'model: whoisServer' /}
{param placeholder: 'e.g. whois.nic.foo' /}
{/call}
{call registry.soy.forms.inputFieldRow data="all"}
{param label: 'Referral URL' /}
{param name: 'referralUrl' /}
{param description: 'model: referralUrl' /}
{param placeholder: 'http://whois.nic.google' /}
{/call}
{/template}
/**
* Security settings, like SSL cert and IP whitelist.
* @private
*/
{template .registrarSecurityFields_}
{@param item: map<string, ?>}
<tr class="{css section-lead}">
<th colspan="2">Security settings - Admin &amp; Registrar Visible</th>
{call registry.soy.forms.inputFieldRow data="all"}
{param label: 'IP whitelist' /}
{param name: 'ipAddressWhitelist' /}
{param placeholder: 'e.g. 1.1.1.1/24' /}
{param description: 'model: ipAddressWhitelist' /}
{/call}
{call registry.soy.forms.inputFieldRow data="all"}
{param label: 'Telephone passcode' /}
{param name: 'phonePasscode' /}
{param placeholder: 'e.g. 01234' /}
{param description: 'model: ipAddressWhitelist (Registrar read-only)' /}
{/call}
{call registry.soy.forms.textareaFieldRow data="all"}
{param label: 'SSL certificate' /}
{param name: 'clientCertificate' /}
{param description: 'model: clientCertificate' /}
{/call}
<tr>
<td><label>clientCertificateHash</label></td>
<td>{$item['clientCertificateHash']}</td>
</tr>
<tr>
<td><label>lastCertificateUpdateTime</label></td>
<td>{$item['lastCertificateUpdateTime']}</td>
</tr>
{/template}
/**
* Registrar communication contacts.
* @private
*/
{template .registrarContactFields_}
{@param item: map<string, ?>}
<tr class="{css section-lead}">
<th colspan="2">
<button id="add-contact-button" type="button"
class="{css kd-button} {css add-contact-button} {css hidden}">
Add Contact</button>
Contacts
</th>
</tr>
<tr>
<td id="contacts" colspan="2">
{if isNonnull($item['contacts'])}
{foreach $c in $item['contacts']}
{call .contactInfo data="all"}
{param namePrefix: 'contacts[' + index($c) + '].' /}
{param item: $c /}
{/call}
{/foreach}
{/if}
</td>
</tr>
{/template}
/**
* Extra fields for internal use.
* @private
*/
{template .registrarMiscFields_}
{@param item: map<string, ?>}
<tr class="{css section-lead}">
<th colspan="2">External IDs</th>
{call registry.soy.forms.inputFieldRow data="all"}
{param name: 'billingIdentifier' /}
{/call}
<tr class="{css section-lead}">
<th colspan="2">Does anybody use this stuff?</th>
{call registry.soy.forms.inputFieldRow data="all"}
{param name: 'url' /}
{/call}
<tr class="{css section-lead}">
<th colspan="2">Metadata</th>
<tr>
<td>creationTime</td>
<td>{$item['creationTime']}</td>
<tr>
<td>lastUpdateTime</td>
<td>{$item['lastUpdateTime']}</td>
{/template}
/** Contact info. Removable. */
{template .contactInfo}
{@param namePrefix: string}
<div>
<table>
{call registry.soy.forms.inputFieldRow data="all"}
{param name: 'name' /}
{/call}
{call registry.soy.forms.inputFieldRow data="all"}
{param name: 'emailAddress' /}
{/call}
{call registry.soy.forms.inputFieldRow data="all"}
{param name: 'phoneNumber' /}
{/call}
{call registry.soy.forms.inputFieldRow data="all"}
{param name: 'faxNumber' /}
{/call}
{call registry.soy.forms.inputFieldRow data="all"}
{param name: 'types' /}
{/call}
{call registry.soy.forms.inputFieldRow data="all"}
{param name: 'gaeUserId' /}
{/call}
</table>
<button type="button" class="{css kd-button} {css remove} {css hidden}">
Remove
</button>
</div>
{/template}

View file

@ -1,87 +0,0 @@
{namespace registry.soy.admin.registry autoescape="strict"}
/**
* Set view for registries.
* @param set
*/
{template .registries}
<div class="{css set}">
<h1>Registries</h1>
<table id="registries">
<tr>
<th>TLD
<th>Status
{foreach $tld in $set}
<tr>
<td class="{css name} {css title}">
<a href="/_dr/admin#registry/{$tld.name}">{$tld.name}</a>
<td class="{css status}">{$tld.state}
{/foreach}
</table>
<form name="create">
<h2>New Registry</h2>
<table>
{call registry.soy.forms.inputFieldRow}
{param name: 'newTldName'/}
{/call}
</table>
<button type="button"
id="create-button"
class="{css kd-button} {css kd-button-submit}">Create</button>
</form>
</div>
{/template}
/**
* Item view for registry.
* @param item
*/
{template .registry}
<form name="item" class="{css item} {css registrar}">
<h1>{$item.name}</h1>
<table>
<tr>
<td>state:
<td>
{$item['state']}
<tr>
{call registry.soy.forms.inputFieldRow data="all"}
{param name: 'tldStateTransitions'/}
{param placeholder: 'e.g. PREDELEGATION,T00:00:00Z;SUNRUSH,T04:00:00Z'/}
{/call}
<tr class="{css section-lead}">
<th colspan="2">Periods</th>
{call registry.soy.forms.inputFieldRow data="all"}
{param name: 'addGracePeriod'/}
{/call}
{call registry.soy.forms.inputFieldRow data="all"}
{param name: 'autoRenewGracePeriod'/}
{/call}
{call registry.soy.forms.inputFieldRow data="all"}
{param name: 'redemptionGracePeriod'/}
{/call}
{call registry.soy.forms.inputFieldRow data="all"}
{param name: 'renewGracePeriod'/}
{/call}
{call registry.soy.forms.inputFieldRow data="all"}
{param name: 'transferGracePeriod'/}
{/call}
{call registry.soy.forms.inputFieldRow data="all"}
{param name: 'automaticTransferLength'/}
{/call}
{call registry.soy.forms.inputFieldRow data="all"}
{param name: 'pendingDeleteLength'/}
{/call}
<tr class="{css section-lead}">
<th colspan="2">Metadata (for GCHQ)</th>
<tr>
<td>creationTime
<td>{$item['creationTime']}
<tr>
<td>lastUpdateTime
<td>{$item['lastUpdateTime']}
</table>
</form>
{/template}

View file

@ -49,7 +49,6 @@ java_library(
"//java/com/google/domain/registry/flows", "//java/com/google/domain/registry/flows",
"//java/com/google/domain/registry/module/backend", "//java/com/google/domain/registry/module/backend",
"//java/com/google/domain/registry/module/frontend", "//java/com/google/domain/registry/module/frontend",
"//java/com/google/domain/registry/ui/server/admin",
"//java/com/google/domain/registry/ui/server/api", "//java/com/google/domain/registry/ui/server/api",
"//java/com/google/domain/registry/ui/server/registrar", "//java/com/google/domain/registry/ui/server/registrar",
"//third_party/java/jsr305_annotations", "//third_party/java/jsr305_annotations",

View file

@ -76,15 +76,7 @@ public final class RegistryTestServer {
route("/registrar-payment", route("/registrar-payment",
com.google.domain.registry.module.frontend.FrontendServlet.class), com.google.domain.registry.module.frontend.FrontendServlet.class),
route("/registrar-payment-setup", route("/registrar-payment-setup",
com.google.domain.registry.module.frontend.FrontendServlet.class), com.google.domain.registry.module.frontend.FrontendServlet.class));
// Admin Console
route("/_dr/admin",
com.google.domain.registry.ui.server.admin.AdminUiServlet.class),
route("/_dr/admin/registry/*",
com.google.domain.registry.ui.server.admin.RegistryServlet.class),
route("/_dr/admin/registrar/*",
com.google.domain.registry.ui.server.admin.RegistrarServlet.class));
private final TestServer server; private final TestServer server;

View file

@ -1,17 +0,0 @@
package(default_visibility = ["//java/com/google/domain/registry:registry_project"])
load("//third_party/closure/testing:closure_js_test.bzl", "closure_js_test")
closure_js_test(
name = "test",
size = "medium",
timeout = "short",
srcs = glob(["*_test.js"]),
deps = [
"//java/com/google/domain/registry/ui/js/admin",
"//java/com/google/domain/registry/ui/soy/admin:Console",
"//javascript/closure",
"//javatests/com/google/domain/registry/ui/js:testing",
],
)

View file

@ -1,306 +0,0 @@
// Copyright 2016 Google Inc. 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.
goog.setTestOnly();
goog.require('goog.History');
goog.require('goog.dispose');
goog.require('goog.dom');
goog.require('goog.soy');
goog.require('goog.string');
goog.require('goog.testing.MockControl');
goog.require('goog.testing.PropertyReplacer');
goog.require('goog.testing.asserts');
goog.require('goog.testing.jsunit');
goog.require('goog.testing.mockmatchers');
goog.require('goog.testing.net.XhrIo');
goog.require('registry.admin.Console');
goog.require('registry.soy.admin.console');
goog.require('registry.testing');
var $ = goog.dom.getRequiredElement;
var _ = goog.testing.mockmatchers.ignoreArgument;
var stubs = new goog.testing.PropertyReplacer();
var mocks = new goog.testing.MockControl();
var historyMock;
var adminConsole;
function setUp() {
registry.testing.addToDocument('<div id="test"/>');
goog.soy.renderElement($('test'), registry.soy.admin.console.main, {
xsrfToken: 'ignore',
clientIdentifier: 'ignore',
user: {
'id': 'go@daddy.tld',
'actionHref': 'http://godaddy.com',
'actionName': 'ignore'
}
});
stubs.setPath('goog.net.XhrIo', goog.testing.net.XhrIo);
historyMock = mocks.createStrictMock(goog.History);
mocks.createConstructorMock(goog, 'History')().$returns(historyMock);
historyMock.addEventListener(_, _, _);
historyMock.setEnabled(true);
mocks.$replayAll();
adminConsole = new registry.admin.Console('༼༎෴ ༎༽');
mocks.$verifyAll();
}
function tearDown() {
goog.dispose(adminConsole);
stubs.reset();
mocks.$tearDown();
goog.testing.net.XhrIo.cleanup();
}
function testCollectionView() {
historyMock.$reset();
historyMock.getToken().$returns('registrar');
mocks.$replayAll();
adminConsole.handleHashChange();
registry.testing.assertReqMockRsp(
'༼༎෴ ༎༽',
'/_dr/admin/registrar',
{op: 'read', args: {}},
{set: []});
assertEquals('We require more vespene gas.',
0, goog.testing.net.XhrIo.getSendInstances().length);
mocks.$verifyAll();
assertNotNull($('clientIdentifier'));
}
function testCreate() {
testCollectionView();
var testRegistrar = createTestRegistrar();
$('clientIdentifier').value = testRegistrar.clientIdentifier;
$('registrarName').value = testRegistrar.registrarName;
$('icannReferralEmail').value = testRegistrar.icannReferralEmail;
$('emailAddress').value = testRegistrar.emailAddress;
$('localizedAddress.street[0]').value =
testRegistrar.localizedAddress.street[0];
$('localizedAddress.city').value = testRegistrar.localizedAddress.city;
$('localizedAddress.countryCode').value =
testRegistrar.localizedAddress.countryCode;
registry.testing.click($('create-button'));
registry.testing.assertReqMockRsp(
'༼༎෴ ༎༽',
'/_dr/admin/registrar/daddy', {
op: 'create',
args: testRegistrar
},
{results: ['daddy: ok']});
testRegistrar.state = 'PENDING';
testRegistrar.lastUpdateTime = '2014-08-11T21:57:58.801Z';
testRegistrar.creationTime = '2014-08-11T21:57:58.801Z';
registry.testing.assertReqMockRsp(
'༼༎෴ ༎༽',
'/_dr/admin/registrar/daddy',
{op: 'read', args: {}},
{item: testRegistrar });
mocks.$verifyAll();
assertEquals('We require more vespene gas.',
0, goog.testing.net.XhrIo.getSendInstances().length);
assertEquals('daddy',
goog.dom.getElementsByTagNameAndClass('h1')[0].innerHTML);
assertEquals('PENDING', $('state').value);
historyMock.$reset();
historyMock.getToken().$returns('registrar');
mocks.$replayAll();
adminConsole.handleHashChange();
registry.testing.assertReqMockRsp(
'༼༎෴ ༎༽',
'/_dr/admin/registrar',
{op: 'read', args: {}},
{set: [testRegistrar]});
assertEquals('We require more vespene gas.',
0, goog.testing.net.XhrIo.getSendInstances().length);
mocks.$verifyAll();
}
function testItemViewEditSave() {
testCreate();
historyMock.$reset();
historyMock.getToken().$returns('registrar/daddy');
mocks.$replayAll();
adminConsole.handleHashChange();
var testRegistrar = createTestRegistrar();
registry.testing.assertReqMockRsp(
'༼༎෴ ༎༽',
'/_dr/admin/registrar/daddy',
{op: 'read', args: {}},
{item: testRegistrar });
assertEquals('We require more vespene gas.',
0, goog.testing.net.XhrIo.getSendInstances().length);
mocks.$verifyAll();
assertTrue('Form should be read-only.', $('registrarName').readOnly);
registry.testing.click($('reg-app-btn-edit'));
assertFalse('Form should be edible.', $('registrarName').readOnly);
testRegistrar.registrarName = 'GoDaddy';
testRegistrar.emailAddress = 'new@email.com';
testRegistrar.icannReferralEmail = 'new@referral.com';
testRegistrar.state = 'ACTIVE';
testRegistrar.allowedTlds = 'foo,bar,baz';
testRegistrar.driveFolderId = 'driveFolderId';
testRegistrar.phoneNumber = '+1.2345678900';
testRegistrar.faxNumber = '+1.2345678900';
testRegistrar.whoisServer = 'blah.blee.foo';
testRegistrar.blockPremiumNames = true;
testRegistrar.localizedAddress = {
street: ['mean', '', ''],
city: 'NYC',
state: 'AZ',
zip: '5555',
countryCode: 'NZ'
};
testRegistrar.clientCertificate = '-----BEGIN CERTIFICATE-----' +
'MIIDvTCCAqWgAwIBAgIJAK/PgPT0jTwRMA0GCSqGSIb3DQEBCwUAMHUxCzAJBgNV' +
'BAYTAlVTMREwDwYDVQQIDAhOZXcgWW9yazERMA8GA1UEBwwITmV3IFlvcmsxDzAN' +
'BgNVBAoMBkdvb2dsZTEdMBsGA1UECwwUZG9tYWluLXJlZ2lzdHJ5LXRlc3QxEDAO' +
'BgNVBAMMB2NsaWVudDEwHhcNMTUwODI2MTkxODA4WhcNNDMwMTExMTkxODA4WjB1' +
'MQswCQYDVQQGEwJVUzERMA8GA1UECAwITmV3IFlvcmsxETAPBgNVBAcMCE5ldyBZ' +
'b3JrMQ8wDQYDVQQKDAZHb29nbGUxHTAbBgNVBAsMFGRvbWFpbi1yZWdpc3RyeS10' +
'ZXN0MRAwDgYDVQQDDAdjbGllbnQxMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIB' +
'CgKCAQEAvoE/IoFJyzb0dU4NFhL8FYgy+B/GnUd5aA66CMx5xKRMbEAtIgxU8TTO' +
'W+9jdTsE00Grk3Ct4KdY73CYW+6IFXL4O0K/m5S+uajh+I2UMVZJV38RAIqNxue0' +
'Egv9M4haSsCVIPcX9b+6McywfYSF1bzPb2Gb2FAQO7Jb0BjlPhPMIROCrbG40qPg' +
'LWrl33dz+O52kO+DyZEzHqI55xH6au77sMITsJe+X23lzQcMFUUm8moiOw0EKrj/' +
'GaMTZLHP46BCRoJDAPTNx55seIwgAHbKA2VVtqrvmA2XYJQA6ipdhfKRoJFy8Z8H' +
'DYsorGtazQL2HhF/5uJD25z1m5eQHQIDAQABo1AwTjAdBgNVHQ4EFgQUParEmiSR' +
'U/Oqy8hr7k+MBKhZwVkwHwYDVR0jBBgwFoAUParEmiSRU/Oqy8hr7k+MBKhZwVkw' +
'DAYDVR0TBAUwAwEB/zANBgkqhkiG9w0BAQsFAAOCAQEAojsUhF6PtZrStnHBFWNR' +
'ryzvANB8krZlYeX9Hkqn8zIVfAkpbVmL8aZQ7yj17jSpw47PQh3x5gwA9yc/SS0G' +
'E1rGuxYH02UGbua8G0+vviSQfLtskPQzK7EIR63WNhHEo/Q9umLJkZ0LguWEBf3L' +
'q8CoXv2i/RNvqVPcTNp/zCKXJZAa8wAjNRJs834AZj4k5xwyYZ3F8D5PGz+YMOmV' +
'M9Qd+NdXSC/Qn7HQzFhE8p5elBV35P8oX5dXEfn0S7zOXDenp5JvvLoggOWOcKsq' +
'KiWDQrsT+TMKmHL94/h4t7FghtQLMzY5SGYJsYTv/LG8tewrz6KRb/Wj3JNojyEw' +
'Ug==' +
'-----END CERTIFICATE-----';
testRegistrar.phonePasscode = '01234';
testRegistrar.ipAddressWhitelist = '1.1.1.1,2.2.2.2';
testRegistrar.password = 'yoyoSheep';
testRegistrar.billingIdentifier = '12345';
testRegistrar.ianaIdentifier = '11111';
testRegistrar.url = 'http://yoyo.com';
testRegistrar.referralUrl = 'http://other.com';
testRegistrar.contacts = [{
name: 'Joe',
emailAddress: 'joe@go.com',
phoneNumber: '',
faxNumber: '',
types: 'ADMIN,TECH',
gaeUserId: '1234'
}, {
name: 'Jane',
emailAddress: 'joe@go.com',
phoneNumber: '',
faxNumber: '',
types: '',
gaeUserId: '5432'
}];
for (var i in testRegistrar) {
// Not all keys are present as inputs with id,
// e.g. clientIdentifier.
var inputElt = goog.dom.getElement(i);
if (inputElt) {
inputElt.value = testRegistrar[i];
}
if (i == 'contacts' ||
i == 'localizedAddress' ||
i == 'blockPremiumNames') {
continue;
}
}
if (testRegistrar.blockPremiumNames) {
$('blockPremiumNames').setAttribute('checked', true);
}
var addr = testRegistrar['localizedAddress'];
$('localizedAddress.street[0]').value = addr.street[0];
$('localizedAddress.street[1]').value = addr.street[1];
$('localizedAddress.street[2]').value = addr.street[2];
$('localizedAddress.city').value = addr.city;
$('localizedAddress.state').value = addr.state;
$('localizedAddress.zip').value = addr.zip;
$('localizedAddress.countryCode').value = addr.countryCode;
var contacts = testRegistrar['contacts'];
for (var c = 0; c < contacts.length; c++) {
registry.testing.click($('add-contact-button'));
var contact = contacts[c];
for (var ci in contact) {
// Form IDs are the full path ref.
$('contacts[' + c + '].' + ci).value = contact[ci];
}
}
registry.testing.click($('reg-app-btn-save'));
// Convert string to wire vals for assert comparison.
testRegistrar.billingIdentifier =
goog.string.parseInt(testRegistrar.billingIdentifier);
testRegistrar.ianaIdentifier =
goog.string.parseInt(testRegistrar.ianaIdentifier);
testRegistrar.allowedTlds = testRegistrar.allowedTlds.split(',');
testRegistrar.ipAddressWhitelist =
testRegistrar.ipAddressWhitelist.split(',');
// And the readonly field the client adds.
testRegistrar.readonly = false;
registry.testing.assertReqMockRsp(
'༼༎෴ ༎༽',
'/_dr/admin/registrar/daddy',
{op: 'update', args: testRegistrar},
{results: ['daddy: ok']});
registry.testing.assertReqMockRsp(
'༼༎෴ ༎༽',
'/_dr/admin/registrar/daddy',
{op: 'read', args: {}},
{item: testRegistrar});
assertEquals('We require more vespene gas.',
0, goog.testing.net.XhrIo.getSendInstances().length);
mocks.$verifyAll();
}
/** @return {!Object.<string, ?>} */
function createTestRegistrar() {
return {
clientIdentifier: 'daddy',
registrarName: 'The Daddy',
icannReferralEmail: 'lol@sloth.test',
emailAddress: 'foo@bar.com',
localizedAddress: {
street: ['111 8th Ave.'],
city: 'NYC',
countryCode: 'NZ'
}
};
}

View file

@ -1,207 +0,0 @@
// Copyright 2016 Google Inc. 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.
goog.setTestOnly();
goog.require('goog.History');
goog.require('goog.dispose');
goog.require('goog.dom');
goog.require('goog.soy');
goog.require('goog.testing.MockControl');
goog.require('goog.testing.PropertyReplacer');
goog.require('goog.testing.asserts');
goog.require('goog.testing.jsunit');
goog.require('goog.testing.mockmatchers');
goog.require('goog.testing.net.XhrIo');
goog.require('registry.admin.Console');
goog.require('registry.soy.admin.console');
goog.require('registry.testing');
var $ = goog.dom.getRequiredElement;
var _ = goog.testing.mockmatchers.ignoreArgument;
var stubs = new goog.testing.PropertyReplacer();
var mocks = new goog.testing.MockControl();
var historyMock;
var adminConsole;
function setUp() {
registry.testing.addToDocument('<div id="test"/>');
goog.soy.renderElement($('test'), registry.soy.admin.console.main, {
xsrfToken: 'ignore',
clientId: 'ignore',
user: {
'id': 'go@daddy.tld',
'actionHref': 'http://godaddy.com',
'actionName': 'ignore'
}
});
stubs.setPath('goog.net.XhrIo', goog.testing.net.XhrIo);
historyMock = mocks.createStrictMock(goog.History);
mocks.createConstructorMock(goog, 'History')().$returns(historyMock);
historyMock.addEventListener(_, _, _);
historyMock.setEnabled(true);
mocks.$replayAll();
adminConsole = new registry.admin.Console('༼༎෴ ༎༽');
mocks.$verifyAll();
}
function tearDown() {
goog.dispose(adminConsole);
stubs.reset();
mocks.$tearDown();
goog.testing.net.XhrIo.cleanup();
}
function testCollectionView() {
historyMock.$reset();
historyMock.getToken().$returns('registry');
mocks.$replayAll();
adminConsole.handleHashChange();
registry.testing.assertReqMockRsp(
'༼༎෴ ༎༽',
'/_dr/admin/registry',
{op: 'read', args: {}},
{set: []});
assertEquals('We require more vespene gas.',
0, goog.testing.net.XhrIo.getSendInstances().length);
mocks.$verifyAll();
assertNotNull($('newTldName'));
}
/** Creates test registry. */
function createTestRegistry() {
return {
addGracePeriod: 'PT432000S',
autoRenewGracePeriod: 'PT3888000S',
automaticTransferLength: 'PT432000S',
name: 'foo',
pendingDeleteLength: 'PT432000S',
redemptionGracePeriod: 'PT2592000S',
renewGracePeriod: 'PT432000S',
state: 'PREDELEGATION',
tldStateTransitions: '{1970-01-01T00:00:00.000Z=PREDELEGATION}',
transferGracePeriod: 'PT432000S'
};
}
function testCreate() {
testCollectionView();
$('newTldName').value = 'foo';
registry.testing.click($('create-button'));
registry.testing.assertReqMockRsp(
'༼༎෴ ༎༽',
'/_dr/admin/registry/foo', {
op: 'create',
args: {
newTldName: 'foo'
}
},
{results: ['foo: ok']});
var testReg = createTestRegistry();
testReg.creationTime = '2014-08-07T20:35:39.142Z';
testReg.lastUpdateTime = '2014-08-07T20:35:39.142Z';
registry.testing.assertReqMockRsp(
'༼༎෴ ༎༽',
'/_dr/admin/registry/foo',
{op: 'read', args: {}},
{item: testReg });
mocks.$verifyAll();
assertEquals('We require more vespene gas.',
0, goog.testing.net.XhrIo.getSendInstances().length);
assertEquals('foo', goog.dom.getElementsByTagNameAndClass('h1')[0].innerHTML);
historyMock.$reset();
historyMock.getToken().$returns('registry');
mocks.$replayAll();
adminConsole.handleHashChange();
registry.testing.assertReqMockRsp(
'༼༎෴ ༎༽',
'/_dr/admin/registry',
{op: 'read', args: {}},
{set: [testReg]});
assertEquals('We require more vespene gas.',
0, goog.testing.net.XhrIo.getSendInstances().length);
mocks.$verifyAll();
}
function testItemViewEditSave() {
testCreate();
historyMock.$reset();
historyMock.getToken().$returns('registry/foo');
mocks.$replayAll();
adminConsole.handleHashChange();
var testReg = createTestRegistry();
registry.testing.assertReqMockRsp(
'༼༎෴ ༎༽',
'/_dr/admin/registry/foo',
{op: 'read', args: {}},
{item: testReg });
assertEquals('We require more vespene gas.',
0, goog.testing.net.XhrIo.getSendInstances().length);
mocks.$verifyAll();
assertTrue('Form should be read-only.', $('addGracePeriod').readOnly);
registry.testing.click($('reg-app-btn-edit'));
assertFalse('Form should be editable.', $('addGracePeriod').readOnly);
// Edit state
testReg.tldStateTransitions = 'GENERAL_AVAILABILITY,1970-01-01T00:00:00.000Z';
for (var i in testReg) {
// Not all keys are present as inputs with id,
// e.g. name.
var inputElt = goog.dom.getElement(i);
if (inputElt) {
inputElt.value = testReg[i];
}
}
registry.testing.click($('reg-app-btn-save'));
// Convert string to wire vals.
var tldStateTransitionStr = testReg.tldStateTransitions;
testReg.tldStateTransitions = [{
tldState: 'GENERAL_AVAILABILITY',
transitionTime: '1970-01-01T00:00:00.000Z'
}];
// And the readonly field the client adds.
testReg.readonly = false;
registry.testing.assertReqMockRsp(
'༼༎෴ ༎༽',
'/_dr/admin/registry/foo',
{op: 'update', args: testReg},
{results: ['foo: ok']});
// Restore the stringified version.
testReg.tldStateTransitions = tldStateTransitionStr;
registry.testing.assertReqMockRsp(
'༼༎෴ ༎༽',
'/_dr/admin/registry/foo',
{op: 'read', args: {}},
{item: testReg});
assertEquals('We require more vespene gas.',
0, goog.testing.net.XhrIo.getSendInstances().length);
mocks.$verifyAll();
}

View file

@ -1,29 +0,0 @@
// Copyright 2016 Google Inc. 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 com.google.domain.registry.ui.server.admin;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** Unit tests for {@link AdminUiServlet}. */
@RunWith(JUnit4.class)
public class AdminUiServletTest {
@Test
public void testTofuCompilation() throws Exception {
AdminUiServlet.TOFU_SUPPLIER.get();
}
}

View file

@ -1,32 +0,0 @@
package(default_visibility = ["//java/com/google/domain/registry:registry_project"])
load("//java/com/google/testing/builddefs:GenTestRules.bzl", "GenTestRules")
java_library(
name = "admin",
srcs = glob(["*.java"]),
deps = [
"//java/com/google/common/base",
"//java/com/google/common/collect",
"//java/com/google/domain/registry/config",
"//java/com/google/domain/registry/export/sheet",
"//java/com/google/domain/registry/model",
"//java/com/google/domain/registry/ui/server/admin",
"//java/com/google/domain/registry/util",
"//javatests/com/google/domain/registry/testing",
"//third_party/java/appengine:appengine-api-testonly",
"//third_party/java/joda_time",
"//third_party/java/junit",
"//third_party/java/mockito",
"//third_party/java/objectify:objectify-v4_1",
"//third_party/java/servlet/servlet_api",
"//third_party/java/truth",
],
)
GenTestRules(
name = "GeneratedTestRules",
test_files = glob(["*Test.java"]),
deps = [":admin"],
)

View file

@ -1,340 +0,0 @@
// Copyright 2016 Google Inc. 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 com.google.domain.registry.ui.server.admin;
import static com.google.common.truth.Truth.assertThat;
import static com.google.domain.registry.model.ofy.ObjectifyService.ofy;
import static com.google.domain.registry.testing.DatastoreHelper.createTld;
import static com.google.domain.registry.testing.TaskQueueHelper.assertNoTasksEnqueued;
import static com.google.domain.registry.testing.TaskQueueHelper.assertTasksEnqueued;
import static org.mockito.Mockito.when;
import com.google.appengine.api.modules.ModulesService;
import com.google.common.base.Suppliers;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.domain.registry.config.RegistryEnvironment;
import com.google.domain.registry.export.sheet.SyncRegistrarsSheetTask;
import com.google.domain.registry.model.common.EntityGroupRoot;
import com.google.domain.registry.model.ofy.Ofy;
import com.google.domain.registry.model.registrar.Registrar;
import com.google.domain.registry.model.registrar.Registrar.State;
import com.google.domain.registry.model.registrar.RegistrarAddress;
import com.google.domain.registry.model.registrar.RegistrarContact;
import com.google.domain.registry.testing.AppEngineRule;
import com.google.domain.registry.testing.CertificateSamples;
import com.google.domain.registry.testing.FakeClock;
import com.google.domain.registry.testing.InjectRule;
import com.google.domain.registry.testing.TaskQueueHelper.TaskMatcher;
import com.google.domain.registry.util.CidrAddressBlock;
import com.google.domain.registry.util.DateTimeUtils;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.runners.MockitoJUnitRunner;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
/** Tests for {@link RegistrarServlet}. */
@RunWith(MockitoJUnitRunner.class)
public class RegistrarServletTest {
//TODO(pmy): remove this duplicate of the registrar console test.
@Rule
public final AppEngineRule appEngine = AppEngineRule.builder()
.withDatastore()
.withTaskQueue()
.build();
@Rule
public final InjectRule inject = new InjectRule();
@Mock
private ModulesService modulesService;
final String clientId = "NewDaddy";
final String tld = "xn--q9jyb4c";
FakeClock clock = new FakeClock(DateTimeUtils.START_OF_TIME.plusMillis(1));
HttpServletRequest req;
Registrar registrar;
Map<String, Object> regMap;
RegistrarServlet servlet;
/**
* Empty whoisServer and referralUrl fields should be set to
* defaults by server.
*/
static Registrar simulateDefaultsForEmptyFields(Registrar registrar) {
return registrar.asBuilder()
.setWhoisServer(RegistryEnvironment.get().config().getRegistrarDefaultWhoisServer())
.setReferralUrl(
RegistryEnvironment.get().config().getRegistrarDefaultReferralUrl().toString())
.build();
}
@Before
public void init() {
inject.setStaticField(Ofy.class, "clock", clock);
inject.setStaticField(
Registrar.class, "saltSupplier", Suppliers.ofInstance(new byte[]{1, 2, 3, 4}));
inject.setStaticField(SyncRegistrarsSheetTask.class, "modulesService", modulesService);
req = Mockito.mock(HttpServletRequest.class);
when(req.getContextPath()).thenReturn("/_dr/admin");
when(req.getRequestURI()).thenReturn("/_dr/admin/registrar/" + clientId);
when(modulesService.getVersionHostname("backend", null)).thenReturn("backend.hostname");
createTld(tld);
}
@Test
public void testCreateRegistrar() {
registrar = loadRegistrar(clientId);
assertThat(registrar).isNull();
// A minimal registrar.
registrar = new Registrar.Builder()
.setClientIdentifier(clientId)
.setRegistrarName("TheRegistrar")
.setEmailAddress("admin@registrar.com")
.setIcannReferralEmail("lol@sloth.test")
.setState(State.ACTIVE)
.setType(Registrar.Type.TEST)
.build();
regMap = registrar.toJsonMap();
servlet = new RegistrarServlet();
Map<String, ?> result = servlet.doJsonPost(req, ImmutableMap.of(
"op", "create",
"args", regMap));
assertThat(result).containsEntry("results", ImmutableList.of(clientId + ": ok"));
registrar = simulateDefaultsForEmptyFields(registrar);
Registrar createdRegistrar = loadRegistrar(clientId);
assertThat(createdRegistrar).isEqualTo(registrar);
registrar = createdRegistrar;
}
@Test
public void testFullRegistrarUpdate() throws Exception {
testCreateRegistrar();
registrar = makeFullRegistrarObject();
regMap = registrar.toJsonMap();
regMap.put("password", "password");
sendUpdate();
registrar = registrar.asBuilder()
.build();
assertThat(loadRegistrar(clientId)).isEqualTo(registrar);
assertTasksEnqueued("sheet", new TaskMatcher()
.url(SyncRegistrarsSheetTask.PATH)
.method("GET")
.header("Host", "backend.hostname"));
}
@Test
public void testMoreUpdates() throws Exception {
testFullRegistrarUpdate();
// Toggle the block premium names flag.
regMap.put("blockPremiumNames", true);
sendUpdate();
registrar = registrar.asBuilder()
.setBlockPremiumNames(true)
.build();
assertThat(loadRegistrar(clientId)).isEqualTo(registrar);
testSetAndNull("whoisServer", "foo.bar.com");
testSetAndNull("url", "http://acme.com/");
testSetAndNull("referralUrl", "http://acme.com/");
testSetAndNull("phoneNumber", "+1.5551234444");
testSetAndNull("faxNumber", "+1.5551234444");
regMap.put("clientCertificate", CertificateSamples.SAMPLE_CERT);
sendUpdate();
registrar = registrar.asBuilder()
.setClientCertificate((String) regMap.get("clientCertificate"), clock.nowUtc())
.build();
assertThat(loadRegistrar(clientId)).isEqualTo(registrar);
regMap.put("clientCertificate", CertificateSamples.SAMPLE_CERT2);
sendUpdate();
registrar = registrar.asBuilder()
.setClientCertificate(CertificateSamples.SAMPLE_CERT2, clock.nowUtc())
.build();
assertThat(loadRegistrar(clientId)).isEqualTo(registrar);
// Update the password.
regMap.put("password", "newPassword");
sendUpdate();
registrar = registrar.asBuilder().setPassword("newPassword").build();
assertThat(loadRegistrar(clientId).testPassword("newPassword")).isTrue();
}
@Test
public void testContactCreate() throws Exception {
testFullRegistrarUpdate();
Map<String, /* @Nullable */ Object> contact = new HashMap<>();
contact.put("name", "foo");
contact.put("emailAddress", "foo@lol.com");
contact.put("types", "ADMIN,LEGAL");
contact.put("gaeUserId", "1234");
regMap.put("contacts", ImmutableList.of(contact));
sendUpdate();
assertThat(registrar.getContacts()).containsExactly(
new RegistrarContact.Builder()
.setParent(registrar)
.setName("foo")
.setEmailAddress("foo@lol.com")
.setTypes(ImmutableSet.of(RegistrarContact.Type.ADMIN, RegistrarContact.Type.LEGAL))
.setGaeUserId("1234")
.build());
}
@Test
public void testUpdate_badState_returnsFormFieldError() throws Exception {
testCreateRegistrar();
Map<String, ?> result = new RegistrarServlet().doJsonPost(req, ImmutableMap.of(
"op", "update",
"args", ImmutableMap.of(
"emailAddress", registrar.getEmailAddress(),
"icannReferralEmail", registrar.getIcannReferralEmail(),
"registrarName", registrar.getRegistrarName(),
"state", "boo!")));
assertThat(result).containsEntry("status", "ERROR");
assertThat(result).containsEntry("field", "state");
assertThat(result).containsEntry("message", "Enum State does not contain 'boo!'");
assertNoTasksEnqueued("sheet");
}
@Test
public void testContactUpdates() throws Exception {
testFullRegistrarUpdate();
Map<String, /* @Nullable */ Object> adminContact1 = new HashMap<>();
adminContact1.put("name", "contact1");
adminContact1.put("emailAddress", "contact1@email.com");
adminContact1.put("phoneNumber", "+1.2125650666");
adminContact1.put("faxNumber", null);
adminContact1.put("types", "ADMIN");
Map<String, /* @Nullable */ Object> adminContact2 = new HashMap<>();
adminContact2.put("name", "foo");
adminContact2.put("emailAddress", "foo@lol.com");
adminContact2.put("types", "ADMIN");
adminContact2.put("gaeUserId", "1234");
regMap.put("contacts", ImmutableList.of(adminContact1, adminContact2));
sendUpdate();
assertThat(loadRegistrar(clientId).getContacts()).containsExactly(
new RegistrarContact.Builder()
.setParent(registrar)
.setName("contact1")
.setEmailAddress("contact1@email.com")
.setPhoneNumber("+1.2125650666")
.setFaxNumber(null)
.setTypes(ImmutableSet.of(RegistrarContact.Type.ADMIN))
.build(),
new RegistrarContact.Builder()
.setParent(registrar)
.setName("foo")
.setEmailAddress("foo@lol.com")
.setPhoneNumber(null)
.setFaxNumber(null)
.setTypes(ImmutableSet.of(RegistrarContact.Type.ADMIN))
.setGaeUserId("1234")
.build());
}
@Test
public void testCertificateUpdate() throws Exception {
testFullRegistrarUpdate();
regMap.put("clientCertificate", CertificateSamples.SAMPLE_CERT2);
sendUpdate();
assertThat(loadRegistrar(clientId).getClientCertificate())
.isEqualTo(CertificateSamples.SAMPLE_CERT2);
assertThat(loadRegistrar(clientId).getClientCertificateHash())
.isEqualTo(CertificateSamples.SAMPLE_CERT2_HASH);
}
private Registrar makeFullRegistrarObject() {
return registrar.asBuilder()
.setRegistrarName("TRO LLC")
.setAllowedTlds(ImmutableSet.of(tld))
.setBillingIdentifier(12345L)
.setBlockPremiumNames(false)
.setEmailAddress("email@foo.bar")
.setPhoneNumber("+1.2125551212")
.setFaxNumber("+1.2125551212")
.setLocalizedAddress(new RegistrarAddress.Builder()
.setCity("loc city")
.setCountryCode("CC")
.setState("loc state")
.setStreet(ImmutableList.of("loc street1", "loc street2"))
.setZip("loc zip")
.build())
.setIpAddressWhitelist(ImmutableList.of(CidrAddressBlock.create("192.168.0.1/32")))
.setPassword("password")
.setReferralUrl("referral url")
.setWhoisServer("whois.server")
.setUrl("url")
.build();
}
private static Registrar loadRegistrar(String id) {
return ofy().load().type(Registrar.class)
.parent(EntityGroupRoot.getCrossTldKey()).id(id).now();
}
private void testSetAndNull(String field, String val) throws Exception {
// Test null first and then restore value second to not affect
// full registrar state in later tests.
regMap.put(field, null);
sendUpdate();
registrar = setBuilderField(registrar.asBuilder(), field, null, val.getClass()).build();
assertThat(loadRegistrar(clientId)).isEqualTo(registrar);
regMap.put(field, val);
sendUpdate();
registrar = setBuilderField(registrar.asBuilder(), field, val).build();
assertThat(loadRegistrar(clientId)).isEqualTo(registrar);
}
private Registrar.Builder setBuilderField(
Registrar.Builder builder, String field, Object val, Class<?>... nullClass) throws Exception {
java.lang.reflect.Method setter = Registrar.Builder.class.getMethod(
"set" + field.substring(0, 1).toUpperCase() + field.substring(1),
val == null ? nullClass[0] : val.getClass());
setter.invoke(builder, val);
return builder;
}
private void sendUpdate() {
clock.setTo(clock.nowUtc().plusMinutes(1));
Map<String, ?> result = servlet.doJsonPost(req, ImmutableMap.of(
"op", "update",
"args", regMap));
assertThat(result).doesNotContainEntry("status", "ERROR");
}
}

View file

@ -1,304 +0,0 @@
// Copyright 2016 Google Inc. 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 com.google.domain.registry.ui.server.admin;
import static com.google.common.truth.Truth.assertThat;
import static com.google.domain.registry.model.registry.Registries.getTlds;
import static com.google.domain.registry.util.DateTimeUtils.START_OF_TIME;
import static org.joda.time.DateTimeZone.UTC;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSortedMap;
import com.google.domain.registry.model.ofy.Ofy;
import com.google.domain.registry.model.registry.Registry;
import com.google.domain.registry.model.registry.Registry.TldState;
import com.google.domain.registry.testing.AppEngineRule;
import com.google.domain.registry.testing.FakeClock;
import com.google.domain.registry.testing.InjectRule;
import org.joda.time.DateTime;
import org.joda.time.Duration;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.mockito.Mockito;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
/** Tests for {@link RegistryServlet}. */
@RunWith(JUnit4.class)
public class RegistryServletTest {
@Rule
public final AppEngineRule appEngine = AppEngineRule.builder()
.withDatastore()
.build();
HttpServletRequest req;
@Rule
public final InjectRule inject = new InjectRule();
FakeClock clock = new FakeClock();
DateTime now = DateTime.now(UTC);
DateTime creationTime;
private static final Map<String, ?> SUCCESS = ImmutableMap.of("results", "OK");
private Registry createRegistry(String tld, TldState tldState) {
return createRegistry(tld, ImmutableSortedMap.of(START_OF_TIME, tldState));
}
private Registry createRegistry(
String tld, ImmutableSortedMap<DateTime, TldState> tldStateTransitions) {
return new Registry.Builder()
.setTldStr(tld)
.setTldStateTransitions(tldStateTransitions)
.build();
}
@Before
public void setUp() {
inject.setStaticField(Ofy.class, "clock", clock);
req = Mockito.mock(HttpServletRequest.class);
Mockito.when(req.getContextPath()).thenReturn("/_dr/admin");
}
@Test
public void testParsePath() {
Mockito.when(req.getRequestURI()).thenReturn("/_dr/admin/registry/foo");
assertThat(new RegistryServlet().parsePath(req)).isEqualTo("registry/foo");
}
@Test
public void testParseId() {
Mockito.when(req.getRequestURI()).thenReturn("/_dr/admin/registry/foo");
assertThat(new RegistryServlet().parseId(req)).isEqualTo("foo");
}
@Test
public void testPost() {
String tld = "xn--q9jyb4c";
Mockito.when(req.getRequestURI()).thenReturn("/_dr/admin/registry/" + tld);
assertThat(getTlds()).doesNotContain(tld);
clock.setTo(clock.nowUtc().plusMinutes(1));
new RegistryServlet().doJsonPost(req, ImmutableMap.of("op", "create"));
creationTime = clock.nowUtc();
assertThat(Registry.get(tld)).isEqualTo(
createRegistry(tld, TldState.PREDELEGATION));
clock.setTo(clock.nowUtc().plusMinutes(1));
Map<String, ?> result = new RegistryServlet().doJsonPost(req, ImmutableMap.of(
"op", "update",
"args", ImmutableMap.of(
"tldStateTransitions", ImmutableList.of(
ImmutableMap.of(
"transitionTime", START_OF_TIME.toString(), "tldState", "PREDELEGATION"),
ImmutableMap.of(
"transitionTime", now.toString(), "tldState", "SUNRUSH")))));
assertThat(result).isEqualTo(SUCCESS);
assertThat(Registry.get(tld)).isEqualTo(
createRegistry(tld,
ImmutableSortedMap.of(
START_OF_TIME, TldState.PREDELEGATION,
now, TldState.SUNRUSH)));
clock.setTo(clock.nowUtc().plusMinutes(1));
result = new RegistryServlet().doJsonPost(req, ImmutableMap.of(
"op", "update",
"args", ImmutableMap.of()));
assertThat(result).isEqualTo(SUCCESS);
assertThat(Registry.get(tld)).isEqualTo(
createRegistry(tld,
ImmutableSortedMap.of(
START_OF_TIME, TldState.PREDELEGATION,
now, TldState.SUNRUSH)));
clock.setTo(clock.nowUtc().plusMinutes(1));
result = new RegistryServlet().doJsonPost(req, ImmutableMap.of(
"op", "update",
"args", ImmutableMap.of(
"tldStateTransitions", ImmutableList.of(
ImmutableMap.of(
"transitionTime", START_OF_TIME.toString(), "tldState", "PREDELEGATION"),
ImmutableMap.of(
"transitionTime", now.toString(), "tldState", "SUNRISE"),
ImmutableMap.of(
"transitionTime", now.plusMonths(1).toString(), "tldState", "SUNRUSH")))));
assertThat(result).isEqualTo(SUCCESS);
assertThat(Registry.get(tld)).isEqualTo(
createRegistry(tld,
ImmutableSortedMap.of(
START_OF_TIME, TldState.PREDELEGATION,
now, TldState.SUNRISE,
now.plusMonths(1), TldState.SUNRUSH)));
clock.setTo(clock.nowUtc().plusMinutes(1));
result = new RegistryServlet().doJsonPost(req, ImmutableMap.of(
"op", "update",
"args", ImmutableMap.of(
"tldStateTransitions", ImmutableList.of(
ImmutableMap.of(
"transitionTime", START_OF_TIME.toString(), "tldState", "PREDELEGATION"),
ImmutableMap.of(
"transitionTime", now.toString(), "tldState", "SUNRISE"),
ImmutableMap.of(
"transitionTime", now.plusMonths(1).toString(), "tldState", "SUNRUSH"),
ImmutableMap.of(
"transitionTime", now.plusMonths(2).toString(), "tldState", "QUIET_PERIOD"),
ImmutableMap.of(
"transitionTime", now.plusMonths(3).toString(),
"tldState", "GENERAL_AVAILABILITY")))));
assertThat(result).isEqualTo(SUCCESS);
assertThat(Registry.get(tld)).isEqualTo(
createRegistry(tld,
ImmutableSortedMap.of(
START_OF_TIME, TldState.PREDELEGATION,
now, TldState.SUNRISE,
now.plusMonths(1), TldState.SUNRUSH,
now.plusMonths(2), TldState.QUIET_PERIOD,
now.plusMonths(3), TldState.GENERAL_AVAILABILITY)));
clock.setTo(clock.nowUtc().plusMinutes(1));
result = new RegistryServlet().doJsonPost(req, ImmutableMap.of(
"op", "update",
"args", ImmutableMap.of(
"tldStateTransitions", ImmutableList.of(
ImmutableMap.of(
"transitionTime", START_OF_TIME.toString(), "tldState", "PREDELEGATION"),
ImmutableMap.of(
"transitionTime", now.toString(), "tldState", "SUNRUSH"),
ImmutableMap.of(
"transitionTime", now.plusMonths(1).toString(),
"tldState", "GENERAL_AVAILABILITY")))));
assertThat(result).isEqualTo(SUCCESS);
assertThat(Registry.get(tld)).isEqualTo(
createRegistry(tld,
ImmutableSortedMap.of(
START_OF_TIME, TldState.PREDELEGATION,
now, TldState.SUNRUSH,
now.plusMonths(1), TldState.GENERAL_AVAILABILITY)));
Registry tldRegistry = Registry.get(tld);
// Switch to foobar.
Mockito.when(req.getRequestURI()).thenReturn("/_dr/admin/registry/foobar");
clock.setTo(clock.nowUtc().plusMinutes(1));
new RegistryServlet().doJsonPost(req, ImmutableMap.of(
"op", "create"));
creationTime = clock.nowUtc();
clock.setTo(clock.nowUtc().plusMinutes(1));
result = new RegistryServlet().doJsonPost(req, ImmutableMap.of(
"op", "update",
"args", ImmutableMap.of(
"tldStateTransitions", ImmutableList.of(
ImmutableMap.of(
"transitionTime", START_OF_TIME.toString(), "tldState", "QUIET_PERIOD")))));
assertThat(result).isEqualTo(SUCCESS);
assertThat(Registry.get("foobar")).isEqualTo(
createRegistry("foobar", ImmutableSortedMap.of(START_OF_TIME, TldState.QUIET_PERIOD)));
// Make sure updating this new TLD "foobar" didn't modify the tld we are using.
assertThat(Registry.get(tld)).isEqualTo(tldRegistry);
// This should fail since the states are out of order (SUNRISE comes before SUNRUSH).
Mockito.when(req.getRequestURI()).thenReturn("/_dr/admin/registry/" + tld);
clock.setTo(clock.nowUtc().plusMinutes(1));
result = new RegistryServlet().doJsonPost(req, ImmutableMap.of(
"op", "update",
"args", ImmutableMap.of(
"id", tld,
"tldStateTransitions", ImmutableList.of(
ImmutableMap.of(
"transitionTime", START_OF_TIME.toString(), "tldState", "PREDELEGATION"),
ImmutableMap.of(
"transitionTime", now.toString(), "tldState", "SUNRUSH"),
ImmutableMap.of(
"transitionTime", now.plusMonths(1).toString(), "tldState", "SUNRISE")))));
assertThat(result).isNotEqualTo(SUCCESS);
Mockito.when(req.getRequestURI()).thenReturn("/_dr/admin/registry/xn--q9jyb4c");
// This should fail since the same state appears twice.
clock.setTo(clock.nowUtc().plusMinutes(1));
result = new RegistryServlet().doJsonPost(req, ImmutableMap.of(
"op", "update",
"args", ImmutableMap.of(
"tldStateTransitions", ImmutableList.of(
ImmutableMap.of(
"transitionTime", START_OF_TIME.toString(), "tldState", "PREDELEGATION"),
ImmutableMap.of(
"transitionTime", now.toString(), "tldState", "SUNRISE"),
ImmutableMap.of(
"transitionTime", now.plusMonths(1).toString(), "tldState", "SUNRISE")))));
assertThat(result).isNotEqualTo(SUCCESS);
// This is the same as the case above, but with a different ordering. It should still fail
// regardless.
clock.setTo(clock.nowUtc().plusMinutes(1));
result = new RegistryServlet().doJsonPost(req, ImmutableMap.of(
"op", "update",
"args", ImmutableMap.of(
"tldStateTransitions", ImmutableList.of(
ImmutableMap.of(
"transitionTime", now.plusMonths(1).toString(), "tldState", "SUNRISE"),
ImmutableMap.of(
"transitionTime", now.toString(), "tldState", "SUNRUSH"),
ImmutableMap.of(
"transitionTime", START_OF_TIME.toString(), "tldState", "PREDELEGATION")))));
assertThat(result).isNotEqualTo(SUCCESS);
// To foobar.
Mockito.when(req.getRequestURI()).thenReturn("/_dr/admin/registry/foobar");
// Test that all grace periods and other various status periods can be configured.
clock.setTo(clock.nowUtc().plusMinutes(1));
result = new RegistryServlet().doJsonPost(req, ImmutableMap.of(
"op", "update",
"args", new ImmutableMap.Builder<String, String>()
.put("addGracePeriod", Duration.standardSeconds(1).toString())
.put("autoRenewGracePeriod", Duration.standardSeconds(2).toString())
.put("redemptionGracePeriod", Duration.standardSeconds(3).toString())
.put("renewGracePeriod", Duration.standardSeconds(4).toString())
.put("transferGracePeriod", Duration.standardSeconds(5).toString())
.put("automaticTransferLength", Duration.standardSeconds(6).toString())
.put("pendingDeleteLength", Duration.standardSeconds(7).toString()).build()));
assertThat(result).isEqualTo(SUCCESS);
Registry loadedRegistry = Registry.get("foobar");
assertThat(loadedRegistry.getAddGracePeriodLength()).isEqualTo(Duration.standardSeconds(1));
assertThat(loadedRegistry.getAutoRenewGracePeriodLength())
.isEqualTo(Duration.standardSeconds(2));
assertThat(loadedRegistry.getRedemptionGracePeriodLength())
.isEqualTo(Duration.standardSeconds(3));
assertThat(loadedRegistry.getRenewGracePeriodLength()).isEqualTo(Duration.standardSeconds(4));
assertThat(loadedRegistry.getTransferGracePeriodLength())
.isEqualTo(Duration.standardSeconds(5));
assertThat(loadedRegistry.getAutomaticTransferLength()).isEqualTo(Duration.standardSeconds(6));
assertThat(loadedRegistry.getPendingDeleteLength()).isEqualTo(Duration.standardSeconds(7));
}
}