Create methods to administratively (un)lock domains (#494)

* Refactor DomainLockUtils methods to take a time rather than a clock

* Add administratively (un)lock methods

* Responses to CR

- Javadoc changes
- Method renames
- Variable renames

* Refactor lock methods to use JPA transaction time

* Remove clock, use Datastore transaction time

* Properly use Datastore transaction time, batched

* Continue to throw exceptions on invalid domains

* DAO writes should be in a transaction

* Assume in-transaction for all RLDao methods

* clean up test

* Fix more tests

* add comment
This commit is contained in:
gbrodman 2020-02-26 17:11:16 -05:00 committed by GitHub
parent 3cd0b4d5e5
commit fc0a9160b2
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
20 changed files with 593 additions and 464 deletions

View file

@ -31,38 +31,32 @@ public final class RegistryLockDao {
* creation and one after verification. * creation and one after verification.
*/ */
public static Optional<RegistryLock> getByVerificationCode(String verificationCode) { public static Optional<RegistryLock> getByVerificationCode(String verificationCode) {
return jpaTm() jpaTm().assertInTransaction();
.transact( EntityManager em = jpaTm().getEntityManager();
() -> { Long revisionId =
EntityManager em = jpaTm().getEntityManager(); em.createQuery(
Long revisionId = "SELECT MAX(revisionId) FROM RegistryLock WHERE verificationCode ="
em.createQuery( + " :verificationCode",
"SELECT MAX(revisionId) FROM RegistryLock WHERE verificationCode =" Long.class)
+ " :verificationCode", .setParameter("verificationCode", verificationCode)
Long.class) .getSingleResult();
.setParameter("verificationCode", verificationCode) return Optional.ofNullable(revisionId).map(revision -> em.find(RegistryLock.class, revision));
.getSingleResult();
return Optional.ofNullable(revisionId)
.map(revision -> em.find(RegistryLock.class, revision));
});
} }
/** Returns all lock objects that this registrar has created. */ /** Returns all lock objects that this registrar has created. */
public static ImmutableList<RegistryLock> getLockedDomainsByRegistrarId(String registrarId) { public static ImmutableList<RegistryLock> getLockedDomainsByRegistrarId(String registrarId) {
return jpaTm() jpaTm().assertInTransaction();
.transact( return ImmutableList.copyOf(
() -> jpaTm()
ImmutableList.copyOf( .getEntityManager()
jpaTm() .createQuery(
.getEntityManager() "SELECT lock FROM RegistryLock lock WHERE"
.createQuery( + " lock.registrarId = :registrarId "
"SELECT lock FROM RegistryLock lock WHERE" + "AND lock.lockCompletionTimestamp IS NOT NULL "
+ " lock.registrarId = :registrarId " + "AND lock.unlockCompletionTimestamp IS NULL",
+ "AND lock.lockCompletionTimestamp IS NOT NULL " RegistryLock.class)
+ "AND lock.unlockCompletionTimestamp IS NULL", .setParameter("registrarId", registrarId)
RegistryLock.class) .getResultList());
.setParameter("registrarId", registrarId)
.getResultList()));
} }
/** /**
@ -70,19 +64,17 @@ public final class RegistryLockDao {
* domain hasn't been locked before. * domain hasn't been locked before.
*/ */
public static Optional<RegistryLock> getMostRecentByRepoId(String repoId) { public static Optional<RegistryLock> getMostRecentByRepoId(String repoId) {
jpaTm().assertInTransaction();
return jpaTm() return jpaTm()
.transact( .getEntityManager()
() -> .createQuery(
jpaTm() "SELECT lock FROM RegistryLock lock WHERE lock.repoId = :repoId"
.getEntityManager() + " ORDER BY lock.revisionId DESC",
.createQuery( RegistryLock.class)
"SELECT lock FROM RegistryLock lock WHERE lock.repoId = :repoId" .setParameter("repoId", repoId)
+ " ORDER BY lock.revisionId DESC", .setMaxResults(1)
RegistryLock.class) .getResultStream()
.setParameter("repoId", repoId) .findFirst();
.setMaxResults(1)
.getResultStream()
.findFirst());
} }
/** /**
@ -91,24 +83,23 @@ public final class RegistryLockDao {
* #getMostRecentByRepoId(String)} in that it only returns verified locks. * #getMostRecentByRepoId(String)} in that it only returns verified locks.
*/ */
public static Optional<RegistryLock> getMostRecentVerifiedLockByRepoId(String repoId) { public static Optional<RegistryLock> getMostRecentVerifiedLockByRepoId(String repoId) {
jpaTm().assertInTransaction();
return jpaTm() return jpaTm()
.transact( .getEntityManager()
() -> .createQuery(
jpaTm() "SELECT lock FROM RegistryLock lock WHERE lock.repoId = :repoId AND"
.getEntityManager() + " lock.lockCompletionTimestamp IS NOT NULL ORDER BY lock.revisionId"
.createQuery( + " DESC",
"SELECT lock FROM RegistryLock lock WHERE lock.repoId = :repoId AND" RegistryLock.class)
+ " lock.lockCompletionTimestamp IS NOT NULL ORDER BY lock.revisionId" .setParameter("repoId", repoId)
+ " DESC", .setMaxResults(1)
RegistryLock.class) .getResultStream()
.setParameter("repoId", repoId) .findFirst();
.setMaxResults(1)
.getResultStream()
.findFirst());
} }
public static RegistryLock save(RegistryLock registryLock) { public static RegistryLock save(RegistryLock registryLock) {
jpaTm().assertInTransaction();
checkNotNull(registryLock, "Null registry lock cannot be saved"); checkNotNull(registryLock, "Null registry lock cannot be saved");
return jpaTm().transact(() -> jpaTm().getEntityManager().merge(registryLock)); return jpaTm().getEntityManager().merge(registryLock);
} }
} }

View file

@ -23,7 +23,6 @@ import google.registry.model.Buildable;
import google.registry.model.CreateAutoTimestamp; import google.registry.model.CreateAutoTimestamp;
import google.registry.model.ImmutableObject; import google.registry.model.ImmutableObject;
import google.registry.model.UpdateAutoTimestamp; import google.registry.model.UpdateAutoTimestamp;
import google.registry.util.Clock;
import google.registry.util.DateTimeUtils; import google.registry.util.DateTimeUtils;
import java.time.ZonedDateTime; import java.time.ZonedDateTime;
import java.util.Optional; import java.util.Optional;
@ -185,17 +184,17 @@ public final class RegistryLock extends ImmutableObject implements Buildable {
} }
/** Returns true iff the lock was requested >= 1 hour ago and has not been verified. */ /** Returns true iff the lock was requested >= 1 hour ago and has not been verified. */
public boolean isLockRequestExpired(Clock clock) { public boolean isLockRequestExpired(DateTime now) {
return !getLockCompletionTimestamp().isPresent() return !getLockCompletionTimestamp().isPresent()
&& isBeforeOrAt(getLockRequestTimestamp(), clock.nowUtc().minusHours(1)); && isBeforeOrAt(getLockRequestTimestamp(), now.minusHours(1));
} }
/** Returns true iff the unlock was requested >= 1 hour ago and has not been verified. */ /** Returns true iff the unlock was requested >= 1 hour ago and has not been verified. */
public boolean isUnlockRequestExpired(Clock clock) { public boolean isUnlockRequestExpired(DateTime now) {
Optional<DateTime> unlockRequestTimestamp = getUnlockRequestTimestamp(); Optional<DateTime> unlockRequestTimestamp = getUnlockRequestTimestamp();
return unlockRequestTimestamp.isPresent() return unlockRequestTimestamp.isPresent()
&& !getUnlockCompletionTimestamp().isPresent() && !getUnlockCompletionTimestamp().isPresent()
&& isBeforeOrAt(unlockRequestTimestamp.get(), clock.nowUtc().minusHours(1)); && isBeforeOrAt(unlockRequestTimestamp.get(), now.minusHours(1));
} }
@Override @Override

View file

@ -31,12 +31,12 @@ import google.registry.model.registry.Registry;
import google.registry.model.registry.RegistryLockDao; import google.registry.model.registry.RegistryLockDao;
import google.registry.model.reporting.HistoryEntry; import google.registry.model.reporting.HistoryEntry;
import google.registry.schema.domain.RegistryLock; import google.registry.schema.domain.RegistryLock;
import google.registry.util.Clock;
import google.registry.util.StringGenerator; import google.registry.util.StringGenerator;
import java.util.Optional; import java.util.Optional;
import javax.annotation.Nullable; import javax.annotation.Nullable;
import javax.inject.Inject; import javax.inject.Inject;
import javax.inject.Named; import javax.inject.Named;
import org.joda.time.DateTime;
/** /**
* Utility functions for validating and applying {@link RegistryLock}s. * Utility functions for validating and applying {@link RegistryLock}s.
@ -56,13 +56,133 @@ public final class DomainLockUtils {
this.stringGenerator = stringGenerator; this.stringGenerator = stringGenerator;
} }
public RegistryLock createRegistryLockRequest( /**
String domainName, * Creates and persists a lock request when requested by a user.
String registrarId, *
@Nullable String registrarPocId, * <p>The lock will not be applied until {@link #verifyAndApplyLock} is called.
boolean isAdmin, */
Clock clock) { public RegistryLock saveNewRegistryLockRequest(
DomainBase domainBase = getDomain(domainName, clock); String domainName, String registrarId, @Nullable String registrarPocId, boolean isAdmin) {
return jpaTm()
.transact(
() ->
RegistryLockDao.save(
createLockBuilder(domainName, registrarId, registrarPocId, isAdmin).build()));
}
/**
* Creates and persists an unlock request when requested by a user.
*
* <p>The unlock will not be applied until {@link #verifyAndApplyUnlock} is called.
*/
public RegistryLock saveNewRegistryUnlockRequest(
String domainName, String registrarId, boolean isAdmin) {
return jpaTm()
.transact(
() ->
RegistryLockDao.save(
createUnlockBuilder(domainName, registrarId, isAdmin).build()));
}
/** Verifies and applies the lock request previously requested by a user. */
public RegistryLock verifyAndApplyLock(String verificationCode, boolean isAdmin) {
return jpaTm()
.transact(
() -> {
DateTime now = jpaTm().getTransactionTime();
RegistryLock lock = getByVerificationCode(verificationCode);
checkArgument(
!lock.getLockCompletionTimestamp().isPresent(),
"Domain %s is already locked",
lock.getDomainName());
checkArgument(
!lock.isLockRequestExpired(now),
"The pending lock has expired; please try again");
checkArgument(
!lock.isSuperuser() || isAdmin, "Non-admin user cannot complete admin lock");
RegistryLock newLock =
RegistryLockDao.save(lock.asBuilder().setLockCompletionTimestamp(now).build());
tm().transact(() -> applyLockStatuses(newLock, now));
return newLock;
});
}
/** Verifies and applies the unlock request previously requested by a user. */
public RegistryLock verifyAndApplyUnlock(String verificationCode, boolean isAdmin) {
return jpaTm()
.transact(
() -> {
DateTime now = jpaTm().getTransactionTime();
RegistryLock lock = getByVerificationCode(verificationCode);
checkArgument(
!lock.getUnlockCompletionTimestamp().isPresent(),
"Domain %s is already unlocked",
lock.getDomainName());
checkArgument(
!lock.isUnlockRequestExpired(now),
"The pending unlock has expired; please try again");
checkArgument(
isAdmin || !lock.isSuperuser(), "Non-admin user cannot complete admin unlock");
RegistryLock newLock =
RegistryLockDao.save(lock.asBuilder().setUnlockCompletionTimestamp(now).build());
tm().transact(() -> removeLockStatuses(newLock, isAdmin, now));
return newLock;
});
}
/**
* Creates and applies a lock in one step -- this should only be used for admin actions, e.g.
* Nomulus tool commands or relocks.
*
* <p>Note: in the case of relocks, isAdmin is determined by the previous lock.
*/
public RegistryLock administrativelyApplyLock(
String domainName, String registrarId, @Nullable String registrarPocId, boolean isAdmin) {
return jpaTm()
.transact(
() -> {
DateTime now = jpaTm().getTransactionTime();
RegistryLock result =
RegistryLockDao.save(
createLockBuilder(domainName, registrarId, registrarPocId, isAdmin)
.setLockCompletionTimestamp(now)
.build());
tm().transact(() -> applyLockStatuses(result, now));
return result;
});
}
/**
* Creates and applies an unlock in one step -- this should only be used for admin actions, e.g.
* Nomulus tool commands.
*/
public RegistryLock administrativelyApplyUnlock(
String domainName, String registrarId, boolean isAdmin) {
return jpaTm()
.transact(
() -> {
DateTime now = jpaTm().getTransactionTime();
RegistryLock result =
RegistryLockDao.save(
createUnlockBuilder(domainName, registrarId, isAdmin)
.setUnlockCompletionTimestamp(now)
.build());
tm().transact(() -> removeLockStatuses(result, isAdmin, now));
return result;
});
}
private RegistryLock.Builder createLockBuilder(
String domainName, String registrarId, @Nullable String registrarPocId, boolean isAdmin) {
DateTime now = jpaTm().getTransactionTime();
DomainBase domainBase = getDomain(domainName, now);
verifyDomainNotLocked(domainBase); verifyDomainNotLocked(domainBase);
// Multiple pending actions are not allowed // Multiple pending actions are not allowed
@ -70,26 +190,24 @@ public final class DomainLockUtils {
.ifPresent( .ifPresent(
previousLock -> previousLock ->
checkArgument( checkArgument(
previousLock.isLockRequestExpired(clock) previousLock.isLockRequestExpired(now)
|| previousLock.getUnlockCompletionTimestamp().isPresent(), || previousLock.getUnlockCompletionTimestamp().isPresent(),
"A pending or completed lock action already exists for %s", "A pending or completed lock action already exists for %s",
previousLock.getDomainName())); previousLock.getDomainName()));
RegistryLock lock = return new RegistryLock.Builder()
new RegistryLock.Builder() .setVerificationCode(stringGenerator.createString(VERIFICATION_CODE_LENGTH))
.setVerificationCode(stringGenerator.createString(VERIFICATION_CODE_LENGTH)) .setDomainName(domainName)
.setDomainName(domainName) .setRepoId(domainBase.getRepoId())
.setRepoId(domainBase.getRepoId()) .setRegistrarId(registrarId)
.setRegistrarId(registrarId) .setRegistrarPocId(registrarPocId)
.setRegistrarPocId(registrarPocId) .isSuperuser(isAdmin);
.isSuperuser(isAdmin)
.build();
return RegistryLockDao.save(lock);
} }
public RegistryLock createRegistryUnlockRequest( private RegistryLock.Builder createUnlockBuilder(
String domainName, String registrarId, boolean isAdmin, Clock clock) { String domainName, String registrarId, boolean isAdmin) {
DomainBase domainBase = getDomain(domainName, clock); DateTime now = jpaTm().getTransactionTime();
DomainBase domainBase = getDomain(domainName, now);
Optional<RegistryLock> lockOptional = Optional<RegistryLock> lockOptional =
RegistryLockDao.getMostRecentVerifiedLockByRepoId(domainBase.getRepoId()); RegistryLockDao.getMostRecentVerifiedLockByRepoId(domainBase.getRepoId());
@ -105,7 +223,7 @@ public final class DomainLockUtils {
new RegistryLock.Builder() new RegistryLock.Builder()
.setRepoId(domainBase.getRepoId()) .setRepoId(domainBase.getRepoId())
.setDomainName(domainName) .setDomainName(domainName)
.setLockCompletionTimestamp(clock.nowUtc()) .setLockCompletionTimestamp(now)
.setRegistrarId(registrarId)); .setRegistrarId(registrarId));
} else { } else {
verifyDomainLocked(domainBase); verifyDomainLocked(domainBase);
@ -117,7 +235,7 @@ public final class DomainLockUtils {
checkArgument( checkArgument(
lock.isLocked(), "Lock object for domain %s is not currently locked", domainName); lock.isLocked(), "Lock object for domain %s is not currently locked", domainName);
checkArgument( checkArgument(
!lock.getUnlockRequestTimestamp().isPresent() || lock.isUnlockRequestExpired(clock), !lock.getUnlockRequestTimestamp().isPresent() || lock.isUnlockRequestExpired(now),
"A pending unlock action already exists for %s", "A pending unlock action already exists for %s",
domainName); domainName);
checkArgument( checkArgument(
@ -128,65 +246,11 @@ public final class DomainLockUtils {
!lock.isSuperuser(), "Non-admin user cannot unlock admin-locked domain %s", domainName); !lock.isSuperuser(), "Non-admin user cannot unlock admin-locked domain %s", domainName);
newLockBuilder = lock.asBuilder(); newLockBuilder = lock.asBuilder();
} }
RegistryLock newLock = return newLockBuilder
newLockBuilder .setVerificationCode(stringGenerator.createString(VERIFICATION_CODE_LENGTH))
.setVerificationCode(stringGenerator.createString(VERIFICATION_CODE_LENGTH)) .isSuperuser(isAdmin)
.isSuperuser(isAdmin) .setUnlockRequestTimestamp(now)
.setUnlockRequestTimestamp(clock.nowUtc()) .setRegistrarId(registrarId);
.setRegistrarId(registrarId)
.build();
return RegistryLockDao.save(newLock);
}
public RegistryLock verifyAndApplyLock(String verificationCode, boolean isAdmin, Clock clock) {
return jpaTm()
.transact(
() -> {
RegistryLock lock = getByVerificationCode(verificationCode);
checkArgument(
!lock.getLockCompletionTimestamp().isPresent(),
"Domain %s is already locked",
lock.getDomainName());
checkArgument(
!lock.isLockRequestExpired(clock),
"The pending lock has expired; please try again");
checkArgument(
!lock.isSuperuser() || isAdmin, "Non-admin user cannot complete admin lock");
RegistryLock newLock =
RegistryLockDao.save(
lock.asBuilder().setLockCompletionTimestamp(clock.nowUtc()).build());
tm().transact(() -> applyLockStatuses(newLock, clock));
return newLock;
});
}
public RegistryLock verifyAndApplyUnlock(String verificationCode, boolean isAdmin, Clock clock) {
return jpaTm()
.transact(
() -> {
RegistryLock lock = getByVerificationCode(verificationCode);
checkArgument(
!lock.getUnlockCompletionTimestamp().isPresent(),
"Domain %s is already unlocked",
lock.getDomainName());
checkArgument(
!lock.isUnlockRequestExpired(clock),
"The pending unlock has expired; please try again");
checkArgument(
isAdmin || !lock.isSuperuser(), "Non-admin user cannot complete admin unlock");
RegistryLock newLock =
RegistryLockDao.save(
lock.asBuilder().setUnlockCompletionTimestamp(clock.nowUtc()).build());
tm().transact(() -> removeLockStatuses(newLock, isAdmin, clock));
return newLock;
});
} }
private static void verifyDomainNotLocked(DomainBase domainBase) { private static void verifyDomainNotLocked(DomainBase domainBase) {
@ -203,8 +267,8 @@ public final class DomainLockUtils {
domainBase.getFullyQualifiedDomainName()); domainBase.getFullyQualifiedDomainName());
} }
private static DomainBase getDomain(String domainName, Clock clock) { private static DomainBase getDomain(String domainName, DateTime now) {
return loadByForeignKeyCached(DomainBase.class, domainName, clock.nowUtc()) return loadByForeignKeyCached(DomainBase.class, domainName, now)
.orElseThrow( .orElseThrow(
() -> new IllegalArgumentException(String.format("Unknown domain %s", domainName))); () -> new IllegalArgumentException(String.format("Unknown domain %s", domainName)));
} }
@ -217,8 +281,8 @@ public final class DomainLockUtils {
String.format("Invalid verification code %s", verificationCode))); String.format("Invalid verification code %s", verificationCode)));
} }
private static void applyLockStatuses(RegistryLock lock, Clock clock) { private static void applyLockStatuses(RegistryLock lock, DateTime lockTime) {
DomainBase domain = getDomain(lock.getDomainName(), clock); DomainBase domain = getDomain(lock.getDomainName(), lockTime);
verifyDomainNotLocked(domain); verifyDomainNotLocked(domain);
DomainBase newDomain = DomainBase newDomain =
@ -227,11 +291,11 @@ public final class DomainLockUtils {
.setStatusValues( .setStatusValues(
ImmutableSet.copyOf(Sets.union(domain.getStatusValues(), REGISTRY_LOCK_STATUSES))) ImmutableSet.copyOf(Sets.union(domain.getStatusValues(), REGISTRY_LOCK_STATUSES)))
.build(); .build();
saveEntities(newDomain, lock, clock); saveEntities(newDomain, lock, lockTime, true);
} }
private static void removeLockStatuses(RegistryLock lock, boolean isAdmin, Clock clock) { private static void removeLockStatuses(RegistryLock lock, boolean isAdmin, DateTime unlockTime) {
DomainBase domain = getDomain(lock.getDomainName(), clock); DomainBase domain = getDomain(lock.getDomainName(), unlockTime);
if (!isAdmin) { if (!isAdmin) {
verifyDomainLocked(domain); verifyDomainLocked(domain);
} }
@ -243,18 +307,21 @@ public final class DomainLockUtils {
ImmutableSet.copyOf( ImmutableSet.copyOf(
Sets.difference(domain.getStatusValues(), REGISTRY_LOCK_STATUSES))) Sets.difference(domain.getStatusValues(), REGISTRY_LOCK_STATUSES)))
.build(); .build();
saveEntities(newDomain, lock, clock); saveEntities(newDomain, lock, unlockTime, false);
} }
private static void saveEntities(DomainBase domain, RegistryLock lock, Clock clock) { private static void saveEntities(
String reason = "Lock or unlock of a domain through a RegistryLock operation"; DomainBase domain, RegistryLock lock, DateTime now, boolean isLock) {
String reason =
String.format(
"%s of a domain through a RegistryLock operation", isLock ? "Lock" : "Unlock");
HistoryEntry historyEntry = HistoryEntry historyEntry =
new HistoryEntry.Builder() new HistoryEntry.Builder()
.setClientId(domain.getCurrentSponsorClientId()) .setClientId(domain.getCurrentSponsorClientId())
.setBySuperuser(lock.isSuperuser()) .setBySuperuser(lock.isSuperuser())
.setRequestedByRegistrar(!lock.isSuperuser()) .setRequestedByRegistrar(!lock.isSuperuser())
.setType(HistoryEntry.Type.DOMAIN_UPDATE) .setType(HistoryEntry.Type.DOMAIN_UPDATE)
.setModificationTime(clock.nowUtc()) .setModificationTime(now)
.setParent(Key.create(domain)) .setParent(Key.create(domain))
.setReason(reason) .setReason(reason)
.build(); .build();
@ -266,8 +333,8 @@ public final class DomainLockUtils {
.setTargetId(domain.getForeignKey()) .setTargetId(domain.getForeignKey())
.setClientId(domain.getCurrentSponsorClientId()) .setClientId(domain.getCurrentSponsorClientId())
.setCost(Registry.get(domain.getTld()).getServerStatusChangeCost()) .setCost(Registry.get(domain.getTld()).getServerStatusChangeCost())
.setEventTime(clock.nowUtc()) .setEventTime(now)
.setBillingTime(clock.nowUtc()) .setBillingTime(now)
.setParent(historyEntry) .setParent(historyEntry)
.build(); .build();
ofy().save().entity(oneTime); ofy().save().entity(oneTime);

View file

@ -22,7 +22,6 @@ import com.google.common.collect.Sets;
import com.google.common.flogger.FluentLogger; import com.google.common.flogger.FluentLogger;
import google.registry.model.domain.DomainBase; import google.registry.model.domain.DomainBase;
import google.registry.model.eppcommon.StatusValue; import google.registry.model.eppcommon.StatusValue;
import google.registry.schema.domain.RegistryLock;
import org.joda.time.DateTime; import org.joda.time.DateTime;
/** /**
@ -36,35 +35,24 @@ public class LockDomainCommand extends LockOrUnlockDomainCommand {
private static final FluentLogger logger = FluentLogger.forEnclosingClass(); private static final FluentLogger logger = FluentLogger.forEnclosingClass();
@Override @Override
protected ImmutableSet<String> getRelevantDomains() { protected boolean shouldApplyToDomain(String domain, DateTime now) {
// Project all domains as of the same time so that argument order doesn't affect behavior. DomainBase domainBase =
DateTime now = clock.nowUtc(); loadByForeignKey(DomainBase.class, domain, now)
ImmutableSet.Builder<String> relevantDomains = new ImmutableSet.Builder<>(); .orElseThrow(
for (String domain : getDomains()) { () ->
DomainBase domainBase = new IllegalArgumentException(
loadByForeignKey(DomainBase.class, domain, now) String.format("Domain '%s' does not exist or is deleted", domain)));
.orElseThrow( ImmutableSet<StatusValue> statusesToAdd =
() -> Sets.difference(REGISTRY_LOCK_STATUSES, domainBase.getStatusValues()).immutableCopy();
new IllegalArgumentException( if (statusesToAdd.isEmpty()) {
String.format("Domain '%s' does not exist or is deleted", domain))); logger.atInfo().log("Domain '%s' is already locked and needs no updates.", domain);
ImmutableSet<StatusValue> statusesToAdd = return false;
Sets.difference(REGISTRY_LOCK_STATUSES, domainBase.getStatusValues()).immutableCopy();
if (statusesToAdd.isEmpty()) {
logger.atInfo().log("Domain '%s' is already locked and needs no updates.", domain);
continue;
}
relevantDomains.add(domain);
} }
return relevantDomains.build(); return true;
} }
@Override @Override
protected RegistryLock createLock(String domain) { protected void createAndApplyRequest(String domain) {
return domainLockUtils.createRegistryLockRequest(domain, clientId, null, true, clock); domainLockUtils.administrativelyApplyLock(domain, clientId, null, true);
}
@Override
protected void finalizeLockOrUnlockRequest(RegistryLock lock) {
domainLockUtils.verifyAndApplyLock(lock.getVerificationCode(), true, clock);
} }
} }

View file

@ -15,29 +15,33 @@
package google.registry.tools; package google.registry.tools;
import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.collect.Iterables.partition;
import static google.registry.model.eppcommon.StatusValue.SERVER_DELETE_PROHIBITED; import static google.registry.model.eppcommon.StatusValue.SERVER_DELETE_PROHIBITED;
import static google.registry.model.eppcommon.StatusValue.SERVER_TRANSFER_PROHIBITED; import static google.registry.model.eppcommon.StatusValue.SERVER_TRANSFER_PROHIBITED;
import static google.registry.model.eppcommon.StatusValue.SERVER_UPDATE_PROHIBITED; import static google.registry.model.eppcommon.StatusValue.SERVER_UPDATE_PROHIBITED;
import static google.registry.persistence.transaction.TransactionManagerFactory.tm;
import static google.registry.util.CollectionUtils.findDuplicates; import static google.registry.util.CollectionUtils.findDuplicates;
import com.beust.jcommander.Parameter; import com.beust.jcommander.Parameter;
import com.google.common.base.Joiner; import com.google.common.base.Joiner;
import com.google.common.base.Throwables;
import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSet;
import com.google.common.flogger.FluentLogger; import com.google.common.flogger.FluentLogger;
import google.registry.config.RegistryConfig.Config; import google.registry.config.RegistryConfig.Config;
import google.registry.model.eppcommon.StatusValue; import google.registry.model.eppcommon.StatusValue;
import google.registry.schema.domain.RegistryLock;
import google.registry.util.Clock;
import java.util.List; import java.util.List;
import javax.inject.Inject; import javax.inject.Inject;
import org.joda.time.DateTime;
/** Shared base class for commands to registry lock or unlock a domain via EPP. */ /**
* Shared base class for commands to registry lock or unlock a domain via EPP.
*/
public abstract class LockOrUnlockDomainCommand extends ConfirmingCommand public abstract class LockOrUnlockDomainCommand extends ConfirmingCommand
implements CommandWithRemoteApi { implements CommandWithRemoteApi {
private static final FluentLogger logger = FluentLogger.forEnclosingClass(); private static final FluentLogger logger = FluentLogger.forEnclosingClass();
private static final int BATCH_SIZE = 10;
public static final ImmutableSet<StatusValue> REGISTRY_LOCK_STATUSES = public static final ImmutableSet<StatusValue> REGISTRY_LOCK_STATUSES =
ImmutableSet.of( ImmutableSet.of(
SERVER_DELETE_PROHIBITED, SERVER_TRANSFER_PROHIBITED, SERVER_UPDATE_PROHIBITED); SERVER_DELETE_PROHIBITED, SERVER_TRANSFER_PROHIBITED, SERVER_UPDATE_PROHIBITED);
@ -55,11 +59,8 @@ public abstract class LockOrUnlockDomainCommand extends ConfirmingCommand
@Config("registryAdminClientId") @Config("registryAdminClientId")
String registryAdminClientId; String registryAdminClientId;
@Inject Clock clock; @Inject
DomainLockUtils domainLockUtils;
@Inject DomainLockUtils domainLockUtils;
protected ImmutableSet<String> relevantDomains = ImmutableSet.of();
protected ImmutableSet<String> getDomains() { protected ImmutableSet<String> getDomains() {
return ImmutableSet.copyOf(mainParameters); return ImmutableSet.copyOf(mainParameters);
@ -75,34 +76,37 @@ public abstract class LockOrUnlockDomainCommand extends ConfirmingCommand
checkArgument(duplicates.isEmpty(), "Duplicate domain arguments found: '%s'", duplicates); checkArgument(duplicates.isEmpty(), "Duplicate domain arguments found: '%s'", duplicates);
System.out.println( System.out.println(
"== ENSURE THAT YOU HAVE AUTHENTICATED THE REGISTRAR BEFORE RUNNING THIS COMMAND =="); "== ENSURE THAT YOU HAVE AUTHENTICATED THE REGISTRAR BEFORE RUNNING THIS COMMAND ==");
relevantDomains = getRelevantDomains();
} }
@Override @Override
protected String execute() { protected String execute() {
int failures = 0; ImmutableSet.Builder<String> successfulDomainsBuilder = new ImmutableSet.Builder<>();
for (String domain : relevantDomains) { ImmutableSet.Builder<String> skippedDomainsBuilder = new ImmutableSet.Builder<>();
try { ImmutableSet.Builder<String> failedDomainsBuilder = new ImmutableSet.Builder<>();
RegistryLock lock = createLock(domain); partition(getDomains(), BATCH_SIZE).forEach(batch -> tm().transact(() -> {
finalizeLockOrUnlockRequest(lock); for (String domain : batch) {
} catch (Throwable t) { if (shouldApplyToDomain(domain, tm().getTransactionTime())) {
Throwable rootCause = Throwables.getRootCause(t); try {
logger.atSevere().withCause(rootCause).log("Error when (un)locking domain %s.", domain); createAndApplyRequest(domain);
failures++; } catch (Throwable t) {
logger.atSevere().withCause(t).log("Error when (un)locking domain %s.", domain);
failedDomainsBuilder.add(domain);
}
successfulDomainsBuilder.add(domain);
} else {
skippedDomainsBuilder.add(domain);
}
} }
} }));
if (failures == 0) { ImmutableSet<String> successfulDomains = successfulDomainsBuilder.build();
return String.format("Successfully locked/unlocked %d domains.", relevantDomains.size()); ImmutableSet<String> skippedDomains = skippedDomainsBuilder.build();
} else { ImmutableSet<String> failedDomains = failedDomainsBuilder.build();
return String.format( return String.format(
"Successfully locked/unlocked %d domains with %d failures.", "Successfully locked/unlocked domains:\n%s\nSkipped domains:\n%s\nFailed domains:\n%s",
relevantDomains.size() - failures, failures); successfulDomains, skippedDomains, failedDomains);
}
} }
protected abstract ImmutableSet<String> getRelevantDomains(); protected abstract boolean shouldApplyToDomain(String domain, DateTime now);
protected abstract RegistryLock createLock(String domain); protected abstract void createAndApplyRequest(String domain);
protected abstract void finalizeLockOrUnlockRequest(RegistryLock lock);
} }

View file

@ -22,7 +22,6 @@ import com.google.common.collect.Sets;
import com.google.common.flogger.FluentLogger; import com.google.common.flogger.FluentLogger;
import google.registry.model.domain.DomainBase; import google.registry.model.domain.DomainBase;
import google.registry.model.eppcommon.StatusValue; import google.registry.model.eppcommon.StatusValue;
import google.registry.schema.domain.RegistryLock;
import org.joda.time.DateTime; import org.joda.time.DateTime;
/** /**
@ -36,35 +35,24 @@ public class UnlockDomainCommand extends LockOrUnlockDomainCommand {
private static final FluentLogger logger = FluentLogger.forEnclosingClass(); private static final FluentLogger logger = FluentLogger.forEnclosingClass();
@Override @Override
protected ImmutableSet<String> getRelevantDomains() { protected boolean shouldApplyToDomain(String domain, DateTime now) {
// Project all domains as of the same time so that argument order doesn't affect behavior. DomainBase domainBase =
DateTime now = clock.nowUtc(); loadByForeignKey(DomainBase.class, domain, now)
ImmutableSet.Builder<String> relevantDomains = new ImmutableSet.Builder<>(); .orElseThrow(
for (String domain : getDomains()) { () ->
DomainBase domainBase = new IllegalArgumentException(
loadByForeignKey(DomainBase.class, domain, now) String.format("Domain '%s' does not exist or is deleted", domain)));
.orElseThrow( ImmutableSet<StatusValue> statusesToRemove =
() -> Sets.intersection(domainBase.getStatusValues(), REGISTRY_LOCK_STATUSES).immutableCopy();
new IllegalArgumentException( if (statusesToRemove.isEmpty()) {
String.format("Domain '%s' does not exist or is deleted", domain))); logger.atInfo().log("Domain '%s' is already unlocked and needs no updates.", domain);
ImmutableSet<StatusValue> statusesToRemove = return false;
Sets.intersection(domainBase.getStatusValues(), REGISTRY_LOCK_STATUSES).immutableCopy();
if (statusesToRemove.isEmpty()) {
logger.atInfo().log("Domain '%s' is already unlocked and needs no updates.", domain);
continue;
}
relevantDomains.add(domain);
} }
return relevantDomains.build(); return true;
} }
@Override @Override
protected RegistryLock createLock(String domain) { protected void createAndApplyRequest(String domain) {
return domainLockUtils.createRegistryUnlockRequest(domain, clientId, true, clock); domainLockUtils.administrativelyApplyUnlock(domain, clientId, true);
}
@Override
protected void finalizeLockOrUnlockRequest(RegistryLock lock) {
domainLockUtils.verifyAndApplyUnlock(lock.getVerificationCode(), true, clock);
} }
} }

View file

@ -17,6 +17,7 @@ package google.registry.tools.javascrap;
import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.collect.ImmutableList.toImmutableList; import static com.google.common.collect.ImmutableList.toImmutableList;
import static google.registry.model.ofy.ObjectifyService.ofy; import static google.registry.model.ofy.ObjectifyService.ofy;
import static google.registry.persistence.transaction.TransactionManagerFactory.jpaTm;
import static google.registry.tools.LockOrUnlockDomainCommand.REGISTRY_LOCK_STATUSES; import static google.registry.tools.LockOrUnlockDomainCommand.REGISTRY_LOCK_STATUSES;
import com.beust.jcommander.Parameter; import com.beust.jcommander.Parameter;
@ -73,15 +74,14 @@ public class BackfillRegistryLocksCommand extends ConfirmingCommand
@Named("base58StringGenerator") @Named("base58StringGenerator")
StringGenerator stringGenerator; StringGenerator stringGenerator;
private DateTime now;
private ImmutableList<DomainBase> lockedDomains; private ImmutableList<DomainBase> lockedDomains;
@Override @Override
protected String prompt() { protected String prompt() {
checkArgument( checkArgument(
roids != null && !roids.isEmpty(), "Must provide non-empty domain_roids argument"); roids != null && !roids.isEmpty(), "Must provide non-empty domain_roids argument");
now = clock.nowUtc(); lockedDomains =
lockedDomains = getLockedDomainsWithoutLocks(); jpaTm().transact(() -> getLockedDomainsWithoutLocks(jpaTm().getTransactionTime()));
ImmutableList<String> lockedDomainNames = ImmutableList<String> lockedDomainNames =
lockedDomains.stream() lockedDomains.stream()
.map(DomainBase::getFullyQualifiedDomainName) .map(DomainBase::getFullyQualifiedDomainName)
@ -94,24 +94,30 @@ public class BackfillRegistryLocksCommand extends ConfirmingCommand
@Override @Override
protected String execute() { protected String execute() {
ImmutableSet.Builder<DomainBase> failedDomainsBuilder = new ImmutableSet.Builder<>(); ImmutableSet.Builder<DomainBase> failedDomainsBuilder = new ImmutableSet.Builder<>();
for (DomainBase domainBase : lockedDomains) { jpaTm()
try { .transact(
RegistryLockDao.save( () -> {
new RegistryLock.Builder() for (DomainBase domainBase : lockedDomains) {
.isSuperuser(true) try {
.setRegistrarId(registryAdminClientId) RegistryLockDao.save(
.setRepoId(domainBase.getRepoId()) new RegistryLock.Builder()
.setDomainName(domainBase.getFullyQualifiedDomainName()) .isSuperuser(true)
.setLockCompletionTimestamp(getLockCompletionTimestamp(domainBase, now)) .setRegistrarId(registryAdminClientId)
.setVerificationCode(stringGenerator.createString(VERIFICATION_CODE_LENGTH)) .setRepoId(domainBase.getRepoId())
.build()); .setDomainName(domainBase.getFullyQualifiedDomainName())
} catch (Throwable t) { .setLockCompletionTimestamp(
logger.atSevere().withCause(t).log( getLockCompletionTimestamp(domainBase, jpaTm().getTransactionTime()))
"Error when creating lock object for domain %s.", .setVerificationCode(
domainBase.getFullyQualifiedDomainName()); stringGenerator.createString(VERIFICATION_CODE_LENGTH))
failedDomainsBuilder.add(domainBase); .build());
} } catch (Throwable t) {
} logger.atSevere().withCause(t).log(
"Error when creating lock object for domain %s.",
domainBase.getFullyQualifiedDomainName());
failedDomainsBuilder.add(domainBase);
}
}
});
ImmutableSet<DomainBase> failedDomains = failedDomainsBuilder.build(); ImmutableSet<DomainBase> failedDomains = failedDomainsBuilder.build();
if (failedDomains.isEmpty()) { if (failedDomains.isEmpty()) {
return String.format( return String.format(
@ -136,7 +142,7 @@ public class BackfillRegistryLocksCommand extends ConfirmingCommand
.orElse(now); .orElse(now);
} }
private ImmutableList<DomainBase> getLockedDomainsWithoutLocks() { private ImmutableList<DomainBase> getLockedDomainsWithoutLocks(DateTime now) {
return ImmutableList.copyOf( return ImmutableList.copyOf(
ofy().load() ofy().load()
.keys( .keys(

View file

@ -16,6 +16,7 @@ package google.registry.ui.server.registrar;
import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.collect.ImmutableList.toImmutableList; import static com.google.common.collect.ImmutableList.toImmutableList;
import static google.registry.persistence.transaction.TransactionManagerFactory.jpaTm;
import static google.registry.security.JsonResponseHelper.Status.SUCCESS; import static google.registry.security.JsonResponseHelper.Status.SUCCESS;
import static google.registry.ui.server.registrar.RegistrarConsoleModule.PARAM_CLIENT_ID; import static google.registry.ui.server.registrar.RegistrarConsoleModule.PARAM_CLIENT_ID;
import static javax.servlet.http.HttpServletResponse.SC_FORBIDDEN; import static javax.servlet.http.HttpServletResponse.SC_FORBIDDEN;
@ -151,9 +152,12 @@ public final class RegistryLockGetAction implements JsonGetAction {
private ImmutableList<ImmutableMap<String, ?>> getLockedDomains( private ImmutableList<ImmutableMap<String, ?>> getLockedDomains(
String clientId, boolean isAdmin) { String clientId, boolean isAdmin) {
return RegistryLockDao.getLockedDomainsByRegistrarId(clientId).stream() return jpaTm()
.map(lock -> lockToMap(lock, isAdmin)) .transact(
.collect(toImmutableList()); () ->
RegistryLockDao.getLockedDomainsByRegistrarId(clientId).stream()
.map(lock -> lockToMap(lock, isAdmin))
.collect(toImmutableList()));
} }
private ImmutableMap<String, ?> lockToMap(RegistryLock lock, boolean isAdmin) { private ImmutableMap<String, ?> lockToMap(RegistryLock lock, boolean isAdmin) {

View file

@ -43,7 +43,6 @@ import google.registry.request.auth.UserAuthInfo;
import google.registry.schema.domain.RegistryLock; import google.registry.schema.domain.RegistryLock;
import google.registry.security.JsonResponseHelper; import google.registry.security.JsonResponseHelper;
import google.registry.tools.DomainLockUtils; import google.registry.tools.DomainLockUtils;
import google.registry.util.Clock;
import google.registry.util.EmailMessage; import google.registry.util.EmailMessage;
import google.registry.util.SendEmailService; import google.registry.util.SendEmailService;
import java.net.URISyntaxException; import java.net.URISyntaxException;
@ -82,7 +81,6 @@ public class RegistryLockPostAction implements Runnable, JsonActionRunner.JsonAc
private final AuthResult authResult; private final AuthResult authResult;
private final AuthenticatedRegistrarAccessor registrarAccessor; private final AuthenticatedRegistrarAccessor registrarAccessor;
private final SendEmailService sendEmailService; private final SendEmailService sendEmailService;
private final Clock clock;
private final DomainLockUtils domainLockUtils; private final DomainLockUtils domainLockUtils;
private final InternetAddress gSuiteOutgoingEmailAddress; private final InternetAddress gSuiteOutgoingEmailAddress;
@ -92,14 +90,12 @@ public class RegistryLockPostAction implements Runnable, JsonActionRunner.JsonAc
AuthResult authResult, AuthResult authResult,
AuthenticatedRegistrarAccessor registrarAccessor, AuthenticatedRegistrarAccessor registrarAccessor,
SendEmailService sendEmailService, SendEmailService sendEmailService,
Clock clock,
DomainLockUtils domainLockUtils, DomainLockUtils domainLockUtils,
@Config("gSuiteOutgoingEmailAddress") InternetAddress gSuiteOutgoingEmailAddress) { @Config("gSuiteOutgoingEmailAddress") InternetAddress gSuiteOutgoingEmailAddress) {
this.jsonActionRunner = jsonActionRunner; this.jsonActionRunner = jsonActionRunner;
this.authResult = authResult; this.authResult = authResult;
this.registrarAccessor = registrarAccessor; this.registrarAccessor = registrarAccessor;
this.sendEmailService = sendEmailService; this.sendEmailService = sendEmailService;
this.clock = clock;
this.domainLockUtils = domainLockUtils; this.domainLockUtils = domainLockUtils;
this.gSuiteOutgoingEmailAddress = gSuiteOutgoingEmailAddress; this.gSuiteOutgoingEmailAddress = gSuiteOutgoingEmailAddress;
} }
@ -138,14 +134,13 @@ public class RegistryLockPostAction implements Runnable, JsonActionRunner.JsonAc
() -> { () -> {
RegistryLock registryLock = RegistryLock registryLock =
postInput.isLock postInput.isLock
? domainLockUtils.createRegistryLockRequest( ? domainLockUtils.saveNewRegistryLockRequest(
postInput.fullyQualifiedDomainName, postInput.fullyQualifiedDomainName,
postInput.clientId, postInput.clientId,
userEmail, userEmail,
isAdmin, isAdmin)
clock) : domainLockUtils.saveNewRegistryUnlockRequest(
: domainLockUtils.createRegistryUnlockRequest( postInput.fullyQualifiedDomainName, postInput.clientId, isAdmin);
postInput.fullyQualifiedDomainName, postInput.clientId, isAdmin, clock);
sendVerificationEmail(registryLock, userEmail, postInput.isLock); sendVerificationEmail(registryLock, userEmail, postInput.isLock);
}); });
String action = postInput.isLock ? "lock" : "unlock"; String action = postInput.isLock ? "lock" : "unlock";

View file

@ -27,7 +27,6 @@ import google.registry.schema.domain.RegistryLock;
import google.registry.tools.DomainLockUtils; import google.registry.tools.DomainLockUtils;
import google.registry.ui.server.SoyTemplateUtils; import google.registry.ui.server.SoyTemplateUtils;
import google.registry.ui.soy.registrar.RegistryLockVerificationSoyInfo; import google.registry.ui.soy.registrar.RegistryLockVerificationSoyInfo;
import google.registry.util.Clock;
import java.util.HashMap; import java.util.HashMap;
import javax.inject.Inject; import javax.inject.Inject;
@ -48,18 +47,15 @@ public final class RegistryLockVerifyAction extends HtmlAction {
google.registry.ui.soy.AnalyticsSoyInfo.getInstance(), google.registry.ui.soy.AnalyticsSoyInfo.getInstance(),
google.registry.ui.soy.registrar.RegistryLockVerificationSoyInfo.getInstance()); google.registry.ui.soy.registrar.RegistryLockVerificationSoyInfo.getInstance());
private final Clock clock;
private final DomainLockUtils domainLockUtils; private final DomainLockUtils domainLockUtils;
private final String lockVerificationCode; private final String lockVerificationCode;
private final Boolean isLock; private final Boolean isLock;
@Inject @Inject
public RegistryLockVerifyAction( public RegistryLockVerifyAction(
Clock clock,
DomainLockUtils domainLockUtils, DomainLockUtils domainLockUtils,
@Parameter("lockVerificationCode") String lockVerificationCode, @Parameter("lockVerificationCode") String lockVerificationCode,
@Parameter("isLock") Boolean isLock) { @Parameter("isLock") Boolean isLock) {
this.clock = clock;
this.domainLockUtils = domainLockUtils; this.domainLockUtils = domainLockUtils;
this.lockVerificationCode = lockVerificationCode; this.lockVerificationCode = lockVerificationCode;
this.isLock = isLock; this.isLock = isLock;
@ -71,9 +67,9 @@ public final class RegistryLockVerifyAction extends HtmlAction {
boolean isAdmin = authResult.userAuthInfo().get().isUserAdmin(); boolean isAdmin = authResult.userAuthInfo().get().isUserAdmin();
final RegistryLock resultLock; final RegistryLock resultLock;
if (isLock) { if (isLock) {
resultLock = domainLockUtils.verifyAndApplyLock(lockVerificationCode, isAdmin, clock); resultLock = domainLockUtils.verifyAndApplyLock(lockVerificationCode, isAdmin);
} else { } else {
resultLock = domainLockUtils.verifyAndApplyUnlock(lockVerificationCode, isAdmin, clock); resultLock = domainLockUtils.verifyAndApplyUnlock(lockVerificationCode, isAdmin);
} }
data.put("isLock", isLock); data.put("isLock", isLock);
data.put("success", true); data.put("success", true);

View file

@ -17,6 +17,11 @@ package google.registry.model.registry;
import static com.google.common.collect.ImmutableSet.toImmutableSet; import static com.google.common.collect.ImmutableSet.toImmutableSet;
import static com.google.common.truth.Truth.assertThat; import static com.google.common.truth.Truth.assertThat;
import static google.registry.persistence.transaction.TransactionManagerFactory.jpaTm; import static google.registry.persistence.transaction.TransactionManagerFactory.jpaTm;
import static google.registry.testing.SqlHelper.getMostRecentRegistryLockByRepoId;
import static google.registry.testing.SqlHelper.getMostRecentVerifiedRegistryLockByRepoId;
import static google.registry.testing.SqlHelper.getRegistryLockByVerificationCode;
import static google.registry.testing.SqlHelper.getRegistryLocksByRegistrarId;
import static google.registry.testing.SqlHelper.saveRegistryLock;
import static org.junit.Assert.assertThrows; import static org.junit.Assert.assertThrows;
import google.registry.persistence.transaction.JpaTestRules; import google.registry.persistence.transaction.JpaTestRules;
@ -45,9 +50,8 @@ public final class RegistryLockDaoTest {
@Test @Test
public void testSaveAndLoad_success() { public void testSaveAndLoad_success() {
RegistryLock lock = createLock(); RegistryLock lock = createLock();
RegistryLockDao.save(lock); saveRegistryLock(lock);
RegistryLock fromDatabase = RegistryLock fromDatabase = getRegistryLockByVerificationCode(lock.getVerificationCode()).get();
RegistryLockDao.getByVerificationCode(lock.getVerificationCode()).get();
assertThat(fromDatabase.getDomainName()).isEqualTo(lock.getDomainName()); assertThat(fromDatabase.getDomainName()).isEqualTo(lock.getDomainName());
assertThat(fromDatabase.getVerificationCode()).isEqualTo(lock.getVerificationCode()); assertThat(fromDatabase.getVerificationCode()).isEqualTo(lock.getVerificationCode());
assertThat(fromDatabase.getLastUpdateTimestamp()).isEqualTo(fakeClock.nowUtc()); assertThat(fromDatabase.getLastUpdateTimestamp()).isEqualTo(fakeClock.nowUtc());
@ -56,7 +60,7 @@ public final class RegistryLockDaoTest {
@Test @Test
public void testSaveTwiceAndLoad_returnsLatest() { public void testSaveTwiceAndLoad_returnsLatest() {
RegistryLock lock = createLock(); RegistryLock lock = createLock();
jpaTm().transact(() -> RegistryLockDao.save(lock)); saveRegistryLock(lock);
fakeClock.advanceOneMilli(); fakeClock.advanceOneMilli();
jpaTm() jpaTm()
.transact( .transact(
@ -80,16 +84,14 @@ public final class RegistryLockDaoTest {
@Test @Test
public void testSave_load_withUnlock() { public void testSave_load_withUnlock() {
RegistryLock lock = RegistryLock lock =
RegistryLockDao.save( saveRegistryLock(
createLock() createLock()
.asBuilder() .asBuilder()
.setLockCompletionTimestamp(fakeClock.nowUtc()) .setLockCompletionTimestamp(fakeClock.nowUtc())
.setUnlockRequestTimestamp(fakeClock.nowUtc()) .setUnlockRequestTimestamp(fakeClock.nowUtc())
.setUnlockCompletionTimestamp(fakeClock.nowUtc()) .setUnlockCompletionTimestamp(fakeClock.nowUtc())
.build()); .build());
RegistryLockDao.save(lock); RegistryLock fromDatabase = getRegistryLockByVerificationCode(lock.getVerificationCode()).get();
RegistryLock fromDatabase =
RegistryLockDao.getByVerificationCode(lock.getVerificationCode()).get();
assertThat(fromDatabase.getUnlockRequestTimestamp()).isEqualTo(Optional.of(fakeClock.nowUtc())); assertThat(fromDatabase.getUnlockRequestTimestamp()).isEqualTo(Optional.of(fakeClock.nowUtc()));
assertThat(fromDatabase.getUnlockCompletionTimestamp()) assertThat(fromDatabase.getUnlockCompletionTimestamp())
.isEqualTo(Optional.of(fakeClock.nowUtc())); .isEqualTo(Optional.of(fakeClock.nowUtc()));
@ -98,11 +100,11 @@ public final class RegistryLockDaoTest {
@Test @Test
public void testUpdateLock_usingSamePrimaryKey() { public void testUpdateLock_usingSamePrimaryKey() {
RegistryLock lock = RegistryLockDao.save(createLock()); RegistryLock lock = saveRegistryLock(createLock());
fakeClock.advanceOneMilli(); fakeClock.advanceOneMilli();
RegistryLock updatedLock = RegistryLock updatedLock =
lock.asBuilder().setLockCompletionTimestamp(fakeClock.nowUtc()).build(); lock.asBuilder().setLockCompletionTimestamp(fakeClock.nowUtc()).build();
jpaTm().transact(() -> RegistryLockDao.save(updatedLock)); saveRegistryLock(updatedLock);
jpaTm() jpaTm()
.transact( .transact(
() -> { () -> {
@ -115,12 +117,12 @@ public final class RegistryLockDaoTest {
@Test @Test
public void testFailure_saveNull() { public void testFailure_saveNull() {
assertThrows(NullPointerException.class, () -> RegistryLockDao.save(null)); assertThrows(NullPointerException.class, () -> saveRegistryLock(null));
} }
@Test @Test
public void getLock_unknownCode() { public void getLock_unknownCode() {
assertThat(RegistryLockDao.getByVerificationCode("hi").isPresent()).isFalse(); assertThat(getRegistryLockByVerificationCode("hi").isPresent()).isFalse();
} }
@Test @Test
@ -141,57 +143,57 @@ public final class RegistryLockDaoTest {
.setUnlockRequestTimestamp(fakeClock.nowUtc()) .setUnlockRequestTimestamp(fakeClock.nowUtc())
.setUnlockCompletionTimestamp(fakeClock.nowUtc()) .setUnlockCompletionTimestamp(fakeClock.nowUtc())
.build(); .build();
RegistryLockDao.save(lock); saveRegistryLock(lock);
RegistryLockDao.save(secondLock); saveRegistryLock(secondLock);
RegistryLockDao.save(unlockedLock); saveRegistryLock(unlockedLock);
assertThat( assertThat(
RegistryLockDao.getLockedDomainsByRegistrarId("TheRegistrar").stream() getRegistryLocksByRegistrarId("TheRegistrar").stream()
.map(RegistryLock::getDomainName) .map(RegistryLock::getDomainName)
.collect(toImmutableSet())) .collect(toImmutableSet()))
.containsExactly("example.test", "otherexample.test"); .containsExactly("example.test", "otherexample.test");
assertThat(RegistryLockDao.getLockedDomainsByRegistrarId("nonexistent")).isEmpty(); assertThat(getRegistryLocksByRegistrarId("nonexistent")).isEmpty();
} }
@Test @Test
public void testLoad_byRepoId() { public void testLoad_byRepoId() {
RegistryLock completedLock = RegistryLock completedLock =
createLock().asBuilder().setLockCompletionTimestamp(fakeClock.nowUtc()).build(); createLock().asBuilder().setLockCompletionTimestamp(fakeClock.nowUtc()).build();
RegistryLockDao.save(completedLock); saveRegistryLock(completedLock);
fakeClock.advanceOneMilli(); fakeClock.advanceOneMilli();
RegistryLock inProgressLock = createLock(); RegistryLock inProgressLock = createLock();
RegistryLockDao.save(inProgressLock); saveRegistryLock(inProgressLock);
Optional<RegistryLock> mostRecent = RegistryLockDao.getMostRecentByRepoId("repoId"); Optional<RegistryLock> mostRecent = getMostRecentRegistryLockByRepoId("repoId");
assertThat(mostRecent.isPresent()).isTrue(); assertThat(mostRecent.isPresent()).isTrue();
assertThat(mostRecent.get().isLocked()).isFalse(); assertThat(mostRecent.get().isLocked()).isFalse();
} }
@Test @Test
public void testLoad_byRepoId_empty() { public void testLoad_byRepoId_empty() {
assertThat(RegistryLockDao.getMostRecentByRepoId("nonexistent").isPresent()).isFalse(); assertThat(getMostRecentRegistryLockByRepoId("nonexistent").isPresent()).isFalse();
} }
@Test @Test
public void testLoad_verified_byRepoId() { public void testLoad_verified_byRepoId() {
RegistryLock completedLock = RegistryLock completedLock =
createLock().asBuilder().setLockCompletionTimestamp(fakeClock.nowUtc()).build(); createLock().asBuilder().setLockCompletionTimestamp(fakeClock.nowUtc()).build();
RegistryLockDao.save(completedLock); saveRegistryLock(completedLock);
fakeClock.advanceOneMilli(); fakeClock.advanceOneMilli();
RegistryLock inProgressLock = createLock(); RegistryLock inProgressLock = createLock();
RegistryLockDao.save(inProgressLock); saveRegistryLock(inProgressLock);
Optional<RegistryLock> mostRecent = RegistryLockDao.getMostRecentVerifiedLockByRepoId("repoId"); Optional<RegistryLock> mostRecent = getMostRecentVerifiedRegistryLockByRepoId("repoId");
assertThat(mostRecent.isPresent()).isTrue(); assertThat(mostRecent.isPresent()).isTrue();
assertThat(mostRecent.get().isLocked()).isTrue(); assertThat(mostRecent.get().isLocked()).isTrue();
} }
@Test @Test
public void testLoad_verified_byRepoId_empty() { public void testLoad_verified_byRepoId_empty() {
RegistryLockDao.save(createLock()); saveRegistryLock(createLock());
Optional<RegistryLock> mostRecent = RegistryLockDao.getMostRecentVerifiedLockByRepoId("repoId"); Optional<RegistryLock> mostRecent = getMostRecentVerifiedRegistryLockByRepoId("repoId");
assertThat(mostRecent.isPresent()).isFalse(); assertThat(mostRecent.isPresent()).isFalse();
} }

View file

@ -0,0 +1,48 @@
// Copyright 2020 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.testing;
import static google.registry.persistence.transaction.TransactionManagerFactory.jpaTm;
import com.google.common.collect.ImmutableList;
import google.registry.model.registry.RegistryLockDao;
import google.registry.schema.domain.RegistryLock;
import java.util.Optional;
/** Static utils for setting up and retrieving test resources from the SQL database. */
public class SqlHelper {
public static RegistryLock saveRegistryLock(RegistryLock lock) {
return jpaTm().transact(() -> RegistryLockDao.save(lock));
}
public static Optional<RegistryLock> getRegistryLockByVerificationCode(String verificationCode) {
return jpaTm().transact(() -> RegistryLockDao.getByVerificationCode(verificationCode));
}
public static Optional<RegistryLock> getMostRecentRegistryLockByRepoId(String repoId) {
return jpaTm().transact(() -> RegistryLockDao.getMostRecentByRepoId(repoId));
}
public static Optional<RegistryLock> getMostRecentVerifiedRegistryLockByRepoId(String repoId) {
return jpaTm().transact(() -> RegistryLockDao.getMostRecentVerifiedLockByRepoId(repoId));
}
public static ImmutableList<RegistryLock> getRegistryLocksByRegistrarId(String registrarId) {
return jpaTm().transact(() -> RegistryLockDao.getLockedDomainsByRegistrarId(registrarId));
}
private SqlHelper() {}
}

View file

@ -16,12 +16,14 @@ package google.registry.tools;
import static com.google.common.truth.Truth.assertThat; import static com.google.common.truth.Truth.assertThat;
import static google.registry.model.ofy.ObjectifyService.ofy; import static google.registry.model.ofy.ObjectifyService.ofy;
import static google.registry.testing.DatastoreHelper.assertNoBillingEvents;
import static google.registry.testing.DatastoreHelper.createTlds; import static google.registry.testing.DatastoreHelper.createTlds;
import static google.registry.testing.DatastoreHelper.getHistoryEntriesOfType; import static google.registry.testing.DatastoreHelper.getHistoryEntriesOfType;
import static google.registry.testing.DatastoreHelper.getOnlyHistoryEntryOfType; import static google.registry.testing.DatastoreHelper.getOnlyHistoryEntryOfType;
import static google.registry.testing.DatastoreHelper.newDomainBase; import static google.registry.testing.DatastoreHelper.newDomainBase;
import static google.registry.testing.DatastoreHelper.persistActiveHost; import static google.registry.testing.DatastoreHelper.persistActiveHost;
import static google.registry.testing.DatastoreHelper.persistResource; import static google.registry.testing.DatastoreHelper.persistResource;
import static google.registry.testing.SqlHelper.getRegistryLockByVerificationCode;
import static google.registry.tools.LockOrUnlockDomainCommand.REGISTRY_LOCK_STATUSES; import static google.registry.tools.LockOrUnlockDomainCommand.REGISTRY_LOCK_STATUSES;
import static org.junit.Assert.assertThrows; import static org.junit.Assert.assertThrows;
@ -31,7 +33,6 @@ import google.registry.model.billing.BillingEvent.Reason;
import google.registry.model.domain.DomainBase; import google.registry.model.domain.DomainBase;
import google.registry.model.host.HostResource; import google.registry.model.host.HostResource;
import google.registry.model.registry.Registry; import google.registry.model.registry.Registry;
import google.registry.model.registry.RegistryLockDao;
import google.registry.model.reporting.HistoryEntry; import google.registry.model.reporting.HistoryEntry;
import google.registry.persistence.transaction.JpaTestRules; import google.registry.persistence.transaction.JpaTestRules;
import google.registry.persistence.transaction.JpaTestRules.JpaIntegrationWithCoverageRule; import google.registry.persistence.transaction.JpaTestRules.JpaIntegrationWithCoverageRule;
@ -84,98 +85,114 @@ public final class DomainLockUtilsTest {
@Test @Test
public void testSuccess_createLock() { public void testSuccess_createLock() {
domainLockUtils.createRegistryLockRequest(DOMAIN_NAME, "TheRegistrar", POC_ID, false, clock); domainLockUtils.saveNewRegistryLockRequest(DOMAIN_NAME, "TheRegistrar", POC_ID, false);
} }
@Test @Test
public void testSuccess_createUnlock() { public void testSuccess_createUnlock() {
RegistryLock lock = RegistryLock lock =
domainLockUtils.createRegistryLockRequest( domainLockUtils.saveNewRegistryLockRequest(DOMAIN_NAME, "TheRegistrar", POC_ID, false);
DOMAIN_NAME, "TheRegistrar", POC_ID, false, clock); domainLockUtils.verifyAndApplyLock(lock.getVerificationCode(), false);
domainLockUtils.verifyAndApplyLock(lock.getVerificationCode(), false, clock); domainLockUtils.saveNewRegistryUnlockRequest(DOMAIN_NAME, "TheRegistrar", false);
domainLockUtils.createRegistryUnlockRequest(DOMAIN_NAME, "TheRegistrar", false, clock);
} }
@Test @Test
public void testSuccess_createUnlock_adminUnlockingAdmin() { public void testSuccess_createUnlock_adminUnlockingAdmin() {
RegistryLock lock = RegistryLock lock =
domainLockUtils.createRegistryLockRequest(DOMAIN_NAME, "TheRegistrar", null, true, clock); domainLockUtils.saveNewRegistryLockRequest(DOMAIN_NAME, "TheRegistrar", null, true);
domainLockUtils.verifyAndApplyLock(lock.getVerificationCode(), true, clock); domainLockUtils.verifyAndApplyLock(lock.getVerificationCode(), true);
domainLockUtils.createRegistryUnlockRequest(DOMAIN_NAME, "TheRegistrar", true, clock); domainLockUtils.saveNewRegistryUnlockRequest(DOMAIN_NAME, "TheRegistrar", true);
} }
@Test @Test
public void testSuccess_createLock_previousLockExpired() { public void testSuccess_createLock_previousLockExpired() {
domainLockUtils.createRegistryLockRequest(DOMAIN_NAME, "TheRegistrar", POC_ID, false, clock); domainLockUtils.saveNewRegistryLockRequest(DOMAIN_NAME, "TheRegistrar", POC_ID, false);
clock.advanceBy(Duration.standardDays(1)); clock.advanceBy(Duration.standardDays(1));
domainLockUtils.createRegistryLockRequest(DOMAIN_NAME, "TheRegistrar", POC_ID, false, clock); domainLockUtils.saveNewRegistryLockRequest(DOMAIN_NAME, "TheRegistrar", POC_ID, false);
} }
@Test @Test
public void testSuccess_applyLockDomain() { public void testSuccess_applyLockDomain() {
RegistryLock lock = RegistryLock lock =
domainLockUtils.createRegistryLockRequest( domainLockUtils.saveNewRegistryLockRequest(DOMAIN_NAME, "TheRegistrar", POC_ID, false);
DOMAIN_NAME, "TheRegistrar", POC_ID, false, clock); domainLockUtils.verifyAndApplyLock(lock.getVerificationCode(), false);
domainLockUtils.verifyAndApplyLock(lock.getVerificationCode(), false, clock); verifyProperlyLockedDomain(false);
assertThat(reloadDomain().getStatusValues()).containsExactlyElementsIn(REGISTRY_LOCK_STATUSES);
HistoryEntry historyEntry = getOnlyHistoryEntryOfType(domain, HistoryEntry.Type.DOMAIN_UPDATE);
assertThat(historyEntry.getRequestedByRegistrar()).isTrue();
assertThat(historyEntry.getBySuperuser()).isFalse();
assertThat(historyEntry.getReason())
.isEqualTo("Lock or unlock of a domain through a RegistryLock operation");
assertBillingEvent(historyEntry);
} }
@Test @Test
public void testSuccess_applyUnlockDomain() { public void testSuccess_applyUnlockDomain() {
RegistryLock lock = RegistryLock lock =
domainLockUtils.createRegistryLockRequest( domainLockUtils.saveNewRegistryLockRequest(DOMAIN_NAME, "TheRegistrar", POC_ID, false);
DOMAIN_NAME, "TheRegistrar", POC_ID, false, clock); domainLockUtils.verifyAndApplyLock(lock.getVerificationCode(), false);
domainLockUtils.verifyAndApplyLock(lock.getVerificationCode(), false, clock);
RegistryLock unlock = RegistryLock unlock =
domainLockUtils.createRegistryUnlockRequest(DOMAIN_NAME, "TheRegistrar", false, clock); domainLockUtils.saveNewRegistryUnlockRequest(DOMAIN_NAME, "TheRegistrar", false);
domainLockUtils.verifyAndApplyUnlock(unlock.getVerificationCode(), false, clock); domainLockUtils.verifyAndApplyUnlock(unlock.getVerificationCode(), false);
verifyProperlyUnlockedDomain(false);
assertThat(reloadDomain().getStatusValues()).containsNoneIn(REGISTRY_LOCK_STATUSES);
ImmutableList<HistoryEntry> historyEntries =
getHistoryEntriesOfType(domain, HistoryEntry.Type.DOMAIN_UPDATE);
assertThat(historyEntries.size()).isEqualTo(2);
historyEntries.forEach(
entry -> {
assertThat(entry.getRequestedByRegistrar()).isTrue();
assertThat(entry.getBySuperuser()).isFalse();
assertThat(entry.getReason())
.isEqualTo("Lock or unlock of a domain through a RegistryLock operation");
});
assertBillingEvents(historyEntries);
} }
@Test @Test
public void testSuccess_applyAdminLock_onlyHistoryEntry() { public void testSuccess_applyAdminLock_onlyHistoryEntry() {
RegistryLock lock = RegistryLock lock =
domainLockUtils.createRegistryLockRequest(DOMAIN_NAME, "TheRegistrar", null, true, clock); domainLockUtils.saveNewRegistryLockRequest(DOMAIN_NAME, "TheRegistrar", null, true);
domainLockUtils.verifyAndApplyLock(lock.getVerificationCode(), true, clock); domainLockUtils.verifyAndApplyLock(lock.getVerificationCode(), true);
verifyProperlyLockedDomain(true);
}
HistoryEntry historyEntry = getOnlyHistoryEntryOfType(domain, HistoryEntry.Type.DOMAIN_UPDATE); @Test
assertThat(historyEntry.getRequestedByRegistrar()).isFalse(); public void testSuccess_applyAdminUnlock_onlyHistoryEntry() {
assertThat(historyEntry.getBySuperuser()).isTrue(); RegistryLock lock =
DatastoreHelper.assertNoBillingEvents(); domainLockUtils.saveNewRegistryLockRequest(DOMAIN_NAME, "TheRegistrar", null, true);
domainLockUtils.verifyAndApplyLock(lock.getVerificationCode(), true);
RegistryLock unlock =
domainLockUtils.saveNewRegistryUnlockRequest(DOMAIN_NAME, "TheRegistrar", true);
domainLockUtils.verifyAndApplyUnlock(unlock.getVerificationCode(), true);
verifyProperlyUnlockedDomain(true);
}
@Test
public void testSuccess_administrativelyLock_nonAdmin() {
domainLockUtils.administrativelyApplyLock(
DOMAIN_NAME, "TheRegistrar", "Marla.Singer@crr.com", false);
verifyProperlyLockedDomain(false);
}
@Test
public void testSuccess_administrativelyLock_admin() {
domainLockUtils.administrativelyApplyLock(DOMAIN_NAME, "TheRegistrar", null, true);
verifyProperlyLockedDomain(true);
}
@Test
public void testSuccess_administrativelyUnlock_nonAdmin() {
RegistryLock lock =
domainLockUtils.saveNewRegistryLockRequest(DOMAIN_NAME, "TheRegistrar", POC_ID, false);
domainLockUtils.verifyAndApplyLock(lock.getVerificationCode(), false);
domainLockUtils.administrativelyApplyUnlock(DOMAIN_NAME, "TheRegistrar", false);
verifyProperlyUnlockedDomain(false);
}
@Test
public void testSuccess_administrativelyUnlock_admin() {
RegistryLock lock =
domainLockUtils.saveNewRegistryLockRequest(DOMAIN_NAME, "TheRegistrar", null, true);
domainLockUtils.verifyAndApplyLock(lock.getVerificationCode(), true);
domainLockUtils.administrativelyApplyUnlock(DOMAIN_NAME, "TheRegistrar", true);
verifyProperlyUnlockedDomain(true);
} }
@Test @Test
public void testFailure_createUnlock_alreadyPendingUnlock() { public void testFailure_createUnlock_alreadyPendingUnlock() {
RegistryLock lock = RegistryLock lock =
domainLockUtils.createRegistryLockRequest( domainLockUtils.saveNewRegistryLockRequest(DOMAIN_NAME, "TheRegistrar", POC_ID, false);
DOMAIN_NAME, "TheRegistrar", POC_ID, false, clock); domainLockUtils.verifyAndApplyLock(lock.getVerificationCode(), false);
domainLockUtils.verifyAndApplyLock(lock.getVerificationCode(), false, clock); domainLockUtils.saveNewRegistryUnlockRequest(DOMAIN_NAME, "TheRegistrar", false);
domainLockUtils.createRegistryUnlockRequest(DOMAIN_NAME, "TheRegistrar", false, clock);
assertThat( assertThat(
assertThrows( assertThrows(
IllegalArgumentException.class, IllegalArgumentException.class,
() -> () ->
domainLockUtils.createRegistryUnlockRequest( domainLockUtils.saveNewRegistryUnlockRequest(
DOMAIN_NAME, "TheRegistrar", false, clock))) DOMAIN_NAME, "TheRegistrar", false)))
.hasMessageThat() .hasMessageThat()
.isEqualTo("A pending unlock action already exists for example.tld"); .isEqualTo("A pending unlock action already exists for example.tld");
} }
@ -183,14 +200,14 @@ public final class DomainLockUtilsTest {
@Test @Test
public void testFailure_createUnlock_nonAdminUnlockingAdmin() { public void testFailure_createUnlock_nonAdminUnlockingAdmin() {
RegistryLock lock = RegistryLock lock =
domainLockUtils.createRegistryLockRequest(DOMAIN_NAME, "TheRegistrar", null, true, clock); domainLockUtils.saveNewRegistryLockRequest(DOMAIN_NAME, "TheRegistrar", null, true);
domainLockUtils.verifyAndApplyLock(lock.getVerificationCode(), true, clock); domainLockUtils.verifyAndApplyLock(lock.getVerificationCode(), true);
assertThat( assertThat(
assertThrows( assertThrows(
IllegalArgumentException.class, IllegalArgumentException.class,
() -> () ->
domainLockUtils.createRegistryUnlockRequest( domainLockUtils.saveNewRegistryUnlockRequest(
DOMAIN_NAME, "TheRegistrar", false, clock))) DOMAIN_NAME, "TheRegistrar", false)))
.hasMessageThat() .hasMessageThat()
.isEqualTo("Non-admin user cannot unlock admin-locked domain example.tld"); .isEqualTo("Non-admin user cannot unlock admin-locked domain example.tld");
} }
@ -201,21 +218,21 @@ public final class DomainLockUtilsTest {
assertThrows( assertThrows(
IllegalArgumentException.class, IllegalArgumentException.class,
() -> () ->
domainLockUtils.createRegistryLockRequest( domainLockUtils.saveNewRegistryLockRequest(
"asdf.tld", "TheRegistrar", POC_ID, false, clock))) "asdf.tld", "TheRegistrar", POC_ID, false)))
.hasMessageThat() .hasMessageThat()
.isEqualTo("Unknown domain asdf.tld"); .isEqualTo("Unknown domain asdf.tld");
} }
@Test @Test
public void testFailure_createLock_alreadyPendingLock() { public void testFailure_createLock_alreadyPendingLock() {
domainLockUtils.createRegistryLockRequest(DOMAIN_NAME, "TheRegistrar", POC_ID, false, clock); domainLockUtils.saveNewRegistryLockRequest(DOMAIN_NAME, "TheRegistrar", POC_ID, false);
assertThat( assertThat(
assertThrows( assertThrows(
IllegalArgumentException.class, IllegalArgumentException.class,
() -> () ->
domainLockUtils.createRegistryLockRequest( domainLockUtils.saveNewRegistryLockRequest(
DOMAIN_NAME, "TheRegistrar", POC_ID, false, clock))) DOMAIN_NAME, "TheRegistrar", POC_ID, false)))
.hasMessageThat() .hasMessageThat()
.isEqualTo("A pending or completed lock action already exists for example.tld"); .isEqualTo("A pending or completed lock action already exists for example.tld");
} }
@ -227,8 +244,8 @@ public final class DomainLockUtilsTest {
assertThrows( assertThrows(
IllegalArgumentException.class, IllegalArgumentException.class,
() -> () ->
domainLockUtils.createRegistryLockRequest( domainLockUtils.saveNewRegistryLockRequest(
DOMAIN_NAME, "TheRegistrar", POC_ID, false, clock))) DOMAIN_NAME, "TheRegistrar", POC_ID, false)))
.hasMessageThat() .hasMessageThat()
.isEqualTo("Domain example.tld is already locked"); .isEqualTo("Domain example.tld is already locked");
} }
@ -239,8 +256,8 @@ public final class DomainLockUtilsTest {
assertThrows( assertThrows(
IllegalArgumentException.class, IllegalArgumentException.class,
() -> () ->
domainLockUtils.createRegistryUnlockRequest( domainLockUtils.saveNewRegistryUnlockRequest(
DOMAIN_NAME, "TheRegistrar", false, clock))) DOMAIN_NAME, "TheRegistrar", false)))
.hasMessageThat() .hasMessageThat()
.isEqualTo("Domain example.tld is already unlocked"); .isEqualTo("Domain example.tld is already unlocked");
} }
@ -248,14 +265,13 @@ public final class DomainLockUtilsTest {
@Test @Test
public void testFailure_applyLock_alreadyApplied() { public void testFailure_applyLock_alreadyApplied() {
RegistryLock lock = RegistryLock lock =
domainLockUtils.createRegistryLockRequest( domainLockUtils.saveNewRegistryLockRequest(DOMAIN_NAME, "TheRegistrar", POC_ID, false);
DOMAIN_NAME, "TheRegistrar", POC_ID, false, clock); domainLockUtils.verifyAndApplyLock(lock.getVerificationCode(), false);
domainLockUtils.verifyAndApplyLock(lock.getVerificationCode(), false, clock);
domain = reloadDomain(); domain = reloadDomain();
assertThat( assertThat(
assertThrows( assertThrows(
IllegalArgumentException.class, IllegalArgumentException.class,
() -> domainLockUtils.verifyAndApplyLock(lock.getVerificationCode(), false, clock))) () -> domainLockUtils.verifyAndApplyLock(lock.getVerificationCode(), false)))
.hasMessageThat() .hasMessageThat()
.isEqualTo("Domain example.tld is already locked"); .isEqualTo("Domain example.tld is already locked");
assertNoDomainChanges(); assertNoDomainChanges();
@ -264,13 +280,12 @@ public final class DomainLockUtilsTest {
@Test @Test
public void testFailure_applyLock_expired() { public void testFailure_applyLock_expired() {
RegistryLock lock = RegistryLock lock =
domainLockUtils.createRegistryLockRequest( domainLockUtils.saveNewRegistryLockRequest(DOMAIN_NAME, "TheRegistrar", POC_ID, false);
DOMAIN_NAME, "TheRegistrar", POC_ID, false, clock);
clock.advanceBy(Duration.standardDays(1)); clock.advanceBy(Duration.standardDays(1));
assertThat( assertThat(
assertThrows( assertThrows(
IllegalArgumentException.class, IllegalArgumentException.class,
() -> domainLockUtils.verifyAndApplyLock(lock.getVerificationCode(), true, clock))) () -> domainLockUtils.verifyAndApplyLock(lock.getVerificationCode(), true)))
.hasMessageThat() .hasMessageThat()
.isEqualTo("The pending lock has expired; please try again"); .isEqualTo("The pending lock has expired; please try again");
assertNoDomainChanges(); assertNoDomainChanges();
@ -279,11 +294,11 @@ public final class DomainLockUtilsTest {
@Test @Test
public void testFailure_applyLock_nonAdmin_applyAdminLock() { public void testFailure_applyLock_nonAdmin_applyAdminLock() {
RegistryLock lock = RegistryLock lock =
domainLockUtils.createRegistryLockRequest(DOMAIN_NAME, "TheRegistrar", null, true, clock); domainLockUtils.saveNewRegistryLockRequest(DOMAIN_NAME, "TheRegistrar", null, true);
assertThat( assertThat(
assertThrows( assertThrows(
IllegalArgumentException.class, IllegalArgumentException.class,
() -> domainLockUtils.verifyAndApplyLock(lock.getVerificationCode(), false, clock))) () -> domainLockUtils.verifyAndApplyLock(lock.getVerificationCode(), false)))
.hasMessageThat() .hasMessageThat()
.isEqualTo("Non-admin user cannot complete admin lock"); .isEqualTo("Non-admin user cannot complete admin lock");
assertNoDomainChanges(); assertNoDomainChanges();
@ -292,19 +307,16 @@ public final class DomainLockUtilsTest {
@Test @Test
public void testFailure_applyUnlock_alreadyUnlocked() { public void testFailure_applyUnlock_alreadyUnlocked() {
RegistryLock lock = RegistryLock lock =
domainLockUtils.createRegistryLockRequest( domainLockUtils.saveNewRegistryLockRequest(DOMAIN_NAME, "TheRegistrar", POC_ID, false);
DOMAIN_NAME, "TheRegistrar", POC_ID, false, clock); domainLockUtils.verifyAndApplyLock(lock.getVerificationCode(), false);
domainLockUtils.verifyAndApplyLock(lock.getVerificationCode(), false, clock);
RegistryLock unlock = RegistryLock unlock =
domainLockUtils.createRegistryUnlockRequest(DOMAIN_NAME, "TheRegistrar", false, clock); domainLockUtils.saveNewRegistryUnlockRequest(DOMAIN_NAME, "TheRegistrar", false);
domainLockUtils.verifyAndApplyUnlock(unlock.getVerificationCode(), false, clock); domainLockUtils.verifyAndApplyUnlock(unlock.getVerificationCode(), false);
assertThat( assertThat(
assertThrows( assertThrows(
IllegalArgumentException.class, IllegalArgumentException.class,
() -> () -> domainLockUtils.verifyAndApplyUnlock(unlock.getVerificationCode(), false)))
domainLockUtils.verifyAndApplyUnlock(
unlock.getVerificationCode(), false, clock)))
.hasMessageThat() .hasMessageThat()
.isEqualTo("Domain example.tld is already unlocked"); .isEqualTo("Domain example.tld is already unlocked");
assertNoDomainChanges(); assertNoDomainChanges();
@ -313,26 +325,57 @@ public final class DomainLockUtilsTest {
@Test @Test
public void testFailure_applyLock_alreadyLocked() { public void testFailure_applyLock_alreadyLocked() {
RegistryLock lock = RegistryLock lock =
domainLockUtils.createRegistryLockRequest( domainLockUtils.saveNewRegistryLockRequest(DOMAIN_NAME, "TheRegistrar", POC_ID, false);
DOMAIN_NAME, "TheRegistrar", POC_ID, false, clock);
String verificationCode = lock.getVerificationCode(); String verificationCode = lock.getVerificationCode();
// reload to pick up modification times, etc // reload to pick up modification times, etc
lock = RegistryLockDao.getByVerificationCode(verificationCode).get(); lock = getRegistryLockByVerificationCode(verificationCode).get();
domain = persistResource(domain.asBuilder().setStatusValues(REGISTRY_LOCK_STATUSES).build()); domain = persistResource(domain.asBuilder().setStatusValues(REGISTRY_LOCK_STATUSES).build());
assertThat( assertThat(
assertThrows( assertThrows(
IllegalArgumentException.class, IllegalArgumentException.class,
() -> domainLockUtils.verifyAndApplyLock(verificationCode, false, clock))) () -> domainLockUtils.verifyAndApplyLock(verificationCode, false)))
.hasMessageThat() .hasMessageThat()
.isEqualTo("Domain example.tld is already locked"); .isEqualTo("Domain example.tld is already locked");
// Failure during Datastore portion shouldn't affect the SQL object // Failure during Datastore portion shouldn't affect the SQL object
RegistryLock afterAction = RegistryLock afterAction = getRegistryLockByVerificationCode(lock.getVerificationCode()).get();
RegistryLockDao.getByVerificationCode(lock.getVerificationCode()).get();
assertThat(afterAction).isEqualTo(lock); assertThat(afterAction).isEqualTo(lock);
assertNoDomainChanges(); assertNoDomainChanges();
} }
private void verifyProperlyLockedDomain(boolean isAdmin) {
assertThat(reloadDomain().getStatusValues()).containsAtLeastElementsIn(REGISTRY_LOCK_STATUSES);
HistoryEntry historyEntry = getOnlyHistoryEntryOfType(domain, HistoryEntry.Type.DOMAIN_UPDATE);
assertThat(historyEntry.getRequestedByRegistrar()).isEqualTo(!isAdmin);
assertThat(historyEntry.getBySuperuser()).isEqualTo(isAdmin);
assertThat(historyEntry.getReason())
.isEqualTo("Lock of a domain through a RegistryLock operation");
if (isAdmin) {
assertNoBillingEvents();
} else {
assertBillingEvent(historyEntry);
}
}
private void verifyProperlyUnlockedDomain(boolean isAdmin) {
assertThat(reloadDomain().getStatusValues()).containsNoneIn(REGISTRY_LOCK_STATUSES);
ImmutableList<HistoryEntry> historyEntries =
getHistoryEntriesOfType(domain, HistoryEntry.Type.DOMAIN_UPDATE);
assertThat(historyEntries.size()).isEqualTo(2);
historyEntries.forEach(
entry -> {
assertThat(entry.getRequestedByRegistrar()).isEqualTo(!isAdmin);
assertThat(entry.getBySuperuser()).isEqualTo(isAdmin);
assertThat(entry.getReason())
.contains("ock of a domain through a RegistryLock operation");
});
if (isAdmin) {
assertNoBillingEvents();
} else {
assertBillingEvents(historyEntries);
}
}
private DomainBase reloadDomain() { private DomainBase reloadDomain() {
return ofy().load().entity(domain).now(); return ofy().load().entity(domain).now();
} }

View file

@ -21,17 +21,16 @@ import static google.registry.testing.DatastoreHelper.newDomainBase;
import static google.registry.testing.DatastoreHelper.persistActiveDomain; import static google.registry.testing.DatastoreHelper.persistActiveDomain;
import static google.registry.testing.DatastoreHelper.persistNewRegistrar; import static google.registry.testing.DatastoreHelper.persistNewRegistrar;
import static google.registry.testing.DatastoreHelper.persistResource; import static google.registry.testing.DatastoreHelper.persistResource;
import static google.registry.testing.SqlHelper.getMostRecentRegistryLockByRepoId;
import static google.registry.tools.LockOrUnlockDomainCommand.REGISTRY_LOCK_STATUSES; import static google.registry.tools.LockOrUnlockDomainCommand.REGISTRY_LOCK_STATUSES;
import static org.junit.Assert.assertThrows; import static org.junit.Assert.assertThrows;
import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableList;
import google.registry.model.domain.DomainBase; import google.registry.model.domain.DomainBase;
import google.registry.model.registrar.Registrar.Type; import google.registry.model.registrar.Registrar.Type;
import google.registry.model.registry.RegistryLockDao;
import google.registry.persistence.transaction.JpaTestRules; import google.registry.persistence.transaction.JpaTestRules;
import google.registry.persistence.transaction.JpaTestRules.JpaIntegrationWithCoverageRule; import google.registry.persistence.transaction.JpaTestRules.JpaIntegrationWithCoverageRule;
import google.registry.testing.DeterministicStringGenerator; import google.registry.testing.DeterministicStringGenerator;
import google.registry.testing.FakeClock;
import google.registry.util.StringGenerator.Alphabets; import google.registry.util.StringGenerator.Alphabets;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
@ -52,7 +51,6 @@ public class LockDomainCommandTest extends CommandTestCase<LockDomainCommand> {
persistNewRegistrar("adminreg", "Admin Registrar", Type.REAL, 693L); persistNewRegistrar("adminreg", "Admin Registrar", Type.REAL, 693L);
createTld("tld"); createTld("tld");
command.registryAdminClientId = "adminreg"; command.registryAdminClientId = "adminreg";
command.clock = new FakeClock();
command.domainLockUtils = command.domainLockUtils =
new DomainLockUtils(new DeterministicStringGenerator(Alphabets.BASE_58)); new DomainLockUtils(new DeterministicStringGenerator(Alphabets.BASE_58));
} }
@ -126,7 +124,7 @@ public class LockDomainCommandTest extends CommandTestCase<LockDomainCommand> {
public void testSuccess_defaultsToAdminRegistrar_ifUnspecified() throws Exception { public void testSuccess_defaultsToAdminRegistrar_ifUnspecified() throws Exception {
DomainBase domain = persistActiveDomain("example.tld"); DomainBase domain = persistActiveDomain("example.tld");
runCommandForced("example.tld"); runCommandForced("example.tld");
assertThat(RegistryLockDao.getMostRecentByRepoId(domain.getRepoId()).get().getRegistrarId()) assertThat(getMostRecentRegistryLockByRepoId(domain.getRepoId()).get().getRegistrarId())
.isEqualTo("adminreg"); .isEqualTo("adminreg");
} }

View file

@ -22,6 +22,7 @@ import static google.registry.testing.DatastoreHelper.newDomainBase;
import static google.registry.testing.DatastoreHelper.persistActiveDomain; import static google.registry.testing.DatastoreHelper.persistActiveDomain;
import static google.registry.testing.DatastoreHelper.persistNewRegistrar; import static google.registry.testing.DatastoreHelper.persistNewRegistrar;
import static google.registry.testing.DatastoreHelper.persistResource; import static google.registry.testing.DatastoreHelper.persistResource;
import static google.registry.testing.SqlHelper.getMostRecentRegistryLockByRepoId;
import static google.registry.tools.LockOrUnlockDomainCommand.REGISTRY_LOCK_STATUSES; import static google.registry.tools.LockOrUnlockDomainCommand.REGISTRY_LOCK_STATUSES;
import static org.junit.Assert.assertThrows; import static org.junit.Assert.assertThrows;
@ -29,12 +30,10 @@ import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSet;
import google.registry.model.domain.DomainBase; import google.registry.model.domain.DomainBase;
import google.registry.model.registrar.Registrar.Type; import google.registry.model.registrar.Registrar.Type;
import google.registry.model.registry.RegistryLockDao;
import google.registry.persistence.transaction.JpaTestRules; import google.registry.persistence.transaction.JpaTestRules;
import google.registry.persistence.transaction.JpaTestRules.JpaIntegrationWithCoverageRule; import google.registry.persistence.transaction.JpaTestRules.JpaIntegrationWithCoverageRule;
import google.registry.schema.domain.RegistryLock; import google.registry.schema.domain.RegistryLock;
import google.registry.testing.DeterministicStringGenerator; import google.registry.testing.DeterministicStringGenerator;
import google.registry.testing.FakeClock;
import google.registry.util.StringGenerator.Alphabets; import google.registry.util.StringGenerator.Alphabets;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
@ -55,7 +54,6 @@ public class UnlockDomainCommandTest extends CommandTestCase<UnlockDomainCommand
persistNewRegistrar("adminreg", "Admin Registrar", Type.REAL, 693L); persistNewRegistrar("adminreg", "Admin Registrar", Type.REAL, 693L);
createTld("tld"); createTld("tld");
command.registryAdminClientId = "adminreg"; command.registryAdminClientId = "adminreg";
command.clock = new FakeClock();
command.domainLockUtils = command.domainLockUtils =
new DomainLockUtils(new DeterministicStringGenerator(Alphabets.BASE_58)); new DomainLockUtils(new DeterministicStringGenerator(Alphabets.BASE_58));
} }
@ -63,9 +61,8 @@ public class UnlockDomainCommandTest extends CommandTestCase<UnlockDomainCommand
private DomainBase persistLockedDomain(String domainName, String registrarId) { private DomainBase persistLockedDomain(String domainName, String registrarId) {
DomainBase domain = persistResource(newDomainBase(domainName)); DomainBase domain = persistResource(newDomainBase(domainName));
RegistryLock lock = RegistryLock lock =
command.domainLockUtils.createRegistryLockRequest( command.domainLockUtils.saveNewRegistryLockRequest(domainName, registrarId, null, true);
domainName, registrarId, null, true, command.clock); command.domainLockUtils.verifyAndApplyLock(lock.getVerificationCode(), true);
command.domainLockUtils.verifyAndApplyLock(lock.getVerificationCode(), true, command.clock);
return reloadResource(domain); return reloadResource(domain);
} }
@ -132,7 +129,7 @@ public class UnlockDomainCommandTest extends CommandTestCase<UnlockDomainCommand
public void testSuccess_defaultsToAdminRegistrar_ifUnspecified() throws Exception { public void testSuccess_defaultsToAdminRegistrar_ifUnspecified() throws Exception {
DomainBase domain = persistLockedDomain("example.tld", "NewRegistrar"); DomainBase domain = persistLockedDomain("example.tld", "NewRegistrar");
runCommandForced("example.tld"); runCommandForced("example.tld");
assertThat(RegistryLockDao.getMostRecentByRepoId(domain.getRepoId()).get().getRegistrarId()) assertThat(getMostRecentRegistryLockByRepoId(domain.getRepoId()).get().getRegistrarId())
.isEqualTo("adminreg"); .isEqualTo("adminreg");
} }

View file

@ -20,6 +20,10 @@ import static google.registry.testing.DatastoreHelper.persistActiveDomain;
import static google.registry.testing.DatastoreHelper.persistDeletedDomain; import static google.registry.testing.DatastoreHelper.persistDeletedDomain;
import static google.registry.testing.DatastoreHelper.persistNewRegistrar; import static google.registry.testing.DatastoreHelper.persistNewRegistrar;
import static google.registry.testing.DatastoreHelper.persistResource; import static google.registry.testing.DatastoreHelper.persistResource;
import static google.registry.testing.SqlHelper.getMostRecentRegistryLockByRepoId;
import static google.registry.testing.SqlHelper.getMostRecentVerifiedRegistryLockByRepoId;
import static google.registry.testing.SqlHelper.getRegistryLocksByRegistrarId;
import static google.registry.testing.SqlHelper.saveRegistryLock;
import static google.registry.tools.LockOrUnlockDomainCommand.REGISTRY_LOCK_STATUSES; import static google.registry.tools.LockOrUnlockDomainCommand.REGISTRY_LOCK_STATUSES;
import static org.junit.Assert.assertThrows; import static org.junit.Assert.assertThrows;
@ -29,7 +33,6 @@ import com.google.common.collect.Iterables;
import com.google.common.truth.Truth8; import com.google.common.truth.Truth8;
import google.registry.model.domain.DomainBase; import google.registry.model.domain.DomainBase;
import google.registry.model.registrar.Registrar; import google.registry.model.registrar.Registrar;
import google.registry.model.registry.RegistryLockDao;
import google.registry.model.reporting.HistoryEntry; import google.registry.model.reporting.HistoryEntry;
import google.registry.persistence.transaction.JpaTestRules; import google.registry.persistence.transaction.JpaTestRules;
import google.registry.persistence.transaction.JpaTestRules.JpaIntegrationWithCoverageRule; import google.registry.persistence.transaction.JpaTestRules.JpaIntegrationWithCoverageRule;
@ -56,7 +59,7 @@ public class BackfillRegistryLocksCommandTest
@Rule @Rule
public final JpaIntegrationWithCoverageRule jpaRule = public final JpaIntegrationWithCoverageRule jpaRule =
new JpaTestRules.Builder().buildIntegrationWithCoverageRule(); new JpaTestRules.Builder().withClock(fakeClock).buildIntegrationWithCoverageRule();
@Before @Before
public void before() { public void before() {
@ -70,11 +73,11 @@ public class BackfillRegistryLocksCommandTest
@Test @Test
public void testSimpleBackfill() throws Exception { public void testSimpleBackfill() throws Exception {
DomainBase domain = persistLockedDomain("example.tld"); DomainBase domain = persistLockedDomain("example.tld");
Truth8.assertThat(RegistryLockDao.getMostRecentByRepoId(domain.getRepoId())).isEmpty(); Truth8.assertThat(getMostRecentRegistryLockByRepoId(domain.getRepoId())).isEmpty();
runCommandForced("--domain_roids", domain.getRepoId()); runCommandForced("--domain_roids", domain.getRepoId());
Optional<RegistryLock> lockOptional = RegistryLockDao.getMostRecentByRepoId(domain.getRepoId()); Optional<RegistryLock> lockOptional = getMostRecentRegistryLockByRepoId(domain.getRepoId());
Truth8.assertThat(lockOptional).isPresent(); Truth8.assertThat(lockOptional).isPresent();
Truth8.assertThat(lockOptional.get().getLockCompletionTimestamp()).isPresent(); Truth8.assertThat(lockOptional.get().getLockCompletionTimestamp()).isPresent();
} }
@ -94,7 +97,7 @@ public class BackfillRegistryLocksCommandTest
previouslyLockedDomain.getRepoId(), previouslyLockedDomain.getRepoId(),
lockedDomain.getRepoId())); lockedDomain.getRepoId()));
ImmutableList<RegistryLock> locks = RegistryLockDao.getLockedDomainsByRegistrarId("adminreg"); ImmutableList<RegistryLock> locks = getRegistryLocksByRegistrarId("adminreg");
assertThat(locks).hasSize(1); assertThat(locks).hasSize(1);
assertThat(Iterables.getOnlyElement(locks).getDomainName()).isEqualTo("locked.tld"); assertThat(Iterables.getOnlyElement(locks).getDomainName()).isEqualTo("locked.tld");
} }
@ -105,7 +108,7 @@ public class BackfillRegistryLocksCommandTest
persistResource(domain.asBuilder().setStatusValues(REGISTRY_LOCK_STATUSES).build()); persistResource(domain.asBuilder().setStatusValues(REGISTRY_LOCK_STATUSES).build());
fakeClock.advanceBy(Duration.standardSeconds(1)); fakeClock.advanceBy(Duration.standardSeconds(1));
runCommandForced("--domain_roids", domain.getRepoId()); runCommandForced("--domain_roids", domain.getRepoId());
Truth8.assertThat(RegistryLockDao.getMostRecentByRepoId(domain.getRepoId())).isEmpty(); Truth8.assertThat(getMostRecentRegistryLockByRepoId(domain.getRepoId())).isEmpty();
} }
@Test @Test
@ -113,7 +116,7 @@ public class BackfillRegistryLocksCommandTest
DomainBase domain = persistLockedDomain("example.tld"); DomainBase domain = persistLockedDomain("example.tld");
RegistryLock previousLock = RegistryLock previousLock =
RegistryLockDao.save( saveRegistryLock(
new RegistryLock.Builder() new RegistryLock.Builder()
.isSuperuser(true) .isSuperuser(true)
.setRegistrarId("adminreg") .setRegistrarId("adminreg")
@ -127,7 +130,7 @@ public class BackfillRegistryLocksCommandTest
runCommandForced("--domain_roids", domain.getRepoId()); runCommandForced("--domain_roids", domain.getRepoId());
assertThat( assertThat(
RegistryLockDao.getMostRecentByRepoId(domain.getRepoId()) getMostRecentRegistryLockByRepoId(domain.getRepoId())
.get() .get()
.getLockCompletionTimestamp()) .getLockCompletionTimestamp())
.isEqualTo(previousLock.getLockCompletionTimestamp()); .isEqualTo(previousLock.getLockCompletionTimestamp());
@ -154,11 +157,10 @@ public class BackfillRegistryLocksCommandTest
runCommandForced( runCommandForced(
"--domain_roids", String.format("%s,%s", ursDomain.getRepoId(), nonUrsDomain.getRepoId())); "--domain_roids", String.format("%s,%s", ursDomain.getRepoId(), nonUrsDomain.getRepoId()));
RegistryLock ursLock = RegistryLock ursLock = getMostRecentVerifiedRegistryLockByRepoId(ursDomain.getRepoId()).get();
RegistryLockDao.getMostRecentVerifiedLockByRepoId(ursDomain.getRepoId()).get();
assertThat(ursLock.getLockCompletionTimestamp().get()).isEqualTo(ursTime); assertThat(ursLock.getLockCompletionTimestamp().get()).isEqualTo(ursTime);
RegistryLock nonUrsLock = RegistryLock nonUrsLock =
RegistryLockDao.getMostRecentVerifiedLockByRepoId(nonUrsDomain.getRepoId()).get(); getMostRecentVerifiedRegistryLockByRepoId(nonUrsDomain.getRepoId()).get();
assertThat(nonUrsLock.getLockCompletionTimestamp().get()).isEqualTo(fakeClock.nowUtc()); assertThat(nonUrsLock.getLockCompletionTimestamp().get()).isEqualTo(fakeClock.nowUtc());
} }

View file

@ -20,6 +20,7 @@ import static google.registry.request.auth.AuthenticatedRegistrarAccessor.Role.O
import static google.registry.testing.AppEngineRule.makeRegistrar2; import static google.registry.testing.AppEngineRule.makeRegistrar2;
import static google.registry.testing.AppEngineRule.makeRegistrarContact3; import static google.registry.testing.AppEngineRule.makeRegistrarContact3;
import static google.registry.testing.DatastoreHelper.persistResource; import static google.registry.testing.DatastoreHelper.persistResource;
import static google.registry.testing.SqlHelper.saveRegistryLock;
import static javax.servlet.http.HttpServletResponse.SC_FORBIDDEN; import static javax.servlet.http.HttpServletResponse.SC_FORBIDDEN;
import static javax.servlet.http.HttpServletResponse.SC_INTERNAL_SERVER_ERROR; import static javax.servlet.http.HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
import static org.junit.Assert.assertThrows; import static org.junit.Assert.assertThrows;
@ -30,7 +31,6 @@ import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSetMultimap; import com.google.common.collect.ImmutableSetMultimap;
import com.google.gson.Gson; import com.google.gson.Gson;
import google.registry.model.registry.RegistryLockDao;
import google.registry.persistence.transaction.JpaTestRules; import google.registry.persistence.transaction.JpaTestRules;
import google.registry.persistence.transaction.JpaTestRules.JpaIntegrationWithCoverageRule; import google.registry.persistence.transaction.JpaTestRules.JpaIntegrationWithCoverageRule;
import google.registry.request.Action.Method; import google.registry.request.Action.Method;
@ -132,10 +132,10 @@ public final class RegistryLockGetActionTest {
.setUnlockCompletionTimestamp(fakeClock.nowUtc()) .setUnlockCompletionTimestamp(fakeClock.nowUtc())
.build(); .build();
RegistryLockDao.save(regularLock); saveRegistryLock(regularLock);
RegistryLockDao.save(adminLock); saveRegistryLock(adminLock);
RegistryLockDao.save(incompleteLock); saveRegistryLock(incompleteLock);
RegistryLockDao.save(unlockedLock); saveRegistryLock(unlockedLock);
action.run(); action.run();
assertThat(response.getStatus()).isEqualTo(HttpStatusCodes.STATUS_CODE_OK); assertThat(response.getStatus()).isEqualTo(HttpStatusCodes.STATUS_CODE_OK);

View file

@ -20,6 +20,8 @@ import static google.registry.testing.DatastoreHelper.createTld;
import static google.registry.testing.DatastoreHelper.loadRegistrar; import static google.registry.testing.DatastoreHelper.loadRegistrar;
import static google.registry.testing.DatastoreHelper.newDomainBase; import static google.registry.testing.DatastoreHelper.newDomainBase;
import static google.registry.testing.DatastoreHelper.persistResource; import static google.registry.testing.DatastoreHelper.persistResource;
import static google.registry.testing.SqlHelper.getRegistryLockByVerificationCode;
import static google.registry.testing.SqlHelper.saveRegistryLock;
import static google.registry.tools.LockOrUnlockDomainCommand.REGISTRY_LOCK_STATUSES; import static google.registry.tools.LockOrUnlockDomainCommand.REGISTRY_LOCK_STATUSES;
import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.verifyNoMoreInteractions;
@ -29,7 +31,6 @@ import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSetMultimap; import com.google.common.collect.ImmutableSetMultimap;
import google.registry.model.domain.DomainBase; import google.registry.model.domain.DomainBase;
import google.registry.model.registry.RegistryLockDao;
import google.registry.persistence.transaction.JpaTestRules; import google.registry.persistence.transaction.JpaTestRules;
import google.registry.persistence.transaction.JpaTestRules.JpaIntegrationTestRule; import google.registry.persistence.transaction.JpaTestRules.JpaIntegrationTestRule;
import google.registry.request.JsonActionRunner; import google.registry.request.JsonActionRunner;
@ -71,11 +72,13 @@ public final class RegistryLockPostActionTest {
+ "https:\\/\\/localhost\\/registry-lock-verify\\?lockVerificationCode=" + "https:\\/\\/localhost\\/registry-lock-verify\\?lockVerificationCode="
+ "[0-9a-zA-Z_\\-]+&isLock=(true|false)"; + "[0-9a-zA-Z_\\-]+&isLock=(true|false)";
private final FakeClock clock = new FakeClock();
@Rule public final AppEngineRule appEngineRule = AppEngineRule.builder().withDatastore().build(); @Rule public final AppEngineRule appEngineRule = AppEngineRule.builder().withDatastore().build();
@Rule @Rule
public final JpaIntegrationTestRule jpaRule = public final JpaIntegrationTestRule jpaRule =
new JpaTestRules.Builder().buildIntegrationTestRule(); new JpaTestRules.Builder().withClock(clock).buildIntegrationTestRule();
@Rule public final MockitoRule mocks = MockitoJUnit.rule(); @Rule public final MockitoRule mocks = MockitoJUnit.rule();
@ -84,7 +87,6 @@ public final class RegistryLockPostActionTest {
// Marla Singer has registry lock auth permissions // Marla Singer has registry lock auth permissions
private final User userWithLockPermission = private final User userWithLockPermission =
new User("Marla.Singer@crr.com", "gmail.com", "31337"); new User("Marla.Singer@crr.com", "gmail.com", "31337");
private final FakeClock clock = new FakeClock();
private InternetAddress outgoingAddress; private InternetAddress outgoingAddress;
private DomainBase domain; private DomainBase domain;
@ -112,8 +114,7 @@ public final class RegistryLockPostActionTest {
@Test @Test
public void testSuccess_unlock() throws Exception { public void testSuccess_unlock() throws Exception {
RegistryLockDao.save( saveRegistryLock(createLock().asBuilder().setLockCompletionTimestamp(clock.nowUtc()).build());
createLock().asBuilder().setLockCompletionTimestamp(clock.nowUtc()).build());
persistResource(domain.asBuilder().setStatusValues(REGISTRY_LOCK_STATUSES).build()); persistResource(domain.asBuilder().setStatusValues(REGISTRY_LOCK_STATUSES).build());
Map<String, ?> response = action.handleJsonRequest(unlockRequest()); Map<String, ?> response = action.handleJsonRequest(unlockRequest());
assertSuccess(response, "unlock", "Marla.Singer@crr.com"); assertSuccess(response, "unlock", "Marla.Singer@crr.com");
@ -121,7 +122,7 @@ public final class RegistryLockPostActionTest {
@Test @Test
public void testSuccess_unlock_adminUnlockingAdmin() throws Exception { public void testSuccess_unlock_adminUnlockingAdmin() throws Exception {
RegistryLockDao.save( saveRegistryLock(
createLock() createLock()
.asBuilder() .asBuilder()
.isSuperuser(true) .isSuperuser(true)
@ -146,7 +147,7 @@ public final class RegistryLockPostActionTest {
@Test @Test
public void testFailure_unlock_alreadyUnlocked() { public void testFailure_unlock_alreadyUnlocked() {
persistResource(domain.asBuilder().setStatusValues(REGISTRY_LOCK_STATUSES).build()); persistResource(domain.asBuilder().setStatusValues(REGISTRY_LOCK_STATUSES).build());
RegistryLockDao.save( saveRegistryLock(
createLock() createLock()
.asBuilder() .asBuilder()
.setLockCompletionTimestamp(clock.nowUtc()) .setLockCompletionTimestamp(clock.nowUtc())
@ -158,7 +159,7 @@ public final class RegistryLockPostActionTest {
@Test @Test
public void testFailure_unlock_nonAdminUnlockingAdmin() { public void testFailure_unlock_nonAdminUnlockingAdmin() {
RegistryLockDao.save( saveRegistryLock(
createLock() createLock()
.asBuilder() .asBuilder()
.isSuperuser(true) .isSuperuser(true)
@ -291,7 +292,7 @@ public final class RegistryLockPostActionTest {
@Test @Test
public void testSuccess_previousLockUnlocked() throws Exception { public void testSuccess_previousLockUnlocked() throws Exception {
RegistryLockDao.save( saveRegistryLock(
createLock() createLock()
.asBuilder() .asBuilder()
.setLockCompletionTimestamp(clock.nowUtc().minusMinutes(1)) .setLockCompletionTimestamp(clock.nowUtc().minusMinutes(1))
@ -305,8 +306,9 @@ public final class RegistryLockPostActionTest {
@Test @Test
public void testSuccess_previousLockExpired() throws Exception { public void testSuccess_previousLockExpired() throws Exception {
RegistryLock previousLock = RegistryLockDao.save(createLock()); RegistryLock previousLock = saveRegistryLock(createLock());
previousLock = RegistryLockDao.getByVerificationCode(previousLock.getVerificationCode()).get(); String verificationCode = previousLock.getVerificationCode();
previousLock = getRegistryLockByVerificationCode(verificationCode).get();
clock.setTo(previousLock.getLockRequestTimestamp().plusHours(2)); clock.setTo(previousLock.getLockRequestTimestamp().plusHours(2));
Map<String, ?> response = action.handleJsonRequest(lockRequest()); Map<String, ?> response = action.handleJsonRequest(lockRequest());
assertSuccess(response, "lock", "Marla.Singer@crr.com"); assertSuccess(response, "lock", "Marla.Singer@crr.com");
@ -314,7 +316,7 @@ public final class RegistryLockPostActionTest {
@Test @Test
public void testFailure_alreadyPendingLock() { public void testFailure_alreadyPendingLock() {
RegistryLockDao.save(createLock()); saveRegistryLock(createLock());
Map<String, ?> response = action.handleJsonRequest(lockRequest()); Map<String, ?> response = action.handleJsonRequest(lockRequest());
assertFailureWithMessage( assertFailureWithMessage(
response, "A pending or completed lock action already exists for example.tld"); response, "A pending or completed lock action already exists for example.tld");
@ -400,7 +402,6 @@ public final class RegistryLockPostActionTest {
authResult, authResult,
registrarAccessor, registrarAccessor,
emailService, emailService,
clock,
domainLockUtils, domainLockUtils,
outgoingAddress); outgoingAddress);
} }

View file

@ -21,6 +21,8 @@ import static google.registry.testing.DatastoreHelper.getOnlyHistoryEntryOfType;
import static google.registry.testing.DatastoreHelper.newDomainBase; import static google.registry.testing.DatastoreHelper.newDomainBase;
import static google.registry.testing.DatastoreHelper.persistActiveHost; import static google.registry.testing.DatastoreHelper.persistActiveHost;
import static google.registry.testing.DatastoreHelper.persistResource; import static google.registry.testing.DatastoreHelper.persistResource;
import static google.registry.testing.SqlHelper.getRegistryLockByVerificationCode;
import static google.registry.testing.SqlHelper.saveRegistryLock;
import static google.registry.tools.LockOrUnlockDomainCommand.REGISTRY_LOCK_STATUSES; import static google.registry.tools.LockOrUnlockDomainCommand.REGISTRY_LOCK_STATUSES;
import static javax.servlet.http.HttpServletResponse.SC_MOVED_TEMPORARILY; import static javax.servlet.http.HttpServletResponse.SC_MOVED_TEMPORARILY;
import static javax.servlet.http.HttpServletResponse.SC_OK; import static javax.servlet.http.HttpServletResponse.SC_OK;
@ -36,7 +38,6 @@ import google.registry.model.billing.BillingEvent.Reason;
import google.registry.model.domain.DomainBase; import google.registry.model.domain.DomainBase;
import google.registry.model.host.HostResource; import google.registry.model.host.HostResource;
import google.registry.model.registry.Registry; import google.registry.model.registry.Registry;
import google.registry.model.registry.RegistryLockDao;
import google.registry.model.reporting.HistoryEntry; import google.registry.model.reporting.HistoryEntry;
import google.registry.persistence.transaction.JpaTestRules; import google.registry.persistence.transaction.JpaTestRules;
import google.registry.persistence.transaction.JpaTestRules.JpaIntegrationWithCoverageRule; import google.registry.persistence.transaction.JpaTestRules.JpaIntegrationWithCoverageRule;
@ -104,7 +105,7 @@ public final class RegistryLockVerifyActionTest {
@Test @Test
public void testSuccess_lockDomain() { public void testSuccess_lockDomain() {
RegistryLockDao.save(createLock()); saveRegistryLock(createLock());
action.run(); action.run();
assertThat(response.getStatus()).isEqualTo(SC_OK); assertThat(response.getStatus()).isEqualTo(SC_OK);
assertThat(reloadDomain().getStatusValues()).containsExactlyElementsIn(REGISTRY_LOCK_STATUSES); assertThat(reloadDomain().getStatusValues()).containsExactlyElementsIn(REGISTRY_LOCK_STATUSES);
@ -113,7 +114,7 @@ public final class RegistryLockVerifyActionTest {
assertThat(historyEntry.getRequestedByRegistrar()).isTrue(); assertThat(historyEntry.getRequestedByRegistrar()).isTrue();
assertThat(historyEntry.getBySuperuser()).isFalse(); assertThat(historyEntry.getBySuperuser()).isFalse();
assertThat(historyEntry.getReason()) assertThat(historyEntry.getReason())
.isEqualTo("Lock or unlock of a domain through a RegistryLock operation"); .isEqualTo("Lock of a domain through a RegistryLock operation");
assertBillingEvent(historyEntry); assertBillingEvent(historyEntry);
} }
@ -121,7 +122,7 @@ public final class RegistryLockVerifyActionTest {
public void testSuccess_unlockDomain() { public void testSuccess_unlockDomain() {
action = createAction(lockId, false); action = createAction(lockId, false);
domain = persistResource(domain.asBuilder().setStatusValues(REGISTRY_LOCK_STATUSES).build()); domain = persistResource(domain.asBuilder().setStatusValues(REGISTRY_LOCK_STATUSES).build());
RegistryLockDao.save( saveRegistryLock(
createLock().asBuilder().setUnlockRequestTimestamp(fakeClock.nowUtc()).build()); createLock().asBuilder().setUnlockRequestTimestamp(fakeClock.nowUtc()).build());
action.run(); action.run();
assertThat(response.getStatus()).isEqualTo(SC_OK); assertThat(response.getStatus()).isEqualTo(SC_OK);
@ -131,14 +132,14 @@ public final class RegistryLockVerifyActionTest {
assertThat(historyEntry.getRequestedByRegistrar()).isTrue(); assertThat(historyEntry.getRequestedByRegistrar()).isTrue();
assertThat(historyEntry.getBySuperuser()).isFalse(); assertThat(historyEntry.getBySuperuser()).isFalse();
assertThat(historyEntry.getReason()) assertThat(historyEntry.getReason())
.isEqualTo("Lock or unlock of a domain through a RegistryLock operation"); .isEqualTo("Unlock of a domain through a RegistryLock operation");
assertBillingEvent(historyEntry); assertBillingEvent(historyEntry);
} }
@Test @Test
public void testSuccess_adminLock_createsOnlyHistoryEntry() { public void testSuccess_adminLock_createsOnlyHistoryEntry() {
action.authResult = AuthResult.create(AuthLevel.USER, UserAuthInfo.create(user, true)); action.authResult = AuthResult.create(AuthLevel.USER, UserAuthInfo.create(user, true));
RegistryLockDao.save(createLock().asBuilder().isSuperuser(true).build()); saveRegistryLock(createLock().asBuilder().isSuperuser(true).build());
action.run(); action.run();
HistoryEntry historyEntry = getOnlyHistoryEntryOfType(domain, HistoryEntry.Type.DOMAIN_UPDATE); HistoryEntry historyEntry = getOnlyHistoryEntryOfType(domain, HistoryEntry.Type.DOMAIN_UPDATE);
@ -149,7 +150,7 @@ public final class RegistryLockVerifyActionTest {
@Test @Test
public void testFailure_badVerificationCode() { public void testFailure_badVerificationCode() {
RegistryLockDao.save( saveRegistryLock(
createLock().asBuilder().setVerificationCode("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA").build()); createLock().asBuilder().setVerificationCode("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA").build());
action.run(); action.run();
assertThat(response.getPayload()).contains("Failed: Invalid verification code"); assertThat(response.getPayload()).contains("Failed: Invalid verification code");
@ -158,7 +159,7 @@ public final class RegistryLockVerifyActionTest {
@Test @Test
public void testFailure_alreadyVerified() { public void testFailure_alreadyVerified() {
RegistryLockDao.save( saveRegistryLock(
createLock().asBuilder().setLockCompletionTimestamp(fakeClock.nowUtc()).build()); createLock().asBuilder().setLockCompletionTimestamp(fakeClock.nowUtc()).build());
action.run(); action.run();
assertThat(response.getPayload()).contains("Failed: Domain example.tld is already locked"); assertThat(response.getPayload()).contains("Failed: Domain example.tld is already locked");
@ -167,7 +168,7 @@ public final class RegistryLockVerifyActionTest {
@Test @Test
public void testFailure_expired() { public void testFailure_expired() {
RegistryLockDao.save(createLock()); saveRegistryLock(createLock());
fakeClock.advanceBy(Duration.standardHours(2)); fakeClock.advanceBy(Duration.standardHours(2));
action.run(); action.run();
assertThat(response.getPayload()) assertThat(response.getPayload())
@ -177,7 +178,7 @@ public final class RegistryLockVerifyActionTest {
@Test @Test
public void testFailure_nonAdmin_verifyingAdminLock() { public void testFailure_nonAdmin_verifyingAdminLock() {
RegistryLockDao.save(createLock().asBuilder().isSuperuser(true).build()); saveRegistryLock(createLock().asBuilder().isSuperuser(true).build());
action.run(); action.run();
assertThat(response.getPayload()).contains("Failed: Non-admin user cannot complete admin lock"); assertThat(response.getPayload()).contains("Failed: Non-admin user cannot complete admin lock");
assertNoDomainChanges(); assertNoDomainChanges();
@ -186,7 +187,7 @@ public final class RegistryLockVerifyActionTest {
@Test @Test
public void testFailure_alreadyUnlocked() { public void testFailure_alreadyUnlocked() {
action = createAction(lockId, false); action = createAction(lockId, false);
RegistryLockDao.save( saveRegistryLock(
createLock() createLock()
.asBuilder() .asBuilder()
.setLockCompletionTimestamp(fakeClock.nowUtc()) .setLockCompletionTimestamp(fakeClock.nowUtc())
@ -200,7 +201,7 @@ public final class RegistryLockVerifyActionTest {
@Test @Test
public void testFailure_alreadyLocked() { public void testFailure_alreadyLocked() {
RegistryLockDao.save(createLock()); saveRegistryLock(createLock());
domain = persistResource(domain.asBuilder().setStatusValues(REGISTRY_LOCK_STATUSES).build()); domain = persistResource(domain.asBuilder().setStatusValues(REGISTRY_LOCK_STATUSES).build());
action.run(); action.run();
assertThat(response.getPayload()).contains("Failed: Domain example.tld is already locked"); assertThat(response.getPayload()).contains("Failed: Domain example.tld is already locked");
@ -221,9 +222,9 @@ public final class RegistryLockVerifyActionTest {
// A failure when performing Datastore actions means that no actions should be taken in the // A failure when performing Datastore actions means that no actions should be taken in the
// Cloud SQL RegistryLock object // Cloud SQL RegistryLock object
RegistryLock lock = createLock(); RegistryLock lock = createLock();
RegistryLockDao.save(lock); saveRegistryLock(lock);
// reload the lock to pick up creation time // reload the lock to pick up creation time
lock = RegistryLockDao.getByVerificationCode(lock.getVerificationCode()).get(); lock = getRegistryLockByVerificationCode(lock.getVerificationCode()).get();
fakeClock.advanceOneMilli(); fakeClock.advanceOneMilli();
domain = persistResource(domain.asBuilder().setStatusValues(REGISTRY_LOCK_STATUSES).build()); domain = persistResource(domain.asBuilder().setStatusValues(REGISTRY_LOCK_STATUSES).build());
action.run(); action.run();
@ -231,15 +232,14 @@ public final class RegistryLockVerifyActionTest {
assertThat(response.getPayload()).contains("Failed: Domain example.tld is already locked"); assertThat(response.getPayload()).contains("Failed: Domain example.tld is already locked");
// verify that the changes to the SQL object were rolled back // verify that the changes to the SQL object were rolled back
RegistryLock afterAction = RegistryLock afterAction = getRegistryLockByVerificationCode(lock.getVerificationCode()).get();
RegistryLockDao.getByVerificationCode(lock.getVerificationCode()).get();
assertThat(afterAction).isEqualTo(lock); assertThat(afterAction).isEqualTo(lock);
} }
@Test @Test
public void testFailure_isLockTrue_shouldBeFalse() { public void testFailure_isLockTrue_shouldBeFalse() {
domain = persistResource(domain.asBuilder().setStatusValues(REGISTRY_LOCK_STATUSES).build()); domain = persistResource(domain.asBuilder().setStatusValues(REGISTRY_LOCK_STATUSES).build());
RegistryLockDao.save( saveRegistryLock(
createLock() createLock()
.asBuilder() .asBuilder()
.setLockCompletionTimestamp(fakeClock.nowUtc()) .setLockCompletionTimestamp(fakeClock.nowUtc())
@ -252,18 +252,18 @@ public final class RegistryLockVerifyActionTest {
@Test @Test
public void testFailure_isLockFalse_shouldBeTrue() { public void testFailure_isLockFalse_shouldBeTrue() {
action = createAction(lockId, false); action = createAction(lockId, false);
RegistryLockDao.save(createLock()); saveRegistryLock(createLock());
action.run(); action.run();
assertThat(response.getPayload()).contains("Failed: Domain example.tld is already unlocked"); assertThat(response.getPayload()).contains("Failed: Domain example.tld is already unlocked");
} }
@Test @Test
public void testFailure_lock_unlock_lockAgain() { public void testFailure_lock_unlock_lockAgain() {
RegistryLock lock = RegistryLockDao.save(createLock()); RegistryLock lock = saveRegistryLock(createLock());
action.run(); action.run();
assertThat(response.getPayload()).contains("Success: lock has been applied to example.tld"); assertThat(response.getPayload()).contains("Success: lock has been applied to example.tld");
String unlockVerificationCode = "some-unlock-code"; String unlockVerificationCode = "some-unlock-code";
RegistryLockDao.save( saveRegistryLock(
lock.asBuilder() lock.asBuilder()
.setVerificationCode(unlockVerificationCode) .setVerificationCode(unlockVerificationCode)
.setUnlockRequestTimestamp(fakeClock.nowUtc()) .setUnlockRequestTimestamp(fakeClock.nowUtc())
@ -278,7 +278,7 @@ public final class RegistryLockVerifyActionTest {
@Test @Test
public void testFailure_lock_lockAgain() { public void testFailure_lock_lockAgain() {
RegistryLockDao.save(createLock()); saveRegistryLock(createLock());
action.run(); action.run();
assertThat(response.getPayload()).contains("Success: lock has been applied to example.tld"); assertThat(response.getPayload()).contains("Success: lock has been applied to example.tld");
action = createAction(lockId, true); action = createAction(lockId, true);
@ -290,7 +290,7 @@ public final class RegistryLockVerifyActionTest {
public void testFailure_unlock_unlockAgain() { public void testFailure_unlock_unlockAgain() {
action = createAction(lockId, false); action = createAction(lockId, false);
domain = persistResource(domain.asBuilder().setStatusValues(REGISTRY_LOCK_STATUSES).build()); domain = persistResource(domain.asBuilder().setStatusValues(REGISTRY_LOCK_STATUSES).build());
RegistryLockDao.save( saveRegistryLock(
createLock().asBuilder().setUnlockRequestTimestamp(fakeClock.nowUtc()).build()); createLock().asBuilder().setUnlockRequestTimestamp(fakeClock.nowUtc()).build());
action.run(); action.run();
assertThat(response.getStatus()).isEqualTo(SC_OK); assertThat(response.getStatus()).isEqualTo(SC_OK);
@ -336,7 +336,7 @@ public final class RegistryLockVerifyActionTest {
response = new FakeResponse(); response = new FakeResponse();
RegistryLockVerifyAction action = RegistryLockVerifyAction action =
new RegistryLockVerifyAction( new RegistryLockVerifyAction(
fakeClock, new DomainLockUtils(stringGenerator), lockVerificationCode, isLock); new DomainLockUtils(stringGenerator), lockVerificationCode, isLock);
authResult = AuthResult.create(AuthLevel.USER, UserAuthInfo.create(user, false)); authResult = AuthResult.create(AuthLevel.USER, UserAuthInfo.create(user, false));
action.req = request; action.req = request;
action.response = response; action.response = response;

View file

@ -23,6 +23,7 @@ import static google.registry.testing.DatastoreHelper.loadRegistrar;
import static google.registry.testing.DatastoreHelper.newDomainBase; import static google.registry.testing.DatastoreHelper.newDomainBase;
import static google.registry.testing.DatastoreHelper.persistActiveDomain; import static google.registry.testing.DatastoreHelper.persistActiveDomain;
import static google.registry.testing.DatastoreHelper.persistResource; import static google.registry.testing.DatastoreHelper.persistResource;
import static google.registry.testing.SqlHelper.saveRegistryLock;
import static google.registry.util.DateTimeUtils.START_OF_TIME; import static google.registry.util.DateTimeUtils.START_OF_TIME;
import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableMap;
@ -30,7 +31,6 @@ import com.googlecode.objectify.ObjectifyFilter;
import google.registry.model.domain.DomainBase; import google.registry.model.domain.DomainBase;
import google.registry.model.ofy.OfyFilter; import google.registry.model.ofy.OfyFilter;
import google.registry.model.registrar.Registrar.State; import google.registry.model.registrar.Registrar.State;
import google.registry.model.registry.RegistryLockDao;
import google.registry.module.frontend.FrontendServlet; import google.registry.module.frontend.FrontendServlet;
import google.registry.schema.domain.RegistryLock; import google.registry.schema.domain.RegistryLock;
import google.registry.server.RegistryTestServer; import google.registry.server.RegistryTestServer;
@ -388,7 +388,7 @@ public class RegistrarConsoleScreenshotTest extends WebDriverTestCase {
() -> { () -> {
createTld("tld"); createTld("tld");
persistResource(newDomainBase("example.tld")); persistResource(newDomainBase("example.tld"));
RegistryLockDao.save( saveRegistryLock(
new RegistryLock.Builder() new RegistryLock.Builder()
.setRegistrarPocId("johndoe@theregistrar.com") .setRegistrarPocId("johndoe@theregistrar.com")
.setRepoId("repoId") .setRepoId("repoId")
@ -436,7 +436,7 @@ public class RegistrarConsoleScreenshotTest extends WebDriverTestCase {
public void registryLock_nonEmpty() throws Throwable { public void registryLock_nonEmpty() throws Throwable {
server.runInAppEngineEnvironment( server.runInAppEngineEnvironment(
() -> { () -> {
saveRegistryLock(); createDomainAndSaveLock();
return null; return null;
}); });
driver.get(server.getUrl("/registrar#registry-lock")); driver.get(server.getUrl("/registrar#registry-lock"));
@ -450,9 +450,9 @@ public class RegistrarConsoleScreenshotTest extends WebDriverTestCase {
() -> { () -> {
createTld("tld"); createTld("tld");
DomainBase domain = persistActiveDomain("example.tld"); DomainBase domain = persistActiveDomain("example.tld");
RegistryLockDao.save(createRegistryLock(domain).asBuilder().isSuperuser(true).build()); saveRegistryLock(createRegistryLock(domain).asBuilder().isSuperuser(true).build());
DomainBase otherDomain = persistActiveDomain("otherexample.tld"); DomainBase otherDomain = persistActiveDomain("otherexample.tld");
RegistryLockDao.save(createRegistryLock(otherDomain)); saveRegistryLock(createRegistryLock(otherDomain));
return null; return null;
}); });
driver.get(server.getUrl("/registrar#registry-lock")); driver.get(server.getUrl("/registrar#registry-lock"));
@ -465,7 +465,7 @@ public class RegistrarConsoleScreenshotTest extends WebDriverTestCase {
server.setIsAdmin(true); server.setIsAdmin(true);
server.runInAppEngineEnvironment( server.runInAppEngineEnvironment(
() -> { () -> {
saveRegistryLock(); createDomainAndSaveLock();
return null; return null;
}); });
driver.get(server.getUrl("/registrar#registry-lock")); driver.get(server.getUrl("/registrar#registry-lock"));
@ -510,10 +510,10 @@ public class RegistrarConsoleScreenshotTest extends WebDriverTestCase {
driver.diffPage("page"); driver.diffPage("page");
} }
private void saveRegistryLock() { private void createDomainAndSaveLock() {
createTld("tld"); createTld("tld");
DomainBase domainBase = persistActiveDomain("example.tld"); DomainBase domainBase = persistActiveDomain("example.tld");
RegistryLockDao.save(createRegistryLock(domainBase)); saveRegistryLock(createRegistryLock(domainBase));
} }
private RegistryLock createRegistryLock(DomainBase domainBase) { private RegistryLock createRegistryLock(DomainBase domainBase) {