Validate individual fee types

Currently we validate the fee extension by summing up all fees present in the extension and comparing it against the total fee to be charged. While this works in most cases, we'd like the ability to individually validate each fee. This is especially useful during EAP when two fees are charged, a regular "create" fee that would also be amount we charge during renewal, and a one time "EAP" fee.

Because we can only distinguish fees by their descriptions, we try to match the description to the format string of the fee type enums. We also only require individual fee matches when we are charging more than one type of fees, which makes the change compatible with most existing use cases where only one fees is charged and the description field is ignored in the extension.

We expect the workflow to be that a registrar sends a domain check, and we reply with exactly what fees we are expecting, and then it will use the descriptions in the response to send us a domain create with the correct fees.

Note that we aggregate fees within the same FeeType together. Normally there will only be one fee per type, but in case of custom logic there could be more than one fee for the same type. There is no way to distinguish them as they both use the same description. So it is simpler to just aggregate them.

This CL also includes some reformatting that conforms to google-java-format output.

-------------
Created by MOE: https://github.com/google/moe
MOE_MIGRATED_REVID=186530316
This commit is contained in:
jianglai 2018-02-21 15:34:13 -08:00
parent 1965c0a0aa
commit ff221fba96
13 changed files with 355 additions and 106 deletions

View file

@ -588,6 +588,9 @@ An EPP flow that creates a new domain resource.
* Domain labels cannot be longer than 63 characters. * Domain labels cannot be longer than 63 characters.
* More than one contact for a given role is not allowed. * More than one contact for a given role is not allowed.
* No part of a domain name can be empty. * No part of a domain name can be empty.
* The fee description passed in the transform command matches multiple fee
types.
* The fee description passed in the transform command cannot be parsed.
* Domain name starts with xn-- but is not a valid IDN. * Domain name starts with xn-- but is not a valid IDN.
* The specified trademark validator is not supported. * The specified trademark validator is not supported.
* Domain labels cannot begin with a dash. * Domain labels cannot begin with a dash.

View file

@ -141,6 +141,8 @@ import org.joda.time.Duration;
* @error {@link DomainFlowUtils.EmptyDomainNamePartException} * @error {@link DomainFlowUtils.EmptyDomainNamePartException}
* @error {@link DomainFlowUtils.ExceedsMaxRegistrationYearsException} * @error {@link DomainFlowUtils.ExceedsMaxRegistrationYearsException}
* @error {@link DomainFlowUtils.ExpiredClaimException} * @error {@link DomainFlowUtils.ExpiredClaimException}
* @error {@link DomainFlowUtils.FeeDescriptionMultipleMatchesException}
* @error {@link DomainFlowUtils.FeeDescriptionParseException}
* @error {@link DomainFlowUtils.FeesMismatchException} * @error {@link DomainFlowUtils.FeesMismatchException}
* @error {@link DomainFlowUtils.FeesRequiredDuringEarlyAccessProgramException} * @error {@link DomainFlowUtils.FeesRequiredDuringEarlyAccessProgramException}
* @error {@link DomainFlowUtils.FeesRequiredForPremiumNameException} * @error {@link DomainFlowUtils.FeesRequiredForPremiumNameException}

View file

@ -17,6 +17,7 @@ package google.registry.flows.domain;
import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkState; import static com.google.common.base.Preconditions.checkState;
import static com.google.common.base.Predicates.equalTo; import static com.google.common.base.Predicates.equalTo;
import static com.google.common.collect.ImmutableMap.toImmutableMap;
import static com.google.common.collect.Iterables.any; import static com.google.common.collect.Iterables.any;
import static com.google.common.collect.Sets.difference; import static com.google.common.collect.Sets.difference;
import static com.google.common.collect.Sets.intersection; import static com.google.common.collect.Sets.intersection;
@ -43,6 +44,7 @@ import com.google.common.base.Joiner;
import com.google.common.base.Splitter; import com.google.common.base.Splitter;
import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableMultimap;
import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Sets; import com.google.common.collect.Sets;
import com.google.common.collect.Streams; import com.google.common.collect.Streams;
@ -78,6 +80,7 @@ import google.registry.model.domain.DomainResource;
import google.registry.model.domain.ForeignKeyedDesignatedContact; import google.registry.model.domain.ForeignKeyedDesignatedContact;
import google.registry.model.domain.LrpTokenEntity; import google.registry.model.domain.LrpTokenEntity;
import google.registry.model.domain.Period; import google.registry.model.domain.Period;
import google.registry.model.domain.fee.BaseFee.FeeType;
import google.registry.model.domain.fee.Credit; import google.registry.model.domain.fee.Credit;
import google.registry.model.domain.fee.Fee; import google.registry.model.domain.fee.Fee;
import google.registry.model.domain.fee.FeeQueryCommandExtensionItem; import google.registry.model.domain.fee.FeeQueryCommandExtensionItem;
@ -111,8 +114,10 @@ import google.registry.model.reporting.HistoryEntry;
import google.registry.model.tmch.ClaimsListShard; import google.registry.model.tmch.ClaimsListShard;
import google.registry.util.Idn; import google.registry.util.Idn;
import java.math.BigDecimal; import java.math.BigDecimal;
import java.util.Comparator;
import java.util.HashSet; import java.util.HashSet;
import java.util.List; import java.util.List;
import java.util.Map.Entry;
import java.util.Objects; import java.util.Objects;
import java.util.Optional; import java.util.Optional;
import java.util.Set; import java.util.Set;
@ -172,8 +177,7 @@ public class DomainFlowUtils {
* *
* @see #validateDomainNameWithIdnTables(InternetDomainName) * @see #validateDomainNameWithIdnTables(InternetDomainName)
*/ */
public static InternetDomainName validateDomainName(String name) public static InternetDomainName validateDomainName(String name) throws EppException {
throws EppException {
if (!ALLOWED_CHARS.matchesAllOf(name)) { if (!ALLOWED_CHARS.matchesAllOf(name)) {
throw new BadDomainNameCharacterException(); throw new BadDomainNameCharacterException();
} }
@ -237,8 +241,7 @@ public class DomainFlowUtils {
} }
/** Check if the registrar running the flow has access to the TLD in question. */ /** Check if the registrar running the flow has access to the TLD in question. */
public static void checkAllowedAccessToTld(String clientId, String tld) public static void checkAllowedAccessToTld(String clientId, String tld) throws EppException {
throws EppException {
if (!Registrar.loadByClientIdCached(clientId).get().getAllowedTlds().contains(tld)) { if (!Registrar.loadByClientIdCached(clientId).get().getAllowedTlds().contains(tld)) {
throw new DomainFlowUtils.NotAuthorizedForTldException(tld); throw new DomainFlowUtils.NotAuthorizedForTldException(tld);
} }
@ -247,8 +250,9 @@ public class DomainFlowUtils {
/** Check that the DS data that will be set on a domain is valid. */ /** Check that the DS data that will be set on a domain is valid. */
static void validateDsData(Set<DelegationSignerData> dsData) throws EppException { static void validateDsData(Set<DelegationSignerData> dsData) throws EppException {
if (dsData != null && dsData.size() > MAX_DS_RECORDS_PER_DOMAIN) { if (dsData != null && dsData.size() > MAX_DS_RECORDS_PER_DOMAIN) {
throw new TooManyDsRecordsException(String.format( throw new TooManyDsRecordsException(
"A maximum of %s DS records are allowed per domain.", MAX_DS_RECORDS_PER_DOMAIN)); String.format(
"A maximum of %s DS records are allowed per domain.", MAX_DS_RECORDS_PER_DOMAIN));
} }
} }
@ -264,7 +268,8 @@ public class DomainFlowUtils {
static void verifyNotInPendingDelete( static void verifyNotInPendingDelete(
Set<DesignatedContact> contacts, Set<DesignatedContact> contacts,
Key<ContactResource> registrant, Key<ContactResource> registrant,
Set<Key<HostResource>> nameservers) throws EppException { Set<Key<HostResource>> nameservers)
throws EppException {
for (DesignatedContact contact : nullToEmpty(contacts)) { for (DesignatedContact contact : nullToEmpty(contacts)) {
verifyNotInPendingDelete(contact.getContactKey()); verifyNotInPendingDelete(contact.getContactKey());
} }
@ -276,8 +281,8 @@ public class DomainFlowUtils {
} }
} }
private static void verifyNotInPendingDelete( private static void verifyNotInPendingDelete(Key<? extends EppResource> resourceKey)
Key<? extends EppResource> resourceKey) throws EppException { throws EppException {
EppResource resource = ofy().load().key(resourceKey).now(); EppResource resource = ofy().load().key(resourceKey).now();
if (resource.getStatusValues().contains(StatusValue.PENDING_DELETE)) { if (resource.getStatusValues().contains(StatusValue.PENDING_DELETE)) {
throw new LinkedResourceInPendingDeleteProhibitsOperationException(resource.getForeignKey()); throw new LinkedResourceInPendingDeleteProhibitsOperationException(resource.getForeignKey());
@ -309,8 +314,8 @@ public class DomainFlowUtils {
domainName.toString()); domainName.toString());
} }
if (count > MAX_NAMESERVERS_PER_DOMAIN) { if (count > MAX_NAMESERVERS_PER_DOMAIN) {
throw new TooManyNameserversException(String.format( throw new TooManyNameserversException(
"Only %d nameservers are allowed per domain", MAX_NAMESERVERS_PER_DOMAIN)); String.format("Only %d nameservers are allowed per domain", MAX_NAMESERVERS_PER_DOMAIN));
} }
} }
@ -326,7 +331,7 @@ public class DomainFlowUtils {
static void validateRequiredContactsPresent( static void validateRequiredContactsPresent(
Key<ContactResource> registrant, Set<DesignatedContact> contacts) Key<ContactResource> registrant, Set<DesignatedContact> contacts)
throws RequiredParameterMissingException { throws RequiredParameterMissingException {
if (registrant == null) { if (registrant == null) {
throw new MissingRegistrantException(); throw new MissingRegistrantException();
} }
@ -347,7 +352,8 @@ public class DomainFlowUtils {
throws RegistrantNotAllowedException { throws RegistrantNotAllowedException {
ImmutableSet<String> whitelist = Registry.get(tld).getAllowedRegistrantContactIds(); ImmutableSet<String> whitelist = Registry.get(tld).getAllowedRegistrantContactIds();
// Empty whitelist or null registrantContactId are ignored. // Empty whitelist or null registrantContactId are ignored.
if (registrantContactId != null && !whitelist.isEmpty() if (registrantContactId != null
&& !whitelist.isEmpty()
&& !whitelist.contains(registrantContactId)) { && !whitelist.contains(registrantContactId)) {
throw new RegistrantNotAllowedException(registrantContactId); throw new RegistrantNotAllowedException(registrantContactId);
} }
@ -418,16 +424,15 @@ public class DomainFlowUtils {
static void verifyLaunchPhaseMatchesRegistryPhase( static void verifyLaunchPhaseMatchesRegistryPhase(
Registry registry, LaunchExtension launchExtension, DateTime now) throws EppException { Registry registry, LaunchExtension launchExtension, DateTime now) throws EppException {
if (!Objects.equals( if (!Objects.equals(
registry.getTldState(now), registry.getTldState(now), LAUNCH_PHASE_TO_TLD_STATE.get(launchExtension.getPhase()))) {
LAUNCH_PHASE_TO_TLD_STATE.get(launchExtension.getPhase()))) {
// No launch operations are allowed during the quiet period or predelegation. // No launch operations are allowed during the quiet period or predelegation.
throw new LaunchPhaseMismatchException(); throw new LaunchPhaseMismatchException();
} }
} }
/** Verifies that an application's domain name matches the target id (from a command). */ /** Verifies that an application's domain name matches the target id (from a command). */
static void verifyApplicationDomainMatchesTargetId( static void verifyApplicationDomainMatchesTargetId(DomainApplication application, String targetId)
DomainApplication application, String targetId) throws EppException { throws EppException {
if (!application.getFullyQualifiedDomainName().equals(targetId)) { if (!application.getFullyQualifiedDomainName().equals(targetId)) {
throw new ApplicationDomainNameMismatchException(); throw new ApplicationDomainNameMismatchException();
} }
@ -438,8 +443,8 @@ public class DomainFlowUtils {
* where it would not be allowed is if domain name is premium, and premium names are blocked by * where it would not be allowed is if domain name is premium, and premium names are blocked by
* this registrar. * this registrar.
*/ */
static void verifyPremiumNameIsNotBlocked( static void verifyPremiumNameIsNotBlocked(String domainName, DateTime priceTime, String clientId)
String domainName, DateTime priceTime, String clientId) throws EppException { throws EppException {
if (isDomainPremium(domainName, priceTime)) { if (isDomainPremium(domainName, priceTime)) {
if (Registrar.loadByClientIdCached(clientId).get().getBlockPremiumNames()) { if (Registrar.loadByClientIdCached(clientId).get().getBlockPremiumNames()) {
throw new PremiumNameBlockedException(); throw new PremiumNameBlockedException();
@ -501,13 +506,14 @@ public class DomainFlowUtils {
// message to be deleted), and then subsequently the transfer was canceled, rejected, or deleted // message to be deleted), and then subsequently the transfer was canceled, rejected, or deleted
// (which would cause the poll message to be recreated here). // (which would cause the poll message to be recreated here).
Key<PollMessage.Autorenew> existingAutorenewKey = domain.getAutorenewPollMessage(); Key<PollMessage.Autorenew> existingAutorenewKey = domain.getAutorenewPollMessage();
PollMessage.Autorenew updatedAutorenewPollMessage = autorenewPollMessage.isPresent() PollMessage.Autorenew updatedAutorenewPollMessage =
? autorenewPollMessage.get().asBuilder().setAutorenewEndTime(newEndTime).build() autorenewPollMessage.isPresent()
: newAutorenewPollMessage(domain) ? autorenewPollMessage.get().asBuilder().setAutorenewEndTime(newEndTime).build()
.setId(existingAutorenewKey.getId()) : newAutorenewPollMessage(domain)
.setAutorenewEndTime(newEndTime) .setId(existingAutorenewKey.getId())
.setParentKey(existingAutorenewKey.getParent()) .setAutorenewEndTime(newEndTime)
.build(); .setParentKey(existingAutorenewKey.getParent())
.build();
// If the resultant autorenew poll message would have no poll messages to deliver, then just // If the resultant autorenew poll message would have no poll messages to deliver, then just
// delete it. Otherwise save it with the new end time. // delete it. Otherwise save it with the new end time.
@ -697,6 +703,49 @@ public class DomainFlowUtils {
if (!feeTotal.equals(feesAndCredits.getTotalCost())) { if (!feeTotal.equals(feesAndCredits.getTotalCost())) {
throw new FeesMismatchException(feesAndCredits.getTotalCost()); throw new FeesMismatchException(feesAndCredits.getTotalCost());
} }
// If more than one fees are required, always validate individual fees.
ImmutableMap<FeeType, Money> expectedFeeMap =
buildFeeMap(feesAndCredits.getFees(), feesAndCredits.getCurrency());
if (expectedFeeMap.size() > 1) {
ImmutableMap<FeeType, Money> providedFeeMap =
buildFeeMap(feeCommand.get().getFees(), feeCommand.get().getCurrency());
for (FeeType type : expectedFeeMap.keySet()) {
Money providedCost = providedFeeMap.get(type);
Money expectedCost = expectedFeeMap.get(type);
if (!providedCost.isEqual(expectedCost)) {
throw new FeesMismatchException(type, expectedCost);
}
}
}
}
private static FeeType getOrParseType(Fee fee) throws ParameterValuePolicyErrorException {
if (fee.getType() != null) {
return fee.getType();
}
ImmutableList<FeeType> types = fee.parseDescriptionForTypes();
if (types.size() == 0) {
throw new FeeDescriptionParseException(fee.getDescription());
} else if (types.size() > 1) {
throw new FeeDescriptionMultipleMatchesException(fee.getDescription());
} else {
return types.get(0);
}
}
private static ImmutableMap<FeeType, Money> buildFeeMap(List<Fee> fees, CurrencyUnit currency)
throws ParameterValuePolicyErrorException {
ImmutableMultimap.Builder<FeeType, Money> mapBuilder =
new ImmutableMultimap.Builder<FeeType, Money>().orderKeysBy(Comparator.naturalOrder());
for (Fee fee : fees) {
mapBuilder.put(getOrParseType(fee), Money.of(currency, fee.getCost()));
}
return mapBuilder
.build()
.asMap()
.entrySet()
.stream()
.collect(toImmutableMap(Entry::getKey, entry -> Money.total(entry.getValue())));
} }
/** /**
@ -714,8 +763,8 @@ public class DomainFlowUtils {
/** /**
* Check whether a new registration period (via a create, allocate, or application create) does * Check whether a new registration period (via a create, allocate, or application create) does
* not extend beyond a maximum number of years (e.g. * not extend beyond a maximum number of years (e.g. {@link
* {@link DomainResource#MAX_REGISTRATION_YEARS}). * DomainResource#MAX_REGISTRATION_YEARS}).
* *
* @throws ExceedsMaxRegistrationYearsException if the new registration period is too long * @throws ExceedsMaxRegistrationYearsException if the new registration period is too long
*/ */
@ -743,9 +792,9 @@ public class DomainFlowUtils {
/** Update {@link DelegationSignerData} based on an update extension command. */ /** Update {@link DelegationSignerData} based on an update extension command. */
static ImmutableSet<DelegationSignerData> updateDsData( static ImmutableSet<DelegationSignerData> updateDsData(
ImmutableSet<DelegationSignerData> oldDsData, SecDnsUpdateExtension secDnsUpdate) ImmutableSet<DelegationSignerData> oldDsData, SecDnsUpdateExtension secDnsUpdate)
throws EppException { throws EppException {
// We don't support 'urgent' because we do everything as fast as we can anyways. // We don't support 'urgent' because we do everything as fast as we can anyways.
if (Boolean.TRUE.equals(secDnsUpdate.getUrgent())) { // We allow both false and null. if (Boolean.TRUE.equals(secDnsUpdate.getUrgent())) { // We allow both false and null.
throw new UrgentAttributeNotSupportedException(); throw new UrgentAttributeNotSupportedException();
} }
// There must be at least one of add/rem/chg, and chg isn't actually supported. // There must be at least one of add/rem/chg, and chg isn't actually supported.
@ -759,14 +808,13 @@ public class DomainFlowUtils {
throw new EmptySecDnsUpdateException(); throw new EmptySecDnsUpdateException();
} }
if (remove != null && Boolean.FALSE.equals(remove.getAll())) { if (remove != null && Boolean.FALSE.equals(remove.getAll())) {
throw new SecDnsAllUsageException(); // Explicit all=false is meaningless. throw new SecDnsAllUsageException(); // Explicit all=false is meaningless.
} }
Set<DelegationSignerData> toAdd = (add == null) Set<DelegationSignerData> toAdd = (add == null) ? ImmutableSet.of() : add.getDsData();
? ImmutableSet.of() Set<DelegationSignerData> toRemove =
: add.getDsData(); (remove == null)
Set<DelegationSignerData> toRemove = (remove == null) ? ImmutableSet.of()
? ImmutableSet.of() : (remove.getAll() == null) ? remove.getDsData() : oldDsData;
: (remove.getAll() == null) ? remove.getDsData() : oldDsData;
// RFC 5910 specifies that removes are processed before adds. // RFC 5910 specifies that removes are processed before adds.
return ImmutableSet.copyOf(union(difference(oldDsData, toRemove), toAdd)); return ImmutableSet.copyOf(union(difference(oldDsData, toRemove), toAdd));
} }
@ -775,7 +823,9 @@ public class DomainFlowUtils {
static void verifyClientUpdateNotProhibited(Update command, DomainBase existingResource) static void verifyClientUpdateNotProhibited(Update command, DomainBase existingResource)
throws ResourceHasClientUpdateProhibitedException { throws ResourceHasClientUpdateProhibitedException {
if (existingResource.getStatusValues().contains(StatusValue.CLIENT_UPDATE_PROHIBITED) if (existingResource.getStatusValues().contains(StatusValue.CLIENT_UPDATE_PROHIBITED)
&& !command.getInnerRemove().getStatusValues() && !command
.getInnerRemove()
.getStatusValues()
.contains(StatusValue.CLIENT_UPDATE_PROHIBITED)) { .contains(StatusValue.CLIENT_UPDATE_PROHIBITED)) {
throw new ResourceHasClientUpdateProhibitedException(); throw new ResourceHasClientUpdateProhibitedException();
} }
@ -845,10 +895,8 @@ public class DomainFlowUtils {
/** Validate the notice from a launch create extension, allowing null as a valid notice. */ /** Validate the notice from a launch create extension, allowing null as a valid notice. */
static void validateLaunchCreateNotice( static void validateLaunchCreateNotice(
@Nullable LaunchNotice notice, @Nullable LaunchNotice notice, String domainLabel, boolean isSuperuser, DateTime now)
String domainLabel, throws EppException {
boolean isSuperuser,
DateTime now) throws EppException {
if (notice == null) { if (notice == null) {
return; return;
} }
@ -887,9 +935,8 @@ public class DomainFlowUtils {
* not on the claims list and is a sunrise application. * not on the claims list and is a sunrise application.
*/ */
static void verifyClaimsNoticeIfAndOnlyIfNeeded( static void verifyClaimsNoticeIfAndOnlyIfNeeded(
InternetDomainName domainName, InternetDomainName domainName, boolean hasSignedMarks, boolean hasClaimsNotice)
boolean hasSignedMarks, throws EppException {
boolean hasClaimsNotice) throws EppException {
boolean isInClaimsList = ClaimsListShard.get().getClaimKey(domainName.parts().get(0)) != null; boolean isInClaimsList = ClaimsListShard.get().getClaimKey(domainName.parts().get(0)) != null;
if (hasClaimsNotice && !isInClaimsList) { if (hasClaimsNotice && !isInClaimsList) {
throw new UnexpectedClaimsNoticeException(domainName.toString()); throw new UnexpectedClaimsNoticeException(domainName.toString());
@ -902,14 +949,12 @@ public class DomainFlowUtils {
/** Create a {@link LrpTokenEntity} object that records this LRP registration. */ /** Create a {@link LrpTokenEntity} object that records this LRP registration. */
static LrpTokenEntity prepareMarkedLrpTokenEntity( static LrpTokenEntity prepareMarkedLrpTokenEntity(
String lrpTokenString, InternetDomainName domainName, HistoryEntry historyEntry) String lrpTokenString, InternetDomainName domainName, HistoryEntry historyEntry)
throws InvalidLrpTokenException { throws InvalidLrpTokenException {
Optional<LrpTokenEntity> lrpToken = getMatchingLrpToken(lrpTokenString, domainName); Optional<LrpTokenEntity> lrpToken = getMatchingLrpToken(lrpTokenString, domainName);
if (!lrpToken.isPresent()) { if (!lrpToken.isPresent()) {
throw new InvalidLrpTokenException(); throw new InvalidLrpTokenException();
} }
return lrpToken.get().asBuilder() return lrpToken.get().asBuilder().setRedemptionHistoryEntry(Key.create(historyEntry)).build();
.setRedemptionHistoryEntry(Key.create(historyEntry))
.build();
} }
/** Check that there are no code marks, which is a type of mark we don't support. */ /** Check that there are no code marks, which is a type of mark we don't support. */
@ -935,9 +980,9 @@ public class DomainFlowUtils {
ImmutableSet<DesignatedContact> contacts) { ImmutableSet<DesignatedContact> contacts) {
ImmutableSet.Builder<ForeignKeyedDesignatedContact> builder = new ImmutableSet.Builder<>(); ImmutableSet.Builder<ForeignKeyedDesignatedContact> builder = new ImmutableSet.Builder<>();
for (DesignatedContact contact : contacts) { for (DesignatedContact contact : contacts) {
builder.add(ForeignKeyedDesignatedContact.create( builder.add(
contact.getType(), ForeignKeyedDesignatedContact.create(
ofy().load().key(contact.getContactKey()).now().getContactId())); contact.getType(), ofy().load().key(contact.getContactKey()).now().getContactId()));
} }
return builder.build(); return builder.build();
} }
@ -960,12 +1005,14 @@ public class DomainFlowUtils {
Duration maxSearchPeriod, Duration maxSearchPeriod,
final ImmutableSet<TransactionReportField> cancelableFields) { final ImmutableSet<TransactionReportField> cancelableFields) {
List<HistoryEntry> recentHistoryEntries = ofy().load() List<HistoryEntry> recentHistoryEntries =
.type(HistoryEntry.class) ofy()
.ancestor(domainResource) .load()
.filter("modificationTime >=", now.minus(maxSearchPeriod)) .type(HistoryEntry.class)
.order("modificationTime") .ancestor(domainResource)
.list(); .filter("modificationTime >=", now.minus(maxSearchPeriod))
.order("modificationTime")
.list();
Optional<HistoryEntry> entryToCancel = Optional<HistoryEntry> entryToCancel =
Streams.findLast( Streams.findLast(
recentHistoryEntries recentHistoryEntries
@ -1006,9 +1053,7 @@ public class DomainFlowUtils {
static class LinkedResourceInPendingDeleteProhibitsOperationException static class LinkedResourceInPendingDeleteProhibitsOperationException
extends StatusProhibitsOperationException { extends StatusProhibitsOperationException {
public LinkedResourceInPendingDeleteProhibitsOperationException(String resourceId) { public LinkedResourceInPendingDeleteProhibitsOperationException(String resourceId) {
super(String.format( super(String.format("Linked resource in pending delete prohibits operation: %s", resourceId));
"Linked resource in pending delete prohibits operation: %s",
resourceId));
} }
} }
@ -1190,8 +1235,9 @@ public class DomainFlowUtils {
/** Fees must be explicitly acknowledged when performing any operations on a premium name. */ /** Fees must be explicitly acknowledged when performing any operations on a premium name. */
static class FeesRequiredForPremiumNameException extends RequiredParameterMissingException { static class FeesRequiredForPremiumNameException extends RequiredParameterMissingException {
FeesRequiredForPremiumNameException() { FeesRequiredForPremiumNameException() {
super("Fees must be explicitly acknowledged when performing any operations on a premium" super(
+ " name"); "Fees must be explicitly acknowledged when performing any operations on a premium"
+ " name");
} }
} }
@ -1221,8 +1267,9 @@ public class DomainFlowUtils {
/** The 'grace-period', 'applied' and 'refundable' fields are disallowed by server policy. */ /** The 'grace-period', 'applied' and 'refundable' fields are disallowed by server policy. */
static class UnsupportedFeeAttributeException extends UnimplementedOptionException { static class UnsupportedFeeAttributeException extends UnimplementedOptionException {
UnsupportedFeeAttributeException() { UnsupportedFeeAttributeException() {
super("The 'grace-period', 'refundable' and 'applied' attributes are disallowed by server " super(
+ "policy"); "The 'grace-period', 'refundable' and 'applied' attributes are disallowed by server "
+ "policy");
} }
} }
@ -1268,8 +1315,9 @@ public class DomainFlowUtils {
*/ */
static class PremiumNameBlockedException extends StatusProhibitsOperationException { static class PremiumNameBlockedException extends StatusProhibitsOperationException {
public PremiumNameBlockedException() { public PremiumNameBlockedException() {
super("The requested domain name is on the premium price list, " super(
+ "and this registrar has blocked premium registrations"); "The requested domain name is on the premium price list, "
+ "and this registrar has blocked premium registrations");
} }
} }
@ -1280,9 +1328,39 @@ public class DomainFlowUtils {
} }
public FeesMismatchException(Money correctFee) { public FeesMismatchException(Money correctFee) {
super(String.format( super(
"The fees passed in the transform command do not match the expected total of %s", String.format(
correctFee)); "The fees passed in the transform command do not match the expected total of %s",
correctFee));
}
public FeesMismatchException(FeeType type, Money correctFee) {
super(
String.format(
"The fees passed in the transform command for type \"%s\" do not match the expected "
+ "fee of %s",
type, correctFee));
}
}
/** The fee description passed in the transform command cannot be parsed. */
public static class FeeDescriptionParseException extends ParameterValuePolicyErrorException {
public FeeDescriptionParseException(String description) {
super(
String.format(
"The fee description \"%s\" passed in the transform command cannot be parsed",
description == null ? "" : description));
}
}
/** The fee description passed in the transform command matches multiple fee types. */
public static class FeeDescriptionMultipleMatchesException
extends ParameterValuePolicyErrorException {
public FeeDescriptionMultipleMatchesException(String description) {
super(
String.format(
"The fee description \"%s\" passed in the transform matches multiple fee types",
description));
} }
} }
@ -1304,9 +1382,10 @@ public class DomainFlowUtils {
public static class NameserversNotAllowedForTldException public static class NameserversNotAllowedForTldException
extends StatusProhibitsOperationException { extends StatusProhibitsOperationException {
public NameserversNotAllowedForTldException(Set<String> fullyQualifiedHostNames) { public NameserversNotAllowedForTldException(Set<String> fullyQualifiedHostNames) {
super(String.format( super(
"Nameservers '%s' are not whitelisted for this TLD", String.format(
Joiner.on(',').join(fullyQualifiedHostNames))); "Nameservers '%s' are not whitelisted for this TLD",
Joiner.on(',').join(fullyQualifiedHostNames)));
} }
} }
@ -1451,8 +1530,7 @@ public class DomainFlowUtils {
} }
/** Invalid limited registration period token. */ /** Invalid limited registration period token. */
static class InvalidLrpTokenException static class InvalidLrpTokenException extends InvalidAuthorizationInformationErrorException {
extends InvalidAuthorizationInformationErrorException {
public InvalidLrpTokenException() { public InvalidLrpTokenException() {
super("Invalid limited registration period token"); super("Invalid limited registration period token");
} }
@ -1468,9 +1546,10 @@ public class DomainFlowUtils {
/** New registration period exceeds maximum number of years. */ /** New registration period exceeds maximum number of years. */
static class ExceedsMaxRegistrationYearsException extends ParameterValueRangeErrorException { static class ExceedsMaxRegistrationYearsException extends ParameterValueRangeErrorException {
public ExceedsMaxRegistrationYearsException() { public ExceedsMaxRegistrationYearsException() {
super(String.format( super(
"New registration period exceeds maximum number of years (%d)", String.format(
MAX_REGISTRATION_YEARS)); "New registration period exceeds maximum number of years (%d)",
MAX_REGISTRATION_YEARS));
} }
} }
@ -1480,5 +1559,4 @@ public class DomainFlowUtils {
super("Registrar must be active in order to create domains or applications"); super("Registrar must be active in order to create domains or applications");
} }
} }
} }

View file

@ -16,11 +16,15 @@ package google.registry.model.domain.fee;
import static com.google.common.base.MoreObjects.firstNonNull; import static com.google.common.base.MoreObjects.firstNonNull;
import static com.google.common.base.Preconditions.checkState; import static com.google.common.base.Preconditions.checkState;
import static com.google.common.collect.ImmutableList.toImmutableList;
import com.google.common.base.Ascii;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Range; import com.google.common.collect.Range;
import google.registry.model.ImmutableObject; import google.registry.model.ImmutableObject;
import google.registry.xml.PeriodAdapter; import google.registry.xml.PeriodAdapter;
import java.math.BigDecimal; import java.math.BigDecimal;
import java.util.stream.Stream;
import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlEnumValue; import javax.xml.bind.annotation.XmlEnumValue;
import javax.xml.bind.annotation.XmlTransient; import javax.xml.bind.annotation.XmlTransient;
@ -68,29 +72,27 @@ public abstract class BaseFee extends ImmutableObject {
String renderDescription(Object... args) { String renderDescription(Object... args) {
return String.format(formatString, args); return String.format(formatString, args);
} }
boolean matchFormatString(String description) {
return Ascii.toLowerCase(formatString).contains(Ascii.toLowerCase(description));
}
} }
@XmlAttribute @XmlAttribute String description;
String description;
@XmlAttribute @XmlAttribute AppliedType applied;
AppliedType applied;
@XmlAttribute(name = "grace-period") @XmlAttribute(name = "grace-period")
@XmlJavaTypeAdapter(PeriodAdapter.class) @XmlJavaTypeAdapter(PeriodAdapter.class)
Period gracePeriod; Period gracePeriod;
@XmlAttribute @XmlAttribute Boolean refundable;
Boolean refundable;
@XmlValue @XmlValue BigDecimal cost;
BigDecimal cost;
@XmlTransient @XmlTransient FeeType type;
FeeType type;
@XmlTransient @XmlTransient Range<DateTime> validDateRange;
Range<DateTime> validDateRange;
public String getDescription() { public String getDescription() {
return description; return description;
@ -113,8 +115,8 @@ public abstract class BaseFee extends ImmutableObject {
* must always be negative. Essentially, they are the same thing, just with different sign. * must always be negative. Essentially, they are the same thing, just with different sign.
* However, we need them to be separate classes for proper JAXB handling. * However, we need them to be separate classes for proper JAXB handling.
* *
* @see <a href="https://tools.ietf.org/html/draft-brown-epp-fees-03#section-2.4"> * @see <a href="https://tools.ietf.org/html/draft-brown-epp-fees-03#section-2.4">Registry Fee
* Registry Fee Extension for EPP - Fees and Credits</a> * Extension for EPP - Fees and Credits</a>
*/ */
public BigDecimal getCost() { public BigDecimal getCost() {
return cost; return cost;
@ -142,4 +144,19 @@ public abstract class BaseFee extends ImmutableObject {
&& getApplied().equals(AppliedType.IMMEDIATE) && getApplied().equals(AppliedType.IMMEDIATE)
&& getRefundable(); && getRefundable();
} }
/**
* Parses the description field and returns {@link FeeType}s that match the description.
*
* <p>A {@link FeeType} is a match when its {@code formatString} contains the description, case
* insensitively.
*/
public ImmutableList<FeeType> parseDescriptionForTypes() {
if (description == null) {
return ImmutableList.of();
}
return Stream.of(FeeType.values())
.filter(feeType -> feeType.matchFormatString(description))
.collect(toImmutableList());
}
} }

View file

@ -84,6 +84,8 @@ import google.registry.flows.domain.DomainFlowUtils.DuplicateContactForRoleExcep
import google.registry.flows.domain.DomainFlowUtils.EmptyDomainNamePartException; import google.registry.flows.domain.DomainFlowUtils.EmptyDomainNamePartException;
import google.registry.flows.domain.DomainFlowUtils.ExceedsMaxRegistrationYearsException; import google.registry.flows.domain.DomainFlowUtils.ExceedsMaxRegistrationYearsException;
import google.registry.flows.domain.DomainFlowUtils.ExpiredClaimException; import google.registry.flows.domain.DomainFlowUtils.ExpiredClaimException;
import google.registry.flows.domain.DomainFlowUtils.FeeDescriptionMultipleMatchesException;
import google.registry.flows.domain.DomainFlowUtils.FeeDescriptionParseException;
import google.registry.flows.domain.DomainFlowUtils.FeesMismatchException; import google.registry.flows.domain.DomainFlowUtils.FeesMismatchException;
import google.registry.flows.domain.DomainFlowUtils.FeesRequiredDuringEarlyAccessProgramException; import google.registry.flows.domain.DomainFlowUtils.FeesRequiredDuringEarlyAccessProgramException;
import google.registry.flows.domain.DomainFlowUtils.FeesRequiredForPremiumNameException; import google.registry.flows.domain.DomainFlowUtils.FeesRequiredForPremiumNameException;
@ -1774,8 +1776,7 @@ public class DomainCreateFlowTest extends ResourceFlowTestCase<DomainCreateFlow,
clock.setTo(DateTime.parse("2014-09-09T09:09:09Z")); clock.setTo(DateTime.parse("2014-09-09T09:09:09Z"));
setEppInput("domain_create_registration_start_date_sunrise_wrong_encoded_signed_mark.xml"); setEppInput("domain_create_registration_start_date_sunrise_wrong_encoded_signed_mark.xml");
persistContactsAndHosts(); persistContactsAndHosts();
EppException thrown = EppException thrown = expectThrows(NoMarksFoundMatchingDomainException.class, this::runFlow);
expectThrows(NoMarksFoundMatchingDomainException.class, this::runFlow);
assertAboutEppExceptions().that(thrown).marshalsToXml(); assertAboutEppExceptions().that(thrown).marshalsToXml();
} }
@ -2153,9 +2154,90 @@ public class DomainCreateFlowTest extends ResourceFlowTestCase<DomainCreateFlow,
assertThat(reloadResourceByForeignKey().getStatusValues()).containsExactly(OK); assertThat(reloadResourceByForeignKey().getStatusValues()).containsExactly(OK);
} }
@Test
public void testFailure_eapFee_combined() throws Exception {
setEppInput("domain_create_eap_combined_fee.xml", ImmutableMap.of("FEE_VERSION", "0.6"));
persistContactsAndHosts();
persistResource(
Registry.get("tld")
.asBuilder()
.setEapFeeSchedule(
ImmutableSortedMap.of(
START_OF_TIME,
Money.of(USD, 0),
clock.nowUtc().minusDays(1),
Money.of(USD, 100),
clock.nowUtc().plusDays(1),
Money.of(USD, 0)))
.build());
EppException thrown = expectThrows(FeeDescriptionParseException.class, this::runFlow);
assertAboutEppExceptions().that(thrown).marshalsToXml();
}
@Test
public void testFailure_eapFee_description_swapped() throws Exception {
setEppInput(
"domain_create_eap_fee.xml",
ImmutableMap.of(
"FEE_VERSION",
"0.6",
"DESCRIPTION_1",
"Early Access Period",
"DESCRIPTION_2",
"create"));
persistContactsAndHosts();
persistResource(
Registry.get("tld")
.asBuilder()
.setEapFeeSchedule(
ImmutableSortedMap.of(
START_OF_TIME,
Money.of(USD, 0),
clock.nowUtc().minusDays(1),
Money.of(USD, 100),
clock.nowUtc().plusDays(1),
Money.of(USD, 0)))
.build());
EppException thrown = expectThrows(FeesMismatchException.class, this::runFlow);
assertThat(thrown).hasMessageThat().contains("CREATE");
assertAboutEppExceptions().that(thrown).marshalsToXml();
}
@Test
public void testFailure_eapFee_description_multipleMatch() throws Exception {
setEppInput(
"domain_create_eap_fee.xml",
ImmutableMap.of(
"FEE_VERSION", "0.6", "DESCRIPTION_1", "Early Access Period", "DESCRIPTION_2", "ea"));
persistContactsAndHosts();
persistResource(
Registry.get("tld")
.asBuilder()
.setEapFeeSchedule(
ImmutableSortedMap.of(
START_OF_TIME,
Money.of(USD, 0),
clock.nowUtc().minusDays(1),
Money.of(USD, 100),
clock.nowUtc().plusDays(1),
Money.of(USD, 0)))
.build());
EppException thrown = expectThrows(FeeDescriptionMultipleMatchesException.class, this::runFlow);
assertThat(thrown).hasMessageThat().contains("ea");
assertAboutEppExceptions().that(thrown).marshalsToXml();
}
@Test @Test
public void testSuccess_eapFeeApplied_v06() throws Exception { public void testSuccess_eapFeeApplied_v06() throws Exception {
setEppInput("domain_create_eap_fee.xml", ImmutableMap.of("FEE_VERSION", "0.6")); setEppInput(
"domain_create_eap_fee.xml",
ImmutableMap.of(
"FEE_VERSION",
"0.6",
"DESCRIPTION_1",
"create",
"DESCRIPTION_2",
"Early Access Period"));
persistContactsAndHosts(); persistContactsAndHosts();
persistResource( persistResource(
Registry.get("tld") Registry.get("tld")
@ -2175,7 +2257,15 @@ public class DomainCreateFlowTest extends ResourceFlowTestCase<DomainCreateFlow,
@Test @Test
public void testSuccess_eapFeeApplied_v11() throws Exception { public void testSuccess_eapFeeApplied_v11() throws Exception {
setEppInput("domain_create_eap_fee.xml", ImmutableMap.of("FEE_VERSION", "0.11")); setEppInput(
"domain_create_eap_fee.xml",
ImmutableMap.of(
"FEE_VERSION",
"0.11",
"DESCRIPTION_1",
"create",
"DESCRIPTION_2",
"Early Access Period"));
persistContactsAndHosts(); persistContactsAndHosts();
persistResource( persistResource(
Registry.get("tld") Registry.get("tld")
@ -2195,7 +2285,15 @@ public class DomainCreateFlowTest extends ResourceFlowTestCase<DomainCreateFlow,
@Test @Test
public void testSuccess_eapFeeApplied_v12() throws Exception { public void testSuccess_eapFeeApplied_v12() throws Exception {
setEppInput("domain_create_eap_fee.xml", ImmutableMap.of("FEE_VERSION", "0.12")); setEppInput(
"domain_create_eap_fee.xml",
ImmutableMap.of(
"FEE_VERSION",
"0.12",
"DESCRIPTION_1",
"create",
"DESCRIPTION_2",
"Early Access Period"));
persistContactsAndHosts(); persistContactsAndHosts();
persistResource( persistResource(
Registry.get("tld") Registry.get("tld")

View file

@ -935,7 +935,7 @@ public class DomainTransferRequestFlowTest
setupDomain("expensive-domain", "foo"); setupDomain("expensive-domain", "foo");
clock.advanceOneMilli(); clock.advanceOneMilli();
doSuccessfulTest( doSuccessfulTest(
"domain_transfer_request_fee.xml", "domain_transfer_request_separate_fees.xml",
"domain_transfer_request_response_fees.xml", "domain_transfer_request_response_fees.xml",
domain.getRegistrationExpirationTime().plusYears(1), domain.getRegistrationExpirationTime().plusYears(1),
new ImmutableMap.Builder<String, String>() new ImmutableMap.Builder<String, String>()

View file

@ -0,0 +1,23 @@
<epp xmlns="urn:ietf:params:xml:ns:epp-1.0">
<command>
<create>
<domain:create xmlns:domain="urn:ietf:params:xml:ns:domain-1.0">
<domain:name>example.tld</domain:name>
<domain:period unit="y">2</domain:period>
<domain:registrant>jd1234</domain:registrant>
<domain:contact type="admin">sh8013</domain:contact>
<domain:contact type="tech">sh8013</domain:contact>
<domain:authInfo>
<domain:pw>2fooBAR</domain:pw>
</domain:authInfo>
</domain:create>
</create>
<extension>
<fee:create xmlns:fee="urn:ietf:params:xml:ns:fee-0.6">
<fee:currency>USD</fee:currency>
<fee:fee>126.00</fee:fee>
</fee:create>
</extension>
<clTRID>ABC-12345</clTRID>
</command>
</epp>

View file

@ -20,8 +20,8 @@
<extension> <extension>
<fee:create xmlns:fee="urn:ietf:params:xml:ns:fee-%FEE_VERSION%"> <fee:create xmlns:fee="urn:ietf:params:xml:ns:fee-%FEE_VERSION%">
<fee:currency>USD</fee:currency> <fee:currency>USD</fee:currency>
<fee:fee>26.00</fee:fee> <fee:fee description="%DESCRIPTION_1%">26.00</fee:fee>
<fee:fee description="Early Access Period">100.00</fee:fee> <fee:fee description="%DESCRIPTION_2%">100.00</fee:fee>
</fee:create> </fee:create>
</extension> </extension>
<clTRID>ABC-12345</clTRID> <clTRID>ABC-12345</clTRID>

View file

@ -20,7 +20,7 @@
<extension> <extension>
<fee:create xmlns:fee="urn:ietf:params:xml:ns:fee-0.6"> <fee:create xmlns:fee="urn:ietf:params:xml:ns:fee-0.6">
<fee:currency>USD</fee:currency> <fee:currency>USD</fee:currency>
<fee:fee>200.00</fee:fee> <fee:fee description="create">200.00</fee:fee>
<fee:fee description="Early Access Period">100.00</fee:fee> <fee:fee description="Early Access Period">100.00</fee:fee>
</fee:create> </fee:create>
</extension> </extension>

View file

@ -0,0 +1,22 @@
<epp xmlns="urn:ietf:params:xml:ns:epp-1.0">
<command>
<transfer op="request">
<domain:transfer
xmlns:domain="urn:ietf:params:xml:ns:domain-1.0">
<domain:name>%DOMAIN%</domain:name>
<domain:period unit="y">%YEARS%</domain:period>
<domain:authInfo>
<domain:pw roid="JD1234-REP">2fooBAR</domain:pw>
</domain:authInfo>
</domain:transfer>
</transfer>
<extension>
<fee:transfer xmlns:fee="urn:ietf:params:xml:ns:fee-%FEE_VERSION%">
<fee:currency>USD</fee:currency>
<fee:fee description="renew">11.00</fee:fee>
<fee:fee description="transfer">100.00</fee:fee>
</fee:transfer>
</extension>
<clTRID>ABC-12345</clTRID>
</command>
</epp>

View file

@ -13,7 +13,8 @@
</rgp:update> </rgp:update>
<fee:update xmlns:fee="urn:ietf:params:xml:ns:fee-%FEE_VERSION%"> <fee:update xmlns:fee="urn:ietf:params:xml:ns:fee-%FEE_VERSION%">
<fee:currency>USD</fee:currency> <fee:currency>USD</fee:currency>
<fee:fee>28.00</fee:fee> <fee:fee description="restore">17.00</fee:fee>
<fee:fee description="renew">11.00</fee:fee>
</fee:update> </fee:update>
</extension> </extension>
<clTRID>ABC-12345</clTRID> <clTRID>ABC-12345</clTRID>

View file

@ -2,7 +2,7 @@
<command> <command>
<update> <update>
<domain:update <domain:update
xmlns:domain="urn:ietf:params:xml:ns:domain-1.0"> xmlns:domain="urn:ietf:params:xml:ns:domain-1.0">
<domain:name>example.tld</domain:name> <domain:name>example.tld</domain:name>
<domain:chg/> <domain:chg/>
</domain:update> </domain:update>
@ -13,7 +13,12 @@
</rgp:update> </rgp:update>
<fee:update xmlns:fee="urn:ietf:params:xml:ns:fee-%FEE_VERSION%"> <fee:update xmlns:fee="urn:ietf:params:xml:ns:fee-%FEE_VERSION%">
<fee:currency>USD</fee:currency> <fee:currency>USD</fee:currency>
<fee:fee refundable="true" grace-period="P0D" applied="immediate">28.00</fee:fee> <fee:fee description="renew" refundable="true" grace-period="P0D" applied="immediate">
11.00
</fee:fee>
<fee:fee description="restore" refundable="true" grace-period="P0D" applied="immediate">
17.00
</fee:fee>
</fee:update> </fee:update>
</extension> </extension>
<clTRID>ABC-12345</clTRID> <clTRID>ABC-12345</clTRID>

View file

@ -15,7 +15,7 @@
<extension> <extension>
<fee:create xmlns:fee="urn:ietf:params:xml:ns:fee-0.6"> <fee:create xmlns:fee="urn:ietf:params:xml:ns:fee-0.6">
<fee:currency>USD</fee:currency> <fee:currency>USD</fee:currency>
<fee:fee>26.00</fee:fee> <fee:fee description="create">26.00</fee:fee>
<fee:fee description="Early Access Period">100.00</fee:fee> <fee:fee description="Early Access Period">100.00</fee:fee>
</fee:create> </fee:create>
</extension> </extension>