feat(heights): mount larger players without consent
Release / release (push) Successful in 4m6s
CI / build (push) Successful in 2m7s

This commit is contained in:
dmg committed 2026-09-12 08:35:29 -04:00
1 parent df44bba9c6
commit a949fd99c4
16 files changed
+585 -206

No files matched your search

@@ -0,0 +1,242 @@
package games.dmg.spigotheights;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.*;
import io.papermc.paper.plugin.manager.PaperPluginManagerImpl;
import java.util.*;
import java.util.logging.Logger;
import org.bukkit.*;
import org.bukkit.command.SimpleCommandMap;
import org.bukkit.entity.Player;
import org.bukkit.event.HandlerList;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerInteractAtEntityEvent;
import org.bukkit.event.player.PlayerInteractEntityEvent;
import org.bukkit.inventory.EquipmentSlot;
import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.PluginDescriptionFile;
import org.bukkit.plugin.PluginManager;
import org.bukkit.util.Vector;
import org.junit.jupiter.api.*;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
/** Actual Purpur 2618 listener discovery, distinct handler lists and Paper event dispatch.
* Only server/player boundaries are doubled; no listening server or client packets. */
class NativeCarryRoutingTest {
private static Server previousServer;
private PluginManager events;
private Plugin plugin;
private BukkitCarry carry;
private final List<Runnable> scheduled = new ArrayList<>();
private final Player small = mock(Player.class), large = mock(Player.class);
private final List<String> replies = new ArrayList<>();
private boolean attached, mountAllowed = true;
private int mounts;
private double smallScale = 0.9, largeScale = 1.0;
@BeforeAll
static void rememberServer() { previousServer = Bukkit.getServer(); }
@AfterAll
static void restoreServer() throws Exception { setServer(previousServer); }
private static void setServer(Server server) throws Exception {
// Bukkit's global is restored so the separate existing native brewing suite is untouched.
var field = Bukkit.class.getDeclaredField("server");
field.setAccessible(true);
field.set(null, server);
}
@BeforeEach
void registerProductionListener() throws Exception {
HandlerList.unregisterAll();
Server server = mock(Server.class);
when(server.isPrimaryThread()).thenReturn(true);
when(server.getLogger()).thenReturn(Logger.getLogger("NativeCarryRoutingTest"));
setServer(server);
events = new PaperPluginManagerImpl(server, new SimpleCommandMap(server, new HashMap<>()), null);
when(server.getPluginManager()).thenReturn(events);
plugin = mock(Plugin.class);
when(plugin.isEnabled()).thenReturn(true);
when(plugin.getName()).thenReturn("SpigotHeights");
when(plugin.getLogger()).thenReturn(Logger.getLogger("NativeCarryRoutingTest"));
var description = new PluginDescriptionFile("SpigotHeights", "test", "unused.Main");
when(plugin.getDescription()).thenReturn(description);
when(plugin.getPluginMeta()).thenReturn(description);
World world = mock(World.class);
when(world.getUID()).thenReturn(UUID.randomUUID());
for (Player p : List.of(small, large)) {
when(p.getUniqueId()).thenReturn(UUID.randomUUID());
when(p.getWorld()).thenReturn(world);
when(p.getLocation()).thenReturn(new Location(world, 0, 64, 0));
when(p.isOnline()).thenReturn(true);
when(p.isValid()).thenReturn(true);
when(p.getGameMode()).thenReturn(GameMode.SURVIVAL);
doAnswer(invocation -> { replies.add(invocation.getArgument(0, String.class)); return null; })
.when(p).sendMessage(anyString());
}
when(small.getVehicle()).thenAnswer(invocation -> attached ? large : null);
when(small.isInsideVehicle()).thenAnswer(invocation -> attached);
when(large.getPassengers()).thenAnswer(invocation -> attached ? List.of(small) : List.of());
when(large.addPassenger(small)).thenAnswer(invocation -> {
mounts++;
var event = new org.bukkit.event.entity.EntityMountEvent(small, large);
events.callEvent(event);
attached = mountAllowed && !event.isCancelled();
return attached;
});
when(small.leaveVehicle()).thenAnswer(invocation -> {
var event = new org.bukkit.event.entity.EntityDismountEvent(small, large, true);
events.callEvent(event);
if (!event.isCancelled()) { attached = false; }
return true; // Intentionally unreliable: production code must inspect attachment.
});
carry = new BukkitCarry(id -> id.equals(small.getUniqueId()) ? small : large,
() -> new HeightSettings(0.4, 2, 0.25, 0.5, 1.5, 20), scheduled::add,
server.getLogger(), p -> p == small ? smallScale : largeScale);
events.registerEvents(carry, plugin);
}
private PlayerInteractEntityEvent click(boolean at, Player sender, Player target, EquipmentSlot hand) {
return at ? new PlayerInteractAtEntityEvent(sender, target, new Vector(), hand)
: new PlayerInteractEntityEvent(sender, target, hand);
}
private void drain() {
var tasks = List.copyOf(scheduled);
scheduled.clear();
tasks.forEach(Runnable::run);
}
@ParameterizedTest
@ValueSource(booleans = {false, true})
void duplicateEventTypesDoNotRepeatMountAttemptsOrMessagesEvenAfterRefusal(boolean atFirst) {
for (boolean allowed : new boolean[] {false, true}) {
mountAllowed = allowed;
int before = mounts;
var first = click(atFirst, small, large, EquipmentSlot.HAND);
events.callEvent(first);
assertTrue(first.isCancelled());
int messageCount = replies.size();
var duplicate = click(!atFirst, small, large, EquipmentSlot.HAND);
events.callEvent(duplicate);
assertTrue(duplicate.isCancelled(), "A duplicate of a handled interaction stays consumed");
events.callEvent(click(atFirst, small, large, EquipmentSlot.OFF_HAND));
assertEquals(before + 1, mounts, "One native attempt for the duplicate event pair, even on refusal");
assertEquals(messageCount, replies.size(), "Duplicate dispatch must not send another refusal/busy reply");
assertEquals(allowed, attached);
if (attached) { carry.command(large, "stop"); }
drain(); // A fresh interaction next tick may immediately remount: no gameplay cooldown.
}
events.callEvent(click(atFirst, small, large, EquipmentSlot.HAND));
assertTrue(attached);
assertEquals(3, mounts);
}
@ParameterizedTest
@ValueSource(booleans = {false, true})
void registeredRoutingHonorsCancellationAndOffhandWithoutSwallowingNextValidEvent(boolean at) {
var cancelled = click(at, small, large, EquipmentSlot.HAND);
cancelled.setCancelled(true);
events.callEvent(cancelled);
events.callEvent(click(at, small, large, EquipmentSlot.OFF_HAND));
assertEquals(0, mounts);
assertTrue(replies.isEmpty());
events.callEvent(click(!at, small, large, EquipmentSlot.HAND));
assertTrue(attached);
}
@ParameterizedTest
@ValueSource(strings = {"equal", "larger", "offline", "distant", "already-riding"})
void ineligibleInteractionsRemainAvailableToOtherPlugins(String reason) {
switch (reason) {
case "equal" -> smallScale = largeScale;
case "larger" -> smallScale = largeScale + 0.2;
case "offline" -> when(small.isOnline()).thenReturn(false);
case "distant" -> {
Location distant = new Location(small.getWorld(), 0, 64, 5);
when(small.getLocation()).thenReturn(distant);
}
case "already-riding" -> when(small.isInsideVehicle()).thenReturn(true);
default -> throw new AssertionError(reason);
}
for (boolean at : new boolean[] {true, false}) {
var interaction = click(at, small, large, EquipmentSlot.HAND);
events.callEvent(interaction);
assertFalse(interaction.isCancelled(), "Rejected carry must leave unrelated interaction handlers available");
}
assertEquals(0, mounts);
assertTrue(replies.isEmpty());
}
@ParameterizedTest
@ValueSource(booleans = {false, true})
void nativeMountCancellationIsRespectedAndFreshInteractionCanRetry(boolean at) {
Listener canceller = new Listener() {};
events.registerEvent(org.bukkit.event.entity.EntityMountEvent.class, canceller, EventPriority.HIGHEST,
(listener, event) -> ((org.bukkit.event.entity.EntityMountEvent) event).setCancelled(true), plugin);
events.callEvent(click(at, small, large, EquipmentSlot.HAND));
assertFalse(attached);
assertEquals(1, mounts);
assertTrue(replies.getLast().contains("refused"));
HandlerList.unregisterAll(canceller);
drain();
events.callEvent(click(at, small, large, EquipmentSlot.HAND));
assertTrue(attached);
assertEquals(2, mounts);
}
@Test
void nonadminCommandRoutingLetsEitherParticipantStopAndNativeSneakDismountClearsTracking() {
var settings = new LiveHeightSettings(new HeightSettings(0.4, 2, 0.1, 0.5, 1.5, 20), ignored -> {});
var command = new HeightsCommand(settings, null, plugin.getLogger(),
(name, value, reply) -> fail("Carry must not reach admin setter"), carry::command);
for (Player participant : List.of(small, large)) {
events.callEvent(click(true, small, large, EquipmentSlot.HAND));
assertTrue(attached);
assertFalse(participant.hasPermission("spigotheights.admin"));
command.onCommand(participant, null, "heights", new String[] {"carry", "stop"});
assertFalse(attached);
drain();
}
events.callEvent(click(false, small, large, EquipmentSlot.HAND));
assertTrue(attached);
small.leaveVehicle(); // Native sneak path: real registered MONITOR observer sees the event.
drain();
events.callEvent(click(true, small, large, EquipmentSlot.HAND));
assertTrue(attached, "Ordinary native detach must release Heights tracking");
assertEquals(4, mounts);
}
@Test
void registeredDismountLateCancellationRetainsRideUntilCarrierRetriesStop() {
events.callEvent(click(true, small, large, EquipmentSlot.HAND));
Listener canceller = new Listener() {};
events.registerEvent(org.bukkit.event.entity.EntityDismountEvent.class, canceller, EventPriority.MONITOR,
(listener, event) -> ((org.bukkit.event.entity.EntityDismountEvent) event).setCancelled(true), plugin);
small.leaveVehicle();
drain();
assertTrue(attached);
carry.command(large, "stop");
assertTrue(attached);
assertTrue(replies.getLast().contains("refused"));
HandlerList.unregisterAll(canceller);
carry.command(large, "stop");
assertFalse(attached);
}
@ParameterizedTest
@ValueSource(booleans = {false, true})
void registeredMainHandEventsImmediatelyMountOnlyTheSmallerInitiator(boolean at) {
events.callEvent(click(at, large, small, EquipmentSlot.HAND));
assertEquals(0, mounts, "Larger players cannot initiate pickup");
assertFalse(small.isSneaking());
events.callEvent(click(at, small, large, EquipmentSlot.HAND));
assertTrue(attached, "Registered handler must receive this event without sneaking or acceptance");
assertEquals(1, mounts);
assertTrue(replies.stream().noneMatch(reply -> reply.contains("request")));
}
}