From 9f1bf5af88b459779cb53fe69996721fa147c438 Mon Sep 17 00:00:00 2001 From: Ben McIlwain Date: Fri, 27 Nov 2026 12:19:42 -0500 Subject: [PATCH] Enforce explicit TimedTransitionProperty FSMs TLD launch phases and allocation token promotion lifecycles previously relied on ad-hoc ordering checks and unvalidated deserialization paths that permitted illegal state regressions, bypassed promo-token checks during YAML sync, resurrected terminal tokens, and suffered a TOCTOU race when ending bulk-pricing packages. This change replaces implicit enum-ordinal ordering with explicit transition graphs enforced across builders, YAML sync, CLI updates, and a bytecode CI guardrail. Key changes: - Tld, EntityYamlUtils & ConfigureTldCommand: - Replace Ordering.natural() on Tld.tldStateTransitions with an explicit VALID_TLD_STATE_TRANSITIONS graph and non-QUIET_PERIOD progression check (forbidding regressions such as GENERAL_AVAILABILITY -> PDT, both directly and via QUIET_PERIOD). - Route EntityYamlUtils.TimedTransitionPropertyTldStateDeserializer and Tld.Builder.setTldStateTransitions through Tld.createTldStateTransitions, and re-validate in Tld.validateState. - Extract Tld.validateDefaultPromoTokens (using batched DB loads and honoring empty allowedTlds as all-TLD tokens) and invoke it from both Tld.Builder.setDefaultPromoTokens and ConfigureTldCommand so YAML sync cannot persist missing, wrong-type, or wrong-TLD promo tokens. - TimedTransitionProperty: - Remove the unused forEmptyMap() method, which unconditionally threw IllegalArgumentException. - Add a 3-argument make() overload enforcing allowed transitions without constraining the initial state, and reject empty maps with IllegalArgumentException instead of NoSuchElementException. - AllocationToken, GenerateAllocationTokensCommand & UpdateAllocationTokensCommand: - Fix BULK_PRICING renewalPrice zero check to use Money.isZero() instead of getAmount().intValue() == 0, which truncated $0.99 to 0. - Add null-checked AllocationToken.isTerminalStatus (reused in both UpdateAllocationTokensCommand and GenerateAllocationTokensCommand). - Reject tokenStatusTransitions updates that resurrect terminal tokens (ENDED or CANCELLED), regress a live status backward (e.g., VALID -> NOT_STARTED), or shrink UNLIMITED_USE/DEFAULT_PROMO transitions to a single NOT_STARTED entry. - Store only token VKeys between init() and execute(), reload, re-validate, and skip already-identical tokens inside each saveBatch() transaction to close TOCTOU windows, and print updated batch token names only after transaction commit. - CI Guardrail & Tests: - Add TimedTransitionPropertyUsageTest using ClassGraph and JDK ClassFile inspection (covering both InvokeInstruction and InvokeDynamicInstruction method references) to enforce an explicit method-level allowlist of stateless production callers of raw TimedTransitionProperty.fromValueMap(). - Add regression tests covering every fix, validateState(), and edge case. Operational justification & blast radius: - Zero database schema or Flyway migrations; zero Protostuff entity field changes; TimedTransitionProperty does not implement Map. - Scoped to TLD configuration sync (configure_tld), allocation token generation/updates, and model validation. BUG= http://b/591075479 --- .../registry/model/EntityYamlUtils.java | 3 +- .../model/common/TimedTransitionProperty.java | 28 +- .../model/domain/token/AllocationToken.java | 15 +- .../java/google/registry/model/tld/Tld.java | 147 ++++++--- .../registry/tools/ConfigureTldCommand.java | 5 + .../GenerateAllocationTokensCommand.java | 3 +- .../tools/UpdateAllocationTokensCommand.java | 123 +++++--- .../common/TimedTransitionPropertyTest.java | 55 ++++ .../TimedTransitionPropertyUsageTest.java | 180 +++++++++++ .../domain/token/AllocationTokenTest.java | 27 ++ .../google/registry/model/tld/TldTest.java | 281 +++++++++++++++-- .../tools/ConfigureTldCommandTest.java | 159 ++++++++++ .../UpdateAllocationTokensCommandTest.java | 287 ++++++++++++++++++ 13 files changed, 1203 insertions(+), 110 deletions(-) create mode 100644 core/src/test/java/google/registry/model/common/TimedTransitionPropertyUsageTest.java diff --git a/core/src/main/java/google/registry/model/EntityYamlUtils.java b/core/src/main/java/google/registry/model/EntityYamlUtils.java index c84a874268b..b3917ad364d 100644 --- a/core/src/main/java/google/registry/model/EntityYamlUtils.java +++ b/core/src/main/java/google/registry/model/EntityYamlUtils.java @@ -39,6 +39,7 @@ import google.registry.model.common.FeatureFlag.FeatureStatus; import google.registry.model.common.TimedTransitionProperty; import google.registry.model.domain.token.AllocationToken; +import google.registry.model.tld.Tld; import google.registry.model.tld.Tld.ExpiryAccessPeriodMode; import google.registry.model.tld.Tld.TldState; import google.registry.persistence.VKey; @@ -340,7 +341,7 @@ public TimedTransitionProperty deserialize( JsonParser jp, DeserializationContext context) throws IOException { SortedMap valueMap = jp.readValueAs(new TypeReference>() {}); - return TimedTransitionProperty.fromValueMap( + return Tld.createTldStateTransitions( valueMap.keySet().stream() .collect( toImmutableSortedMap( diff --git a/core/src/main/java/google/registry/model/common/TimedTransitionProperty.java b/core/src/main/java/google/registry/model/common/TimedTransitionProperty.java index 21a3e7cebbf..30eef9bc072 100644 --- a/core/src/main/java/google/registry/model/common/TimedTransitionProperty.java +++ b/core/src/main/java/google/registry/model/common/TimedTransitionProperty.java @@ -73,11 +73,6 @@ private TimedTransitionProperty(ImmutableSortedMap backingMap) { this.backingMap = ImmutableSortedMap.copyOfSorted(backingMap); } - /** Returns an empty {@link TimedTransitionProperty}. */ - public static TimedTransitionProperty forEmptyMap() { - return new TimedTransitionProperty<>(ImmutableSortedMap.of()); - } - /** * Returns a {@link TimedTransitionProperty} that starts with the given value at {@code * START_INSTANT}. @@ -99,10 +94,23 @@ public static TimedTransitionProperty fromValueMap( /** * Returns a {@link TimedTransitionProperty} that contains the transition values and times defined - * in the given map. + * in the given map, validated against a set of allowed transitions. + * + *

The map must start at {@code START_INSTANT}. + */ + public static TimedTransitionProperty make( + ImmutableSortedMap valueMap, + ImmutableMultimap allowedTransitions, + String mapName) { + validateTimedTransitionMap(valueMap, allowedTransitions, mapName); + return fromValueMap(valueMap); + } + + /** + * Returns a {@link TimedTransitionProperty} that contains the transition values and times defined + * in the given map, validated against a set of allowed transitions and a required initial value. * - *

The map must contain a value for {@code START_INSTANT}. The map is also validated against a - * set of allowed transitions. + *

The map must start at {@code START_INSTANT} with {@code initialValue}. */ public static TimedTransitionProperty make( ImmutableSortedMap valueMap, @@ -124,7 +132,9 @@ public static void validateTimedTransitionMap( Ordering.natural().equals(valueMap.comparator()), "Timed transition value map must have transition time keys in chronological order"); checkArgument( - valueMap.firstKey().equals(START_INSTANT), "%s map must start at START_INSTANT.", mapName); + !valueMap.isEmpty() && valueMap.firstKey().equals(START_INSTANT), + "%s map must start at START_INSTANT.", + mapName); V lastValue = null; for (V value : valueMap.values()) { diff --git a/core/src/main/java/google/registry/model/domain/token/AllocationToken.java b/core/src/main/java/google/registry/model/domain/token/AllocationToken.java index bdb6ee803a6..f500254c6b1 100644 --- a/core/src/main/java/google/registry/model/domain/token/AllocationToken.java +++ b/core/src/main/java/google/registry/model/domain/token/AllocationToken.java @@ -89,13 +89,22 @@ public class AllocationToken extends UpdateAutoTimestampEntity implements Builda private static final ImmutableMap STATIC_TOKEN_BEHAVIORS = ImmutableMap.of(REMOVE_BULK_PRICING, TokenBehavior.REMOVE_BULK_PRICING); - // Promotions should only move forward, and ENDED / CANCELLED are terminal states. - private static final ImmutableMultimap VALID_TOKEN_STATUS_TRANSITIONS = + /** + * Valid transitions between {@link TokenStatus} values. Promotions should only move forward, and + * {@link TokenStatus#ENDED} and {@link TokenStatus#CANCELLED} are terminal states. + */ + public static final ImmutableMultimap VALID_TOKEN_STATUS_TRANSITIONS = ImmutableMultimap.builder() .putAll(NOT_STARTED, VALID, CANCELLED) .putAll(VALID, ENDED, CANCELLED) .build(); + /** Returns true if {@code status} is a terminal status with no valid outgoing transitions. */ + public static boolean isTerminalStatus(TokenStatus status) { + checkArgumentNotNull(status, "TokenStatus cannot be null"); + return VALID_TOKEN_STATUS_TRANSITIONS.get(status).isEmpty(); + } + private static final ImmutableMap BEHAVIORAL_TOKENS = ImmutableMap.of( REMOVE_BULK_PRICING, @@ -491,7 +500,7 @@ public AllocationToken build() { getInstance().renewalPriceBehavior.equals(RenewalPriceBehavior.SPECIFIED), "BULK_PRICING tokens must have renewalPriceBehavior set to SPECIFIED"); checkArgument( - getInstance().renewalPrice.getAmount().intValue() == 0, + getInstance().renewalPrice.isZero(), "BULK_PRICING tokens must have a renewal price of 0"); checkArgument( ImmutableSet.of(CommandName.CREATE).equals(getInstance().allowedEppActions), diff --git a/core/src/main/java/google/registry/model/tld/Tld.java b/core/src/main/java/google/registry/model/tld/Tld.java index 46e9430dc95..af87c511fbf 100644 --- a/core/src/main/java/google/registry/model/tld/Tld.java +++ b/core/src/main/java/google/registry/model/tld/Tld.java @@ -40,10 +40,10 @@ import com.google.common.base.Joiner; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; +import com.google.common.collect.ImmutableMultimap; import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSortedMap; import com.google.common.collect.Maps; -import com.google.common.collect.Ordering; import com.google.common.collect.Range; import com.google.common.net.InternetDomainName; import google.registry.model.Buildable; @@ -96,7 +96,6 @@ import java.util.Set; import java.util.function.Predicate; import java.util.regex.Pattern; -import java.util.stream.Collectors; import javax.annotation.Nullable; import org.hibernate.annotations.Type; import org.joda.money.CurrencyUnit; @@ -170,8 +169,8 @@ public enum TldType { } /** - * The states a TLD can be in at any given point in time. The ordering below is the required - * sequence of states (ignoring {@link #PDT} which is a pseudo-state). + * The states a TLD can be in at any given point in time. Valid state transitions are enforced by + * {@link #VALID_TLD_STATE_TRANSITIONS}. */ public enum TldState { @@ -186,8 +185,9 @@ public enum TldState { /** * A state in which no domain operations are permitted. Generally used between sunrise and - * general availability. This state is special in that it has no ordering constraints and can - * appear after any phase. + * general availability. This state may be entered from any phase and exit into + * non-predelegation phases, but cannot repeat consecutively or be used to transition backward + * across phases. */ QUIET_PERIOD, @@ -201,6 +201,108 @@ public enum TldState { PDT } + /** + * Valid direct transitions between {@link TldState} values. + * + *

TLD launch phases progress strictly forward ({@code PREDELEGATION -> PDT -> + * START_DATE_SUNRISE -> GENERAL_AVAILABILITY}, skipping optional intermediate phases). {@link + * TldState#QUIET_PERIOD} may be entered from any phase and exit into non-predelegation phases, + * but cannot repeat consecutively or be used to transition backward across phases. + */ + public static final ImmutableMultimap VALID_TLD_STATE_TRANSITIONS = + ImmutableMultimap.builder() + .putAll( + TldState.PREDELEGATION, + TldState.PDT, + TldState.QUIET_PERIOD, + TldState.START_DATE_SUNRISE, + TldState.GENERAL_AVAILABILITY) + .putAll( + TldState.PDT, + TldState.QUIET_PERIOD, + TldState.START_DATE_SUNRISE, + TldState.GENERAL_AVAILABILITY) + .putAll(TldState.START_DATE_SUNRISE, TldState.QUIET_PERIOD, TldState.GENERAL_AVAILABILITY) + .putAll( + TldState.QUIET_PERIOD, + TldState.PDT, + TldState.START_DATE_SUNRISE, + TldState.GENERAL_AVAILABILITY) + .putAll(TldState.GENERAL_AVAILABILITY, TldState.QUIET_PERIOD) + .build(); + + /** + * Creates a validated {@link TimedTransitionProperty} for {@link TldState} transitions, enforcing + * {@link #VALID_TLD_STATE_TRANSITIONS} on both adjacent transitions and phase progression across + * intervening {@link TldState#QUIET_PERIOD} entries. + */ + public static TimedTransitionProperty createTldStateTransitions( + ImmutableSortedMap tldStatesMap) { + checkNotNull(tldStatesMap, "TLD states map cannot be null"); + TimedTransitionProperty transitions = + TimedTransitionProperty.make( + tldStatesMap, VALID_TLD_STATE_TRANSITIONS, "tldStateTransitions"); + validateNonQuietPeriodProgression(tldStatesMap); + return transitions; + } + + private static void validateTldStateTransitions( + ImmutableSortedMap tldStatesMap) { + TimedTransitionProperty.validateTimedTransitionMap( + tldStatesMap, VALID_TLD_STATE_TRANSITIONS, "tldStateTransitions"); + validateNonQuietPeriodProgression(tldStatesMap); + } + + private static void validateNonQuietPeriodProgression( + ImmutableSortedMap tldStatesMap) { + TldState previousPhase = null; + for (TldState state : tldStatesMap.values()) { + if (TldState.QUIET_PERIOD.equals(state)) { + continue; + } + if (previousPhase != null + && !VALID_TLD_STATE_TRANSITIONS.containsEntry(previousPhase, state)) { + throw new IllegalArgumentException( + String.format( + "tldStateTransitions map cannot transition from %s to %s (even via QUIET_PERIOD).", + previousPhase, state)); + } + previousPhase = state; + } + } + + /** + * Validates that every token in {@code promoTokens} exists in the database, has type {@link + * TokenType#DEFAULT_PROMO}, and is allowed on {@code tldStr}. + */ + public static void validateDefaultPromoTokens( + String tldStr, @Nullable List> promoTokens) { + if (promoTokens == null || promoTokens.isEmpty()) { + return; + } + tm().reTransact( + () -> { + Map, AllocationToken> tokensByKey = + tm().loadByKeysIfPresent(promoTokens); + for (VKey tokenKey : promoTokens) { + AllocationToken token = tokensByKey.get(tokenKey); + checkArgument( + token != null, "Default promo token %s does not exist", tokenKey.getKey()); + checkArgument( + token.getTokenType().equals(TokenType.DEFAULT_PROMO), + "Token %s has an invalid token type of %s. DefaultPromoTokens must be of" + + " the type DEFAULT_PROMO", + token.getToken(), + token.getTokenType()); + checkArgument( + token.getAllowedTlds().isEmpty() || token.getAllowedTlds().contains(tldStr), + "The token %s is not valid for this TLD. The valid TLDs for it are %s", + token.getToken(), + token.getAllowedTlds()); + } + }); + } + /** The modes an Expiry Access Period (XAP) can be in at any given point in time. */ public enum ExpiryAccessPeriodMode { DISABLED, @@ -858,6 +960,7 @@ public void validateState() { // here to catch cases where we loaded an invalid TimedTransitionProperty from the database // and cloned it into a new builder, to block re-building a Tld in an invalid state. tldStateTransitions.checkValidity(); + validateTldStateTransitions(tldStateTransitions.toValueMap()); createBillingCostTransitions.checkValidity(); renewBillingCostTransitions.checkValidity(); eapFeeSchedule.checkValidity(); @@ -915,17 +1018,7 @@ public Builder setInvoicingEnabled(boolean invoicingEnabled) { /** Sets the TLD state to transition to the specified states at the specified times. */ public Builder setTldStateTransitions(ImmutableSortedMap tldStatesMap) { - checkNotNull(tldStatesMap, "TLD states map cannot be null"); - // Filter out any entries with QUIET_PERIOD as the value before checking for ordering, since - // that phase is allowed to appear anywhere. - checkArgument( - Ordering.natural() - .isStrictlyOrdered( - tldStatesMap.values().stream() - .filter(state -> !TldState.QUIET_PERIOD.equals(state)) - .collect(Collectors.toList())), - "The TLD states are chronologically out of order"); - getInstance().tldStateTransitions = TimedTransitionProperty.fromValueMap(tldStatesMap); + getInstance().tldStateTransitions = createTldStateTransitions(tldStatesMap); return this; } @@ -1152,24 +1245,8 @@ public Builder setAllowedFullyQualifiedHostNames( } public Builder setDefaultPromoTokens(ImmutableList> promoTokens) { - tm().transact( - () -> { - for (VKey tokenKey : promoTokens) { - AllocationToken token = tm().loadByKey(tokenKey); - checkArgument( - token.getTokenType().equals(TokenType.DEFAULT_PROMO), - "Token %s has an invalid token type of %s. DefaultPromoTokens must be of" - + " the type DEFAULT_PROMO", - token.getToken(), - token.getTokenType()); - checkArgument( - token.getAllowedTlds().contains(getInstance().tldStr), - "The token %s is not valid for this TLD. The valid TLDs for it are %s", - token.getToken(), - token.getAllowedTlds()); - } - getInstance().defaultPromoTokens = promoTokens; - }); + validateDefaultPromoTokens(getInstance().tldStr, promoTokens); + getInstance().defaultPromoTokens = promoTokens; return this; } diff --git a/core/src/main/java/google/registry/tools/ConfigureTldCommand.java b/core/src/main/java/google/registry/tools/ConfigureTldCommand.java index ffa9d79d877..6cd9241d7b4 100644 --- a/core/src/main/java/google/registry/tools/ConfigureTldCommand.java +++ b/core/src/main/java/google/registry/tools/ConfigureTldCommand.java @@ -153,6 +153,7 @@ protected void init() throws Exception { checkPremiumList(newTld); checkDnsWriters(newTld); checkCurrency(newTld); + checkDefaultPromoTokens(newTld); // bsaEnrollStartTime only exists in DB. Need to carry it over to the updated copy. See Tld.java // for more information. Optional bsaEnrollTime = @@ -248,6 +249,10 @@ private void checkDnsWriters(Tld newTld) { invalidDnsWriters.isEmpty(), "Invalid DNS writer name(s) specified: %s", invalidDnsWriters); } + private void checkDefaultPromoTokens(Tld newTld) { + Tld.validateDefaultPromoTokens(newTld.getTldStr(), newTld.getDefaultPromoTokens()); + } + private void checkCurrency(Tld newTld) { CurrencyUnit currencyUnit = newTld.getCurrency(); checkArgument( diff --git a/core/src/main/java/google/registry/tools/GenerateAllocationTokensCommand.java b/core/src/main/java/google/registry/tools/GenerateAllocationTokensCommand.java index 4afd260dc80..97121cc7303 100644 --- a/core/src/main/java/google/registry/tools/GenerateAllocationTokensCommand.java +++ b/core/src/main/java/google/registry/tools/GenerateAllocationTokensCommand.java @@ -315,8 +315,7 @@ private void verifyInput() { // TODO(b/261763205): Create a cleaner way to handle ending bulk pricing packages once we // actually have customers using them boolean hasEnding = - tokenStatusTransitions.containsValue(TokenStatus.ENDED) - || tokenStatusTransitions.containsValue(TokenStatus.CANCELLED); + tokenStatusTransitions.values().stream().anyMatch(AllocationToken::isTerminalStatus); checkArgument( !(BULK_PRICING.equals(tokenType) && hasEnding), "BULK_PRICING tokens should not be generated with ENDED or CANCELLED in their transition" diff --git a/core/src/main/java/google/registry/tools/UpdateAllocationTokensCommand.java b/core/src/main/java/google/registry/tools/UpdateAllocationTokensCommand.java index d2a2e80ad6d..7297def5a20 100644 --- a/core/src/main/java/google/registry/tools/UpdateAllocationTokensCommand.java +++ b/core/src/main/java/google/registry/tools/UpdateAllocationTokensCommand.java @@ -15,10 +15,10 @@ package google.registry.tools; import static com.google.common.base.Preconditions.checkArgument; +import static com.google.common.collect.ImmutableList.toImmutableList; import static com.google.common.collect.ImmutableMap.toImmutableMap; import static com.google.common.collect.ImmutableSet.toImmutableSet; import static com.google.common.collect.Iterables.partition; -import static com.google.common.collect.Streams.stream; import static google.registry.persistence.transaction.TransactionManagerFactory.tm; import com.beust.jcommander.Parameter; @@ -34,6 +34,7 @@ import google.registry.model.domain.token.AllocationToken.RegistrationBehavior; import google.registry.model.domain.token.AllocationToken.TokenStatus; import google.registry.model.domain.token.AllocationToken.TokenType; +import google.registry.persistence.VKey; import google.registry.tools.params.MoneyParameter; import google.registry.tools.params.StringListParameter; import google.registry.tools.params.TransitionListParameter.TokenStatusTransitions; @@ -146,21 +147,14 @@ final class UpdateAllocationTokensCommand extends UpdateOrDeleteAllocationTokens private static final int BATCH_SIZE = 20; private static final Joiner JOINER = Joiner.on(", "); - private ImmutableSet tokensToSave; - private boolean endToken = false; + private ImmutableList> tokenKeysToSave; @Override public void init() { - if (tokenStatusTransitions != null - && (tokenStatusTransitions.containsValue(TokenStatus.ENDED) - || tokenStatusTransitions.containsValue(TokenStatus.CANCELLED))) { - endToken = true; - } - GenerateAllocationTokensCommand.verifyAllRegistrarIdsExist(allowedClientIds); GenerateAllocationTokensCommand.verifyAllTldsExist(allowedTlds); - tokensToSave = + tokenKeysToSave = tm().transact( () -> tm().loadByKeys(getTokenKeys(tokens, prefix)).values().stream() @@ -172,37 +166,65 @@ public void init() { !entry .getKey() .equals(entry.getValue())) // only update changed tokens - .map(Map.Entry::getValue) - .collect(toImmutableSet())); + .map(entry -> entry.getKey().createVKey()) + .collect(toImmutableList())); } @Override public String prompt() { - return String.format("Update %d tokens?", tokensToSave.size()); + return String.format("Update %d tokens?", tokenKeysToSave.size()); } @Override protected String execute() { - long numUpdated = - stream(partition(tokensToSave, BATCH_SIZE)) - .mapToLong(batch -> tm().transact(() -> saveBatch(ImmutableList.copyOf(batch)))) - .sum(); + long numUpdated = 0; + for (List> batch : partition(tokenKeysToSave, BATCH_SIZE)) { + ImmutableList updatedTokenNames = + tm().transact(() -> saveBatch(ImmutableList.copyOf(batch))); + if (!updatedTokenNames.isEmpty()) { + printStream.printf( + "%s tokens: %s\n", dryRun ? "Would update" : "Updated", JOINER.join(updatedTokenNames)); + } + numUpdated += updatedTokenNames.size(); + } return String.format("Updated %d tokens in total.", numUpdated); } - private AllocationToken updateToken(AllocationToken original) { - if (endToken && original.getTokenType().equals(TokenType.BULK_PRICING)) { - Long domainsInBulkPackage = - tm().query("SELECT COUNT(*) FROM Domain WHERE currentBulkToken = :token", Long.class) - .setParameter("token", original.createVKey()) - .getSingleResult(); + private boolean isEndingToken() { + return tokenStatusTransitions != null + && tokenStatusTransitions.values().stream().anyMatch(AllocationToken::isTerminalStatus); + } + + private void verifyNoDomainsInBulkPackage(AllocationToken token) { + Long domainsInBulkPackage = + tm().query("SELECT COUNT(*) FROM Domain WHERE currentBulkToken = :token", Long.class) + .setParameter("token", token.createVKey()) + .getSingleResult(); + checkArgument( + domainsInBulkPackage == 0, + "Bulk token %s can not end its promotion because it still has %s domains in the promotion", + token.getToken(), + domainsInBulkPackage); + } + private AllocationToken updateToken(AllocationToken original) { + Instant txTime = null; + TokenStatus currentStatus = null; + if (tokenStatusTransitions != null) { + txTime = tm().getTxTime(); + currentStatus = + original.getTokenStatusTransitions() == null + ? TokenStatus.NOT_STARTED + : original.getTokenStatusTransitions().getValueAtTime(txTime); checkArgument( - domainsInBulkPackage == 0, - "Bulk token %s can not end its promotion because it still has %s domains in the" - + " promotion", + !AllocationToken.isTerminalStatus(currentStatus), + "Cannot update tokenStatusTransitions for token %s because it is already in terminal" + + " status %s", original.getToken(), - domainsInBulkPackage); + currentStatus); + } + if (isEndingToken() && original.getTokenType().equals(TokenType.BULK_PRICING)) { + verifyNoDomainsInBulkPackage(original); } AllocationToken.Builder builder = original.asBuilder(); Optional.ofNullable(allowedClientIds) @@ -229,21 +251,42 @@ private AllocationToken updateToken(AllocationToken original) { Optional.ofNullable(renewalPriceBehavior).ifPresent(builder::setRenewalPriceBehavior); Optional.ofNullable(renewalPrice).ifPresent(builder::setRenewalPrice); Optional.ofNullable(registrationBehavior).ifPresent(builder::setRegistrationBehavior); - return builder.build(); + AllocationToken updated = builder.build(); + if (tokenStatusTransitions != null) { + TokenStatus newStatus = updated.getTokenStatusTransitions().getValueAtTime(txTime); + checkArgument( + newStatus.equals(currentStatus) + || AllocationToken.VALID_TOKEN_STATUS_TRANSITIONS.containsEntry( + currentStatus, newStatus), + "Cannot transition token %s from current status %s to %s", + original.getToken(), + currentStatus, + newStatus); + if (original.getTokenType().equals(TokenType.UNLIMITED_USE) + || original.getTokenType().equals(TokenType.DEFAULT_PROMO)) { + checkArgument( + tokenStatusTransitions.size() > 1, + "For %s tokens, tokenStatusTransitions must contain at least one transition beyond" + + " NOT_STARTED", + original.getTokenType()); + } + } + return updated; } - private long saveBatch(ImmutableList batch) { - if (!dryRun) { - tm().putAll(batch); + private ImmutableList saveBatch(ImmutableList> batch) { + // Re-load and re-validate inside the write transaction to close TOCTOU races between init() + // and execute() (e.g., domains added to a BULK_PRICING token or a token reaching a terminal + // state while awaiting confirmation). + ImmutableList updatedBatch = + tm().loadByKeys(batch).values().stream() + .map(original -> Map.entry(original, updateToken(original))) + .filter(entry -> !entry.getKey().equals(entry.getValue())) + .map(Map.Entry::getValue) + .collect(toImmutableList()); + if (!dryRun && !updatedBatch.isEmpty()) { + tm().putAll(updatedBatch); } - printStream.printf( - "%s tokens: %s\n", - dryRun ? "Would update" : "Updated", - JOINER.join( - tokensToSave.stream() - .map(AllocationToken::getToken) - .sorted() - .collect(toImmutableSet()))); - return batch.size(); + return updatedBatch.stream().map(AllocationToken::getToken).sorted().collect(toImmutableList()); } } diff --git a/core/src/test/java/google/registry/model/common/TimedTransitionPropertyTest.java b/core/src/test/java/google/registry/model/common/TimedTransitionPropertyTest.java index a2f673a7e78..c8154999c49 100644 --- a/core/src/test/java/google/registry/model/common/TimedTransitionPropertyTest.java +++ b/core/src/test/java/google/registry/model/common/TimedTransitionPropertyTest.java @@ -19,6 +19,7 @@ import static google.registry.util.DateTimeUtils.START_INSTANT; import static org.junit.jupiter.api.Assertions.assertThrows; +import com.google.common.collect.ImmutableMultimap; import com.google.common.collect.ImmutableSortedMap; import java.time.Instant; import org.junit.jupiter.api.BeforeEach; @@ -114,4 +115,58 @@ void testFailure_noValueAtStartOfTime() { IllegalArgumentException.class, () -> TimedTransitionProperty.fromValueMap(ImmutableSortedMap.of(DATE_1, "1"))); } + + @Test + void testSuccess_makeWithAllowedTransitionsOnly() { + ImmutableMultimap allowedTransitions = + ImmutableMultimap.builder().put("0", "1").put("1", "2").build(); + ImmutableSortedMap validMap = + ImmutableSortedMap.of(START_INSTANT, "0", DATE_1, "1", DATE_2, "2"); + TimedTransitionProperty property = + TimedTransitionProperty.make(validMap, allowedTransitions, "testMap"); + assertThat(property.toValueMap()).isEqualTo(validMap); + } + + @Test + void testFailure_makeRejectsInvalidTransition() { + ImmutableMultimap allowedTransitions = + ImmutableMultimap.builder().put("0", "1").put("1", "2").build(); + IllegalArgumentException thrown = + assertThrows( + IllegalArgumentException.class, + () -> + TimedTransitionProperty.make( + ImmutableSortedMap.of(START_INSTANT, "0", DATE_1, "2"), + allowedTransitions, + "testMap")); + assertThat(thrown).hasMessageThat().isEqualTo("testMap map cannot transition from 0 to 2."); + } + + @Test + void testFailure_makeRejectsTransitionFromTerminalState() { + ImmutableMultimap allowedTransitions = + ImmutableMultimap.builder().put("0", "1").build(); + IllegalArgumentException thrown = + assertThrows( + IllegalArgumentException.class, + () -> + TimedTransitionProperty.make( + ImmutableSortedMap.of(START_INSTANT, "0", DATE_1, "1", DATE_2, "0"), + allowedTransitions, + "testMap")); + assertThat(thrown).hasMessageThat().isEqualTo("testMap map cannot transition from 1."); + } + + @Test + void testFailure_makeRejectsEmptyMap() { + ImmutableMultimap allowedTransitions = + ImmutableMultimap.builder().put("0", "1").build(); + IllegalArgumentException thrown = + assertThrows( + IllegalArgumentException.class, + () -> + TimedTransitionProperty.make( + ImmutableSortedMap.of(), allowedTransitions, "testMap")); + assertThat(thrown).hasMessageThat().isEqualTo("testMap map must start at START_INSTANT."); + } } diff --git a/core/src/test/java/google/registry/model/common/TimedTransitionPropertyUsageTest.java b/core/src/test/java/google/registry/model/common/TimedTransitionPropertyUsageTest.java new file mode 100644 index 00000000000..cefafcef971 --- /dev/null +++ b/core/src/test/java/google/registry/model/common/TimedTransitionPropertyUsageTest.java @@ -0,0 +1,180 @@ +// Copyright 2026 The Nomulus Authors. All Rights Reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package google.registry.model.common; + +import static com.google.common.truth.Truth.assertThat; +import static com.google.common.truth.Truth.assertWithMessage; + +import com.google.common.collect.ImmutableSet; +import com.google.common.collect.ImmutableSortedMap; +import google.registry.model.EntityYamlUtils.TimedTransitionPropertyExpiryAccessPeriodModeDeserializer; +import google.registry.model.EntityYamlUtils.TimedTransitionPropertyFeatureStatusDeserializer; +import google.registry.model.EntityYamlUtils.TimedTransitionPropertyMoneyDeserializer; +import google.registry.model.EntityYamlUtils.TimedTransitionPropertyTldStateDeserializer; +import google.registry.model.domain.token.AllocationToken; +import google.registry.model.domain.token.AllocationToken.TokenStatus; +import google.registry.model.tld.Tld; +import google.registry.model.tld.Tld.TldState; +import google.registry.persistence.converter.TimedTransitionBaseUserType; +import io.github.classgraph.ClassGraph; +import io.github.classgraph.ClassInfo; +import io.github.classgraph.ScanResult; +import java.io.IOException; +import java.lang.classfile.ClassFile; +import java.lang.classfile.ClassModel; +import java.lang.classfile.CodeElement; +import java.lang.classfile.MethodModel; +import java.lang.classfile.instruction.InvokeDynamicInstruction; +import java.lang.classfile.instruction.InvokeInstruction; +import java.lang.constant.ClassDesc; +import java.lang.constant.ConstantDesc; +import java.lang.constant.DirectMethodHandleDesc; +import java.net.URI; +import java.time.Instant; +import java.util.Optional; +import org.junit.jupiter.api.Test; + +/** + * Guardrail verifying that only allowlisted stateless callers invoke raw {@link + * TimedTransitionProperty#fromValueMap(ImmutableSortedMap)} in production code, preventing stateful + * transitions ({@link TldState}, {@link TokenStatus}) from bypassing transition-graph validation. + */ +final class TimedTransitionPropertyUsageTest { + + private static final String TIMED_TRANSITION_INTERNAL_NAME = + TimedTransitionProperty.class.getName().replace('.', '/'); + private static final ClassDesc TIMED_TRANSITION_CLASS_DESC = + ClassDesc.of(TimedTransitionProperty.class.getName()); + + /** + * Verified production methods permitted to call raw {@code TimedTransitionProperty.fromValueMap}. + * Stateful properties ({@code TldState}, {@code TokenStatus}) must use validated factory methods. + */ + private static final ImmutableSet ALLOWED_FROM_VALUE_MAP_CALLERS = + ImmutableSet.of( + // Core factory methods on TimedTransitionProperty itself (withInitialValue, make). + TimedTransitionProperty.class.getName() + "#withInitialValue", + TimedTransitionProperty.class.getName() + "#make", + // Hibernate deserialization of already-persisted rows. + TimedTransitionBaseUserType.class.getName() + "#toEntity", + // Stateless YAML deserializers (ExpiryAccessPeriodMode, Money, FeatureStatus). + TimedTransitionPropertyExpiryAccessPeriodModeDeserializer.class.getName() + + "#deserialize", + TimedTransitionPropertyMoneyDeserializer.class.getName() + "#deserialize", + TimedTransitionPropertyFeatureStatusDeserializer.class.getName() + "#deserialize", + // Stateless builder setters (FeatureStatus, ExpiryAccessPeriodMode, Money). + FeatureFlag.Builder.class.getName() + "#setStatusMap", + Tld.Builder.class.getName() + "#setExpiryAccessPeriodTransitions", + Tld.Builder.class.getName() + "#setCreateBillingCostTransitions", + Tld.Builder.class.getName() + "#setRenewBillingCostTransitions", + Tld.Builder.class.getName() + "#setEapFeeSchedule"); + + @Test + void testOnlyAllowlistedProductionCallersInvokeFromValueMap() throws Exception { + URI mainClasspath = + TimedTransitionProperty.class.getProtectionDomain().getCodeSource().getLocation().toURI(); + + ImmutableSet.Builder scannedClasses = ImmutableSet.builder(); + ImmutableSet.Builder callers = ImmutableSet.builder(); + + try (ScanResult scanResult = + new ClassGraph() + .overrideClasspath(mainClasspath) + .acceptPackages("google.registry") + .enableClassInfo() + .ignoreClassVisibility() + .scan()) { + for (ClassInfo classInfo : scanResult.getAllClasses()) { + scannedClasses.add(classInfo.getName()); + callers.addAll(findFromValueMapCallers(classInfo.getResource().load())); + } + } + + assertWithMessage("Expected to scan production classes in core/src/main") + .that(scannedClasses.build()) + .containsAtLeast( + Tld.Builder.class.getName(), + AllocationToken.Builder.class.getName(), + TimedTransitionPropertyTldStateDeserializer.class.getName()); + + assertWithMessage( + "Only allowlisted stateless callers may invoke TimedTransitionProperty.fromValueMap;" + + " stateful transitions (TldState, TokenStatus) must use validated factories") + .that(callers.build()) + .containsExactlyElementsIn(ALLOWED_FROM_VALUE_MAP_CALLERS); + } + + @Test + void testDetectorCatchesUnallowlistedCaller() throws IOException { + String expectedDirectCaller = UnallowlistedCaller.class.getName() + "#bypass"; + String expectedMethodRefCaller = + UnallowlistedCaller.class.getName() + "#bypassViaMethodReference"; + String resourcePath = "/" + UnallowlistedCaller.class.getName().replace('.', '/') + ".class"; + try (var stream = UnallowlistedCaller.class.getResourceAsStream(resourcePath)) { + assertWithMessage("Missing bytecode resource %s", resourcePath).that(stream).isNotNull(); + assertThat(findFromValueMapCallers(stream.readAllBytes())) + .containsExactly(expectedDirectCaller, expectedMethodRefCaller); + assertThat(ALLOWED_FROM_VALUE_MAP_CALLERS) + .containsNoneOf(expectedDirectCaller, expectedMethodRefCaller); + } + } + + private static ImmutableSet findFromValueMapCallers(byte[] bytecode) { + ClassModel classModel = ClassFile.of().parse(bytecode); + String className = classModel.thisClass().asInternalName().replace('/', '.'); + ImmutableSet.Builder callers = ImmutableSet.builder(); + for (MethodModel method : classModel.methods()) { + if (callsFromValueMap(method)) { + callers.add(className + "#" + method.methodName().stringValue()); + } + } + return callers.build(); + } + + private static boolean callsFromValueMap(MethodModel method) { + if (method.code().isEmpty()) { + return false; + } + for (CodeElement element : method.code().get()) { + if (element instanceof InvokeInstruction invoke + && invoke.owner().asInternalName().equals(TIMED_TRANSITION_INTERNAL_NAME) + && invoke.name().equalsString("fromValueMap")) { + return true; + } + if (element instanceof InvokeDynamicInstruction indy) { + for (ConstantDesc arg : indy.bootstrapArgs()) { + if (arg instanceof DirectMethodHandleDesc handle + && handle.owner().equals(TIMED_TRANSITION_CLASS_DESC) + && handle.methodName().equals("fromValueMap")) { + return true; + } + } + } + } + return false; + } + + /** Self-test fixture verifying direct and method-reference {@code fromValueMap} detection. */ + static final class UnallowlistedCaller { + static TimedTransitionProperty bypass(ImmutableSortedMap map) { + return TimedTransitionProperty.fromValueMap(map); + } + + static TimedTransitionProperty bypassViaMethodReference( + ImmutableSortedMap map) { + return Optional.of(map).map(TimedTransitionProperty::fromValueMap).orElseThrow(); + } + } +} diff --git a/core/src/test/java/google/registry/model/domain/token/AllocationTokenTest.java b/core/src/test/java/google/registry/model/domain/token/AllocationTokenTest.java index e914784d5f5..ee89aa6496d 100644 --- a/core/src/test/java/google/registry/model/domain/token/AllocationTokenTest.java +++ b/core/src/test/java/google/registry/model/domain/token/AllocationTokenTest.java @@ -254,6 +254,33 @@ void testFail_bulkTokenInvalidRenewalBehavior() { .build())) .hasMessageThat() .isEqualTo("BULK_PRICING tokens must have a renewal price of 0"); + + assertThat( + assertThrows( + IllegalArgumentException.class, + () -> + new AllocationToken.Builder() + .setToken("abc123") + .setTokenType(TokenType.BULK_PRICING) + .setDiscountFraction(1.0) + .setAllowedEppActions(ImmutableSet.of(CommandName.CREATE)) + .setAllowedRegistrarIds(ImmutableSet.of("TheRegistrar")) + .setRenewalPriceBehavior(RenewalPriceBehavior.SPECIFIED) + .setRenewalPrice(Money.of(CurrencyUnit.USD, 0.99)) + .build())) + .hasMessageThat() + .isEqualTo("BULK_PRICING tokens must have a renewal price of 0"); + } + + @Test + void testIsTerminalStatus() { + assertThat(AllocationToken.isTerminalStatus(NOT_STARTED)).isFalse(); + assertThat(AllocationToken.isTerminalStatus(VALID)).isFalse(); + assertThat(AllocationToken.isTerminalStatus(ENDED)).isTrue(); + assertThat(AllocationToken.isTerminalStatus(CANCELLED)).isTrue(); + IllegalArgumentException thrown = + assertThrows(IllegalArgumentException.class, () -> AllocationToken.isTerminalStatus(null)); + assertThat(thrown).hasMessageThat().isEqualTo("TokenStatus cannot be null"); } @Test diff --git a/core/src/test/java/google/registry/model/tld/TldTest.java b/core/src/test/java/google/registry/model/tld/TldTest.java index 41945ef54fe..9ae453688f0 100644 --- a/core/src/test/java/google/registry/model/tld/TldTest.java +++ b/core/src/test/java/google/registry/model/tld/TldTest.java @@ -21,6 +21,7 @@ import static google.registry.model.domain.token.AllocationToken.TokenType.DEFAULT_PROMO; import static google.registry.model.domain.token.AllocationToken.TokenType.SINGLE_USE; import static google.registry.model.tld.Tld.TldState.GENERAL_AVAILABILITY; +import static google.registry.model.tld.Tld.TldState.PDT; import static google.registry.model.tld.Tld.TldState.PREDELEGATION; import static google.registry.model.tld.Tld.TldState.QUIET_PERIOD; import static google.registry.model.tld.Tld.TldState.START_DATE_SUNRISE; @@ -42,12 +43,14 @@ import static org.joda.money.CurrencyUnit.USD; import static org.junit.jupiter.api.Assertions.assertThrows; +import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSortedMap; import google.registry.dns.writer.VoidDnsWriter; import google.registry.model.EntityTestCase; +import google.registry.model.common.TimedTransitionProperty; import google.registry.model.domain.token.AllocationToken; import google.registry.model.tld.Tld.TldNotFoundException; import google.registry.model.tld.Tld.TldState; @@ -564,30 +567,239 @@ void testFailure_setTldStr_nonCanonicalTld() { @Test void testFailure_tldStatesOutOfOrder() { - assertThrows( - IllegalArgumentException.class, - () -> - Tld.get("tld") - .asBuilder() - .setTldStateTransitions( - ImmutableSortedMap.of( - fakeClock.now(), GENERAL_AVAILABILITY, - plusMonths(fakeClock.now(), 1), START_DATE_SUNRISE)) - .build()); + Instant t1 = Instant.parse("2025-01-01T00:00:00.000Z"); + IllegalArgumentException thrown = + assertThrows( + IllegalArgumentException.class, + () -> + Tld.get("tld") + .asBuilder() + .setTldStateTransitions( + ImmutableSortedMap.of( + START_INSTANT, GENERAL_AVAILABILITY, t1, START_DATE_SUNRISE)) + .build()); + assertThat(thrown) + .hasMessageThat() + .isEqualTo( + "tldStateTransitions map cannot transition from GENERAL_AVAILABILITY to" + + " START_DATE_SUNRISE."); } @Test void testFailure_duplicateTldState() { - assertThrows( - IllegalArgumentException.class, - () -> - Tld.get("tld") - .asBuilder() - .setTldStateTransitions( - ImmutableSortedMap.of( - fakeClock.now(), START_DATE_SUNRISE, - plusMonths(fakeClock.now(), 1), START_DATE_SUNRISE)) - .build()); + Instant t1 = Instant.parse("2025-01-01T00:00:00.000Z"); + IllegalArgumentException thrown = + assertThrows( + IllegalArgumentException.class, + () -> + Tld.get("tld") + .asBuilder() + .setTldStateTransitions( + ImmutableSortedMap.of( + START_INSTANT, START_DATE_SUNRISE, t1, START_DATE_SUNRISE)) + .build()); + assertThat(thrown) + .hasMessageThat() + .isEqualTo( + "tldStateTransitions map cannot transition from START_DATE_SUNRISE to" + + " START_DATE_SUNRISE."); + } + + @Test + void testFailure_tldStateTransition_gaToPdt() { + Instant t1 = Instant.parse("2025-01-01T00:00:00.000Z"); + IllegalArgumentException thrown = + assertThrows( + IllegalArgumentException.class, + () -> + Tld.get("tld") + .asBuilder() + .setTldStateTransitions( + ImmutableSortedMap.of(START_INSTANT, GENERAL_AVAILABILITY, t1, PDT)) + .build()); + assertThat(thrown) + .hasMessageThat() + .isEqualTo("tldStateTransitions map cannot transition from GENERAL_AVAILABILITY to PDT."); + } + + @Test + void testFailure_tldStateTransition_sunriseToPdt() { + Instant t1 = Instant.parse("2025-01-01T00:00:00.000Z"); + IllegalArgumentException thrown = + assertThrows( + IllegalArgumentException.class, + () -> + Tld.get("tld") + .asBuilder() + .setTldStateTransitions( + ImmutableSortedMap.of(START_INSTANT, START_DATE_SUNRISE, t1, PDT)) + .build()); + assertThat(thrown) + .hasMessageThat() + .isEqualTo("tldStateTransitions map cannot transition from START_DATE_SUNRISE to PDT."); + } + + @Test + void testFailure_tldStateTransition_backwardViaQuietPeriod() { + Instant t1 = Instant.parse("2025-01-01T00:00:00.000Z"); + Instant t2 = Instant.parse("2025-02-01T00:00:00.000Z"); + IllegalArgumentException gaToPdt = + assertThrows( + IllegalArgumentException.class, + () -> + Tld.get("tld") + .asBuilder() + .setTldStateTransitions( + ImmutableSortedMap.of( + START_INSTANT, GENERAL_AVAILABILITY, t1, QUIET_PERIOD, t2, PDT)) + .build()); + assertThat(gaToPdt) + .hasMessageThat() + .isEqualTo( + "tldStateTransitions map cannot transition from GENERAL_AVAILABILITY to PDT (even via" + + " QUIET_PERIOD)."); + + IllegalArgumentException gaToSunrise = + assertThrows( + IllegalArgumentException.class, + () -> + Tld.get("tld") + .asBuilder() + .setTldStateTransitions( + ImmutableSortedMap.of( + START_INSTANT, + GENERAL_AVAILABILITY, + t1, + QUIET_PERIOD, + t2, + START_DATE_SUNRISE)) + .build()); + assertThat(gaToSunrise) + .hasMessageThat() + .isEqualTo( + "tldStateTransitions map cannot transition from GENERAL_AVAILABILITY to" + + " START_DATE_SUNRISE (even via QUIET_PERIOD)."); + + IllegalArgumentException gaToGa = + assertThrows( + IllegalArgumentException.class, + () -> + Tld.get("tld") + .asBuilder() + .setTldStateTransitions( + ImmutableSortedMap.of( + START_INSTANT, + GENERAL_AVAILABILITY, + t1, + QUIET_PERIOD, + t2, + GENERAL_AVAILABILITY)) + .build()); + assertThat(gaToGa) + .hasMessageThat() + .isEqualTo( + "tldStateTransitions map cannot transition from GENERAL_AVAILABILITY to" + + " GENERAL_AVAILABILITY (even via QUIET_PERIOD)."); + } + + @Test + void testFailure_tldStateTransition_consecutiveQuietPeriods() { + Instant t1 = Instant.parse("2025-01-01T00:00:00.000Z"); + IllegalArgumentException thrown = + assertThrows( + IllegalArgumentException.class, + () -> + Tld.get("tld") + .asBuilder() + .setTldStateTransitions( + ImmutableSortedMap.of(START_INSTANT, QUIET_PERIOD, t1, QUIET_PERIOD)) + .build()); + assertThat(thrown) + .hasMessageThat() + .isEqualTo("tldStateTransitions map cannot transition from QUIET_PERIOD to QUIET_PERIOD."); + } + + @Test + void testFailure_tldStateTransition_quietPeriodToPredelegation() { + Instant t1 = Instant.parse("2025-01-01T00:00:00.000Z"); + IllegalArgumentException thrown = + assertThrows( + IllegalArgumentException.class, + () -> + Tld.get("tld") + .asBuilder() + .setTldStateTransitions( + ImmutableSortedMap.of(START_INSTANT, QUIET_PERIOD, t1, PREDELEGATION)) + .build()); + assertThat(thrown) + .hasMessageThat() + .isEqualTo("tldStateTransitions map cannot transition from QUIET_PERIOD to PREDELEGATION."); + } + + @Test + void testFailure_validateState_rejectsCorruptTldStateTransitions() { + Instant t1 = Instant.parse("2025-01-01T00:00:00.000Z"); + Tld tld = Tld.get("tld"); + // Simulate a corrupt persisted row loaded via TldStateTransitionUserType without validation. + tld.tldStateTransitions = + TimedTransitionProperty.fromValueMap( + ImmutableSortedMap.of(START_INSTANT, GENERAL_AVAILABILITY, t1, PDT)); + IllegalArgumentException validateThrown = + assertThrows(IllegalArgumentException.class, tld::validateState); + assertThat(validateThrown) + .hasMessageThat() + .isEqualTo("tldStateTransitions map cannot transition from GENERAL_AVAILABILITY to PDT."); + IllegalArgumentException rebuildThrown = + assertThrows(IllegalArgumentException.class, () -> tld.asBuilder().build()); + assertThat(rebuildThrown) + .hasMessageThat() + .isEqualTo("tldStateTransitions map cannot transition from GENERAL_AVAILABILITY to PDT."); + } + + @Test + void testSuccess_tldStateTransition_fullForwardLifecycleWithPdtAndQuietPeriods() { + Instant t1 = Instant.parse("2025-01-01T00:00:00.000Z"); + Instant t2 = Instant.parse("2025-02-01T00:00:00.000Z"); + Instant t3 = Instant.parse("2025-03-01T00:00:00.000Z"); + Instant t4 = Instant.parse("2025-04-01T00:00:00.000Z"); + Instant t5 = Instant.parse("2025-05-01T00:00:00.000Z"); + Instant t6 = Instant.parse("2025-06-01T00:00:00.000Z"); + Tld tld = + Tld.get("tld") + .asBuilder() + .setTldStateTransitions( + ImmutableSortedMap.naturalOrder() + .put(START_INSTANT, PREDELEGATION) + .put(t1, QUIET_PERIOD) + .put(t2, PDT) + .put(t3, START_DATE_SUNRISE) + .put(t4, QUIET_PERIOD) + .put(t5, GENERAL_AVAILABILITY) + .put(t6, QUIET_PERIOD) + .build()) + .build(); + assertThat(tld.isPdt(t2)).isTrue(); + assertThat(tld.getTldState(t5)).isEqualTo(GENERAL_AVAILABILITY); + assertThat(tld.getTldState(t6)).isEqualTo(QUIET_PERIOD); + } + + @Test + void testFailure_yamlToTld_invalidTldStateTransition() throws Exception { + String invalidYaml = + loadFile(getClass(), "tld.yaml") + .replace( + " \"1970-01-01T00:00:00.000Z\": \"GENERAL_AVAILABILITY\"", + """ + "1970-01-01T00:00:00.000Z": "GENERAL_AVAILABILITY" + "2025-01-01T00:00:00.000Z": "PDT"\ + """); + ObjectMapper mapper = createObjectMapper(); + JsonMappingException thrown = + assertThrows(JsonMappingException.class, () -> mapper.readValue(invalidYaml, Tld.class)); + assertThat(thrown) + .hasCauseThat() + .hasMessageThat() + .isEqualTo("tldStateTransitions map cannot transition from GENERAL_AVAILABILITY to PDT."); } @Test @@ -845,6 +1057,20 @@ void testSuccess_setDefaultPromoTokens() { assertThat(registry.getDefaultPromoTokens()).isEqualTo(tokens); } + @Test + void testSuccess_setDefaultPromoTokens_allTldsAllowed() { + Tld registry = Tld.get("tld"); + AllocationToken allTldsToken = + persistResource( + new AllocationToken.Builder() + .setToken("allTldsPromo") + .setTokenType(DEFAULT_PROMO) + .build()); + ImmutableList> tokens = ImmutableList.of(allTldsToken.createVKey()); + registry = registry.asBuilder().setDefaultPromoTokens(tokens).build(); + assertThat(registry.getDefaultPromoTokens()).isEqualTo(tokens); + } + @Test void testFailure_setDefaultPromoTokensWrongTokenType() { Tld registry = Tld.get("tld"); @@ -895,4 +1121,19 @@ void testFailure_setDefaultPromoTokensNotValidForTld() { .isEqualTo( "The token abc123 is not valid for this TLD. The valid TLDs for it are [example]"); } + + @Test + void testFailure_setDefaultPromoTokensNonExistent() { + Tld registry = Tld.get("tld"); + IllegalArgumentException thrown = + assertThrows( + IllegalArgumentException.class, + () -> + registry + .asBuilder() + .setDefaultPromoTokens( + ImmutableList.of(VKey.create(AllocationToken.class, "missing"))) + .build()); + assertThat(thrown).hasMessageThat().isEqualTo("Default promo token missing does not exist"); + } } diff --git a/core/src/test/java/google/registry/tools/ConfigureTldCommandTest.java b/core/src/test/java/google/registry/tools/ConfigureTldCommandTest.java index ee2c35c115a..e2ff7eb6673 100644 --- a/core/src/test/java/google/registry/tools/ConfigureTldCommandTest.java +++ b/core/src/test/java/google/registry/tools/ConfigureTldCommandTest.java @@ -16,6 +16,7 @@ import static com.google.common.truth.Truth.assertThat; import static google.registry.model.EntityYamlUtils.createObjectMapper; import static google.registry.model.domain.token.AllocationToken.TokenType.DEFAULT_PROMO; +import static google.registry.model.domain.token.AllocationToken.TokenType.SINGLE_USE; import static google.registry.testing.DatabaseHelper.createTld; import static google.registry.testing.DatabaseHelper.persistPremiumList; import static google.registry.testing.DatabaseHelper.persistResource; @@ -32,6 +33,7 @@ import static org.junit.jupiter.api.Assertions.assertThrows; import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.exc.InvalidFormatException; import com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException; @@ -731,4 +733,161 @@ void testSuccess_runCommandOnProduction_buildEnvFlag() throws Exception { testTldConfiguredSuccessfully(updatedTld, "tld.yaml"); assertThat(updatedTld.getBreakglassMode()).isFalse(); } + + @Test + void testFailure_invalidTldStateTransitionInYaml_gaToPdt() throws Exception { + String yaml = + loadFile(getClass(), "tld.yaml") + .replace( + " \"1970-01-01T00:00:00.000Z\": \"GENERAL_AVAILABILITY\"", + """ + "1970-01-01T00:00:00.000Z": "GENERAL_AVAILABILITY" + "2025-01-01T00:00:00.000Z": "PDT"\ + """); + File tldFile = tmpDir.resolve("tld.yaml").toFile(); + Files.asCharSink(tldFile, UTF_8).write(yaml); + JsonMappingException thrown = + assertThrows(JsonMappingException.class, () -> runCommandForced("--input=" + tldFile)); + assertThat(thrown) + .hasCauseThat() + .hasMessageThat() + .isEqualTo("tldStateTransitions map cannot transition from GENERAL_AVAILABILITY to PDT."); + } + + @Test + void testFailure_invalidTldStateTransitionInYaml_gaToSunrise() throws Exception { + String yaml = + loadFile(getClass(), "tld.yaml") + .replace( + " \"1970-01-01T00:00:00.000Z\": \"GENERAL_AVAILABILITY\"", + """ + "1970-01-01T00:00:00.000Z": "GENERAL_AVAILABILITY" + "2025-01-01T00:00:00.000Z": "START_DATE_SUNRISE"\ + """); + File tldFile = tmpDir.resolve("tld.yaml").toFile(); + Files.asCharSink(tldFile, UTF_8).write(yaml); + JsonMappingException thrown = + assertThrows(JsonMappingException.class, () -> runCommandForced("--input=" + tldFile)); + assertThat(thrown) + .hasCauseThat() + .hasMessageThat() + .isEqualTo( + "tldStateTransitions map cannot transition from GENERAL_AVAILABILITY to" + + " START_DATE_SUNRISE."); + } + + @Test + void testFailure_invalidTldStateTransitionInYaml_gaToQuietPeriodToPdt() throws Exception { + String yaml = + loadFile(getClass(), "tld.yaml") + .replace( + " \"1970-01-01T00:00:00.000Z\": \"GENERAL_AVAILABILITY\"", + """ + "1970-01-01T00:00:00.000Z": "GENERAL_AVAILABILITY" + "2025-01-01T00:00:00.000Z": "QUIET_PERIOD" + "2025-02-01T00:00:00.000Z": "PDT"\ + """); + File tldFile = tmpDir.resolve("tld.yaml").toFile(); + Files.asCharSink(tldFile, UTF_8).write(yaml); + JsonMappingException thrown = + assertThrows(JsonMappingException.class, () -> runCommandForced("--input=" + tldFile)); + assertThat(thrown) + .hasCauseThat() + .hasMessageThat() + .isEqualTo( + "tldStateTransitions map cannot transition from GENERAL_AVAILABILITY to PDT (even via" + + " QUIET_PERIOD)."); + } + + @Test + void testSuccess_validDefaultPromoTokenInYaml() throws Exception { + AllocationToken defaultToken = + persistResource( + new AllocationToken.Builder() + .setToken("promo1") + .setTokenType(DEFAULT_PROMO) + .setAllowedTlds(ImmutableSet.of("tld")) + .build()); + String yaml = + loadFile(getClass(), "tld.yaml") + .replace("defaultPromoTokens: []", "defaultPromoTokens:\n- \"promo1\""); + File tldFile = tmpDir.resolve("tld.yaml").toFile(); + Files.asCharSink(tldFile, UTF_8).write(yaml); + runCommandForced("--input=" + tldFile); + assertThat(Tld.get("tld").getDefaultPromoTokens()).containsExactly(defaultToken.createVKey()); + } + + @Test + void testSuccess_allTldDefaultPromoTokenInYaml() throws Exception { + AllocationToken allTldsToken = + persistResource( + new AllocationToken.Builder() + .setToken("promoAllTlds") + .setTokenType(DEFAULT_PROMO) + .build()); + String yaml = + loadFile(getClass(), "tld.yaml") + .replace("defaultPromoTokens: []", "defaultPromoTokens:\n- \"promoAllTlds\""); + File tldFile = tmpDir.resolve("tld.yaml").toFile(); + Files.asCharSink(tldFile, UTF_8).write(yaml); + runCommandForced("--input=" + tldFile); + assertThat(Tld.get("tld").getDefaultPromoTokens()).containsExactly(allTldsToken.createVKey()); + } + + @Test + void testFailure_defaultPromoTokenInYamlDoesNotExist() throws Exception { + String yaml = + loadFile(getClass(), "tld.yaml") + .replace("defaultPromoTokens: []", "defaultPromoTokens:\n- \"missingToken\""); + File tldFile = tmpDir.resolve("tld.yaml").toFile(); + Files.asCharSink(tldFile, UTF_8).write(yaml); + IllegalArgumentException thrown = + assertThrows(IllegalArgumentException.class, () -> runCommandForced("--input=" + tldFile)); + assertThat(thrown) + .hasMessageThat() + .isEqualTo("Default promo token missingToken does not exist"); + } + + @Test + void testFailure_defaultPromoTokenInYamlWrongTokenType() throws Exception { + persistResource( + new AllocationToken.Builder() + .setToken("singleUse") + .setTokenType(SINGLE_USE) + .setAllowedTlds(ImmutableSet.of("tld")) + .build()); + String yaml = + loadFile(getClass(), "tld.yaml") + .replace("defaultPromoTokens: []", "defaultPromoTokens:\n- \"singleUse\""); + File tldFile = tmpDir.resolve("tld.yaml").toFile(); + Files.asCharSink(tldFile, UTF_8).write(yaml); + IllegalArgumentException thrown = + assertThrows(IllegalArgumentException.class, () -> runCommandForced("--input=" + tldFile)); + assertThat(thrown) + .hasMessageThat() + .isEqualTo( + "Token singleUse has an invalid token type of SINGLE_USE. DefaultPromoTokens must be of" + + " the type DEFAULT_PROMO"); + } + + @Test + void testFailure_defaultPromoTokenInYamlNotValidForTld() throws Exception { + persistResource( + new AllocationToken.Builder() + .setToken("otherPromo") + .setTokenType(DEFAULT_PROMO) + .setAllowedTlds(ImmutableSet.of("other")) + .build()); + String yaml = + loadFile(getClass(), "tld.yaml") + .replace("defaultPromoTokens: []", "defaultPromoTokens:\n- \"otherPromo\""); + File tldFile = tmpDir.resolve("tld.yaml").toFile(); + Files.asCharSink(tldFile, UTF_8).write(yaml); + IllegalArgumentException thrown = + assertThrows(IllegalArgumentException.class, () -> runCommandForced("--input=" + tldFile)); + assertThat(thrown) + .hasMessageThat() + .isEqualTo( + "The token otherPromo is not valid for this TLD. The valid TLDs for it are [other]"); + } } diff --git a/core/src/test/java/google/registry/tools/UpdateAllocationTokensCommandTest.java b/core/src/test/java/google/registry/tools/UpdateAllocationTokensCommandTest.java index f1e8e647e15..5867a3d9a08 100644 --- a/core/src/test/java/google/registry/tools/UpdateAllocationTokensCommandTest.java +++ b/core/src/test/java/google/registry/tools/UpdateAllocationTokensCommandTest.java @@ -14,6 +14,7 @@ package google.registry.tools; +import static com.google.common.collect.ImmutableList.toImmutableList; import static com.google.common.truth.Truth.assertThat; import static google.registry.model.billing.BillingBase.RenewalPriceBehavior.DEFAULT; import static google.registry.model.billing.BillingBase.RenewalPriceBehavior.NONPREMIUM; @@ -34,7 +35,10 @@ import static google.registry.util.DateTimeUtils.plusDays; import static org.junit.jupiter.api.Assertions.assertThrows; +import com.beust.jcommander.JCommander; import com.beust.jcommander.ParameterException; +import com.google.common.base.Splitter; +import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSortedMap; import google.registry.model.domain.fee.FeeQueryCommandExtensionItem.CommandName; @@ -42,7 +46,9 @@ import google.registry.model.domain.token.AllocationToken.RegistrationBehavior; import google.registry.model.domain.token.AllocationToken.TokenStatus; import google.registry.testing.DatabaseHelper; +import google.registry.tools.params.ParameterFactory; import java.time.Instant; +import java.util.List; import org.joda.money.CurrencyUnit; import org.joda.money.Money; import org.junit.jupiter.api.BeforeEach; @@ -54,6 +60,7 @@ class UpdateAllocationTokensCommandTest extends CommandTestCasenaturalOrder() + .put(START_INSTANT, NOT_STARTED) + .put(minusDays(now, 2), VALID) + .put(minusDays(now, 1), ENDED) + .build()) + .build()); + IllegalArgumentException thrown = + assertThrows( + IllegalArgumentException.class, + () -> + runCommandForced( + "--prefix", + "token", + "--token_status_transitions", + String.format( + "%s=NOT_STARTED,%s=VALID,%s=ENDED", + START_INSTANT, minusDays(now, 2), plusDays(now, 1)))); + assertThat(thrown) + .hasMessageThat() + .isEqualTo( + "Cannot update tokenStatusTransitions for token token because it is already in terminal" + + " status ENDED"); + assertThat(reloadResource(token).getTokenStatusTransitions().getValueAtTime(now)) + .isEqualTo(ENDED); + } + + @Test + void testFailure_updateStatusTransitions_cannotResurrectCancelledToken() { + Instant now = Instant.parse("2022-09-01T00:00:00.000Z"); + fakeClock.setTo(now); + AllocationToken token = + persistResource( + new AllocationToken.Builder() + .setToken("token") + .setTokenType(UNLIMITED_USE) + .setTokenStatusTransitions( + ImmutableSortedMap.naturalOrder() + .put(START_INSTANT, NOT_STARTED) + .put(minusDays(now, 2), VALID) + .put(minusDays(now, 1), CANCELLED) + .build()) + .build()); + IllegalArgumentException thrown = + assertThrows( + IllegalArgumentException.class, + () -> + runCommandForced( + "--prefix", + "token", + "--token_status_transitions", + String.format( + "%s=NOT_STARTED,%s=VALID,%s=ENDED", + START_INSTANT, minusDays(now, 2), plusDays(now, 1)))); + assertThat(thrown) + .hasMessageThat() + .isEqualTo( + "Cannot update tokenStatusTransitions for token token because it is already in terminal" + + " status CANCELLED"); + assertThat(reloadResource(token).getTokenStatusTransitions().getValueAtTime(now)) + .isEqualTo(CANCELLED); + } + + @Test + void testFailure_updateStatusTransitions_cannotRegressValidToNotStarted() { + Instant now = Instant.parse("2022-09-01T00:00:00.000Z"); + fakeClock.setTo(now); + AllocationToken token = + persistResource( + new AllocationToken.Builder() + .setToken("token") + .setTokenType(UNLIMITED_USE) + .setTokenStatusTransitions( + ImmutableSortedMap.naturalOrder() + .put(START_INSTANT, NOT_STARTED) + .put(minusDays(now, 1), VALID) + .put(plusDays(now, 1), ENDED) + .build()) + .build()); + IllegalArgumentException thrown = + assertThrows( + IllegalArgumentException.class, + () -> + runCommandForced( + "--prefix", + "token", + "--token_status_transitions", + String.format( + "%s=NOT_STARTED,%s=VALID,%s=ENDED", + START_INSTANT, plusDays(now, 1), plusDays(now, 5)))); + assertThat(thrown) + .hasMessageThat() + .isEqualTo("Cannot transition token token from current status VALID to NOT_STARTED"); + assertThat(reloadResource(token).getTokenStatusTransitions().getValueAtTime(now)) + .isEqualTo(VALID); + } + + @Test + void testFailure_updateStatusTransitions_singleEntryMapRejectedForUnlimitedUse() { + Instant now = Instant.parse("2022-09-01T00:00:00.000Z"); + fakeClock.setTo(now); + persistResource( + new AllocationToken.Builder() + .setToken("token") + .setTokenType(UNLIMITED_USE) + .setTokenStatusTransitions( + ImmutableSortedMap.naturalOrder() + .put(START_INSTANT, NOT_STARTED) + .put(plusDays(now, 1), VALID) + .put(plusDays(now, 2), ENDED) + .build()) + .build()); + IllegalArgumentException thrown = + assertThrows( + IllegalArgumentException.class, + () -> + runCommandForced( + "--prefix", + "token", + "--token_status_transitions", + String.format("%s=NOT_STARTED", START_INSTANT))); + assertThat(thrown) + .hasMessageThat() + .isEqualTo( + "For UNLIMITED_USE tokens, tokenStatusTransitions must contain at least one transition" + + " beyond NOT_STARTED"); + } + + @Test + void testFailure_endBulkToken_toctouDomainAddedBetweenInitAndExecute() { + Instant now = Instant.parse("2022-09-01T00:00:00.000Z"); + fakeClock.setTo(now); + AllocationToken token = + persistResource( + new AllocationToken.Builder() + .setToken("token") + .setTokenType(BULK_PRICING) + .setDiscountFraction(1.0) + .setRenewalPriceBehavior(SPECIFIED) + .setRenewalPrice(Money.of(CurrencyUnit.USD, 0)) + .setAllowedEppActions(ImmutableSet.of(CommandName.CREATE)) + .setAllowedRegistrarIds(ImmutableSet.of("TheRegistrar")) + .setTokenStatusTransitions( + ImmutableSortedMap.naturalOrder() + .put(START_INSTANT, NOT_STARTED) + .put(minusDays(now, 1), VALID) + .build()) + .build()); + JCommander jcommander = new JCommander(command); + jcommander.addConverterFactory(new ParameterFactory()); + jcommander.parse( + "--prefix", + "token", + "--token_status_transitions", + String.format("%s=NOT_STARTED,%s=VALID,%s=ENDED", START_INSTANT, minusDays(now, 1), now)); + // init() sees zero domains in the bulk package and prepares the update. + command.init(); + // Simulate a domain joining the bulk package before execute() commits the batch. + persistResource( + persistActiveDomain("example.tld") + .asBuilder() + .setCurrentBulkToken(token.createVKey()) + .build()); + IllegalArgumentException thrown = + assertThrows(IllegalArgumentException.class, () -> command.execute()); + assertThat(thrown) + .hasMessageThat() + .isEqualTo( + "Bulk token token can not end its promotion because it still has 1 domains in the" + + " promotion"); + assertThat(reloadResource(token).getTokenStatusTransitions().getValueAtTime(now)) + .isEqualTo(VALID); + } + + @Test + void testFailure_updateStatusTransitions_toctouTokenEndedBetweenInitAndExecute() { + Instant now = Instant.parse("2022-09-01T00:00:00.000Z"); + fakeClock.setTo(now); + AllocationToken token = + persistResource( + new AllocationToken.Builder() + .setToken("token") + .setTokenType(UNLIMITED_USE) + .setTokenStatusTransitions( + ImmutableSortedMap.naturalOrder() + .put(START_INSTANT, NOT_STARTED) + .put(minusDays(now, 1), VALID) + .put(plusDays(now, 1), ENDED) + .build()) + .build()); + JCommander jcommander = new JCommander(command); + jcommander.addConverterFactory(new ParameterFactory()); + jcommander.parse( + "--prefix", + "token", + "--token_status_transitions", + String.format( + "%s=NOT_STARTED,%s=VALID,%s=ENDED", + START_INSTANT, minusDays(now, 1), plusDays(now, 5))); + // init() runs while the token is still VALID. + command.init(); + // Advance the clock past the original ENDED transition before execute() commits. + fakeClock.setTo(plusDays(now, 2)); + IllegalArgumentException thrown = + assertThrows(IllegalArgumentException.class, () -> command.execute()); + assertThat(thrown) + .hasMessageThat() + .isEqualTo( + "Cannot update tokenStatusTransitions for token token because it is already in terminal" + + " status ENDED"); + assertThat(reloadResource(token).getTokenStatusTransitions().getValueAtTime(plusDays(now, 2))) + .isEqualTo(ENDED); + } + + @Test + void testSuccess_saveBatchSkipsConcurrentlyAlreadyUpdatedToken() { + AllocationToken token = + persistResource( + new AllocationToken.Builder() + .setToken("token") + .setTokenType(SINGLE_USE) + .setAllowedTlds(ImmutableSet.of("tld")) + .build()); + JCommander jcommander = new JCommander(command); + jcommander.addConverterFactory(new ParameterFactory()); + jcommander.parse("--prefix", "token", "--allowed_tlds", "example"); + command.init(); + // Simulate a concurrent transaction applying the exact same update before execute() runs. + persistResource(token.asBuilder().setAllowedTlds(ImmutableSet.of("example")).build()); + String result = command.execute(); + assertThat(result).isEqualTo("Updated 0 tokens in total."); + assertThat( + getStdoutAsLines().stream() + .filter(line -> line.startsWith("Updated tokens: ")) + .collect(toImmutableList())) + .isEmpty(); + } + + @Test + void testSuccess_saveBatchLogsOnlyCurrentBatch() throws Exception { + ImmutableSet.Builder expectedTokens = ImmutableSet.builder(); + for (int i = 0; i < 25; i++) { + String tokenStr = String.format("batchToken%02d", i); + expectedTokens.add(tokenStr); + persistResource( + new AllocationToken.Builder() + .setToken(tokenStr) + .setTokenType(SINGLE_USE) + .setAllowedTlds(ImmutableSet.of("tld")) + .build()); + } + runCommandForced("--prefix", "batchToken", "--allowed_tlds", "example"); + ImmutableList updatedLines = + getStdoutAsLines().stream() + .filter(line -> line.startsWith("Updated tokens: ")) + .collect(toImmutableList()); + assertThat(updatedLines).hasSize(2); + List firstBatch = + Splitter.on(", ").splitToList(updatedLines.get(0).substring("Updated tokens: ".length())); + List secondBatch = + Splitter.on(", ").splitToList(updatedLines.get(1).substring("Updated tokens: ".length())); + assertThat(firstBatch).hasSize(20); + assertThat(secondBatch).hasSize(5); + assertThat(firstBatch).isInOrder(); + assertThat(secondBatch).isInOrder(); + assertThat(firstBatch).containsNoneIn(secondBatch); + ImmutableSet loggedTokens = + ImmutableSet.builder().addAll(firstBatch).addAll(secondBatch).build(); + assertThat(loggedTokens).containsExactlyElementsIn(expectedTokens.build()); + } + @Test void testUpdate_onlyWithPrefix() throws Exception { AllocationToken token =