diff --git a/core/src/main/java/com/minekube/connect/addon/DebugAddon.java b/core/src/main/java/com/minekube/connect/addon/DebugAddon.java index b049e869a..38c3fa007 100644 --- a/core/src/main/java/com/minekube/connect/addon/DebugAddon.java +++ b/core/src/main/java/com/minekube/connect/addon/DebugAddon.java @@ -29,15 +29,25 @@ import com.google.inject.name.Named; import com.minekube.connect.addon.debug.ChannelInDebugHandler; import com.minekube.connect.addon.debug.ChannelOutDebugHandler; +import com.minekube.connect.addon.debug.ChannelOutObjectDebugHandler; import com.minekube.connect.api.inject.InjectorAddon; import com.minekube.connect.api.logger.ConnectLogger; import com.minekube.connect.config.ConnectConfig; import com.minekube.connect.util.Utils; import io.netty.channel.Channel; +import io.netty.channel.ChannelHandler; import io.netty.channel.ChannelPipeline; +import io.netty.handler.codec.MessageToByteEncoder; +import io.netty.handler.codec.MessageToMessageEncoder; +import java.util.List; import java.util.concurrent.atomic.AtomicInteger; +import javax.annotation.Nullable; public final class DebugAddon implements InjectorAddon { + /** Pipeline names the recorders are injected under; also what {@link #onRemoveInject} removes. */ + static final String OUT_HANDLER_NAME = "connect_debug_out"; + static final String IN_HANDLER_NAME = "connect_debug_in"; + @Inject private ConnectConfig config; @Inject private ConnectLogger logger; @@ -56,35 +66,118 @@ public final class DebugAddon implements InjectorAddon { @Override public void onInject(Channel channel, boolean toServer) { logger.info("Successfully called onInject. To server? " + toServer); + installRecorders(channel, platformName, toServer, packetEncoder, packetDecoder, logger); + } - AtomicInteger packetCount = new AtomicInteger(); + /** + * Installs the inbound and outbound packet recorders on {@code channel}. + * + *

Neither direction may fail silently: a one-sided dump looks exactly like a silent peer, and + * has already been read as one during support work. The recorders must also survive the platform + * renaming its pipeline handlers: Paper 26.3 names the outbound packet encoder + * {@code outbound_config} in the injected (configuration-capable) connection and only uses + * {@code encoder} on the player-side path, so the old "add before the configured name, else skip at + * debug level" left every support dump outbound-silent. The encoder is therefore located in the + * pipeline itself, and every non-obvious placement is reported at WARN. + * + *

Each direction gets its own packet budget: a shared counter let whichever direction spoke + * first consume {@link com.minekube.connect.util.Utils#MAX_DEBUG_PACKET_COUNT} and silence the + * other one entirely. + */ + static void installRecorders( + Channel channel, + String platformName, + boolean toServer, + @Nullable String packetEncoder, + @Nullable String packetDecoder, + ConnectLogger logger) { + ChannelPipeline pipeline = channel.pipeline(); - // Check if handlers exist before trying to add - pipeline may not be fully initialized - if (channel.pipeline().get(packetEncoder) != null) { - channel.pipeline().addBefore( - packetEncoder, "connect_debug_out", - new ChannelOutDebugHandler(platformName, toServer, packetCount, logger) - ); + String outboundAnchor = outboundRecorderAnchor(pipeline, packetEncoder); + if (outboundAnchor != null) { + pipeline.addBefore( + outboundAnchor, + OUT_HANDLER_NAME, + new ChannelOutDebugHandler(platformName, toServer, new AtomicInteger(), logger)); + if (!outboundAnchor.equals(packetEncoder)) { + logger.warn( + "Debug capture: packet encoder '{}' is not in this channel's pipeline ({}); " + + "recording the outbound direction in front of '{}' instead.", + packetEncoder, + pipeline.names(), + outboundAnchor); + } } else { - logger.debug("Skipping debug out handler - '" + packetEncoder + "' not found in pipeline"); + // Nothing in this pipeline encodes messages: record at the tail with the object recorder so + // the direction is still visible (as pre-encoding message types), and say so. + pipeline.addLast( + OUT_HANDLER_NAME, + new ChannelOutObjectDebugHandler(platformName, toServer, new AtomicInteger(), logger)); + logger.warn( + "Debug capture: no packet encoder found in this channel's pipeline ({}); " + + "recording the outbound direction at the pipeline tail - outbound entries " + + "show the pre-encoding message, not packet bytes.", + pipeline.names()); } - if (channel.pipeline().get(packetDecoder) != null) { - channel.pipeline().addBefore( - packetDecoder, "connect_debug_in", - new ChannelInDebugHandler(platformName, toServer, packetCount, logger) - ); + if (packetDecoder != null && pipeline.get(packetDecoder) != null) { + pipeline.addBefore( + packetDecoder, + IN_HANDLER_NAME, + new ChannelInDebugHandler(platformName, toServer, new AtomicInteger(), logger)); } else { - logger.debug("Skipping debug in handler - '" + packetDecoder + "' not found in pipeline"); + logger.warn( + "Debug capture: packet decoder '{}' is not in this channel's pipeline ({}); " + + "the inbound direction is NOT being recorded - this dump is one-sided.", + packetDecoder, + pipeline.names()); + } + } + + /** + * Pipeline name to install the outbound recorder in front of, or {@code null} if this pipeline has + * no message encoder at all. + * + *

Search order: the configured encoder name, then the packet encoder the platform actually + * installed - recognised by class name, because Minecraft's {@code PacketEncoder} is a plain + * {@code ChannelOutboundHandler} and not a Netty codec base class - and only then any Netty message + * encoder, taking the handler furthest towards the tail because that is the one an outbound write + * reaches first. + */ + @Nullable + static String outboundRecorderAnchor(ChannelPipeline pipeline, @Nullable String packetEncoder) { + if (packetEncoder != null && pipeline.get(packetEncoder) != null) { + return packetEncoder; + } + String firstMessageEncoder = null; + List names = pipeline.names(); + for (int i = names.size() - 1; i >= 0; i--) { + String name = names.get(i); + if (OUT_HANDLER_NAME.equals(name) || IN_HANDLER_NAME.equals(name)) { + continue; + } + ChannelHandler handler = pipeline.get(name); + if (handler == null) { + continue; + } + if (handler.getClass().getSimpleName().contains("PacketEncoder")) { + return name; + } + boolean messageEncoder = + handler instanceof MessageToMessageEncoder || handler instanceof MessageToByteEncoder; + if (messageEncoder && firstMessageEncoder == null) { + firstMessageEncoder = name; + } } + return firstMessageEncoder; } @Override public void onRemoveInject(Channel channel) { ChannelPipeline pipeline = channel.pipeline(); - Utils.removeHandler(pipeline, "connect_debug_out"); - Utils.removeHandler(pipeline, "connect_debug_in"); + Utils.removeHandler(pipeline, OUT_HANDLER_NAME); + Utils.removeHandler(pipeline, IN_HANDLER_NAME); } @Override diff --git a/core/src/main/java/com/minekube/connect/addon/debug/ChannelOutObjectDebugHandler.java b/core/src/main/java/com/minekube/connect/addon/debug/ChannelOutObjectDebugHandler.java new file mode 100644 index 000000000..9c86b5e20 --- /dev/null +++ b/core/src/main/java/com/minekube/connect/addon/debug/ChannelOutObjectDebugHandler.java @@ -0,0 +1,82 @@ +/* + * Copyright (c) 2019-2022 GeyserMC. http://geysermc.org + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + * + * @author GeyserMC + * @link https://github.com/GeyserMC/Floodgate + */ + +package com.minekube.connect.addon.debug; + +import com.minekube.connect.api.logger.ConnectLogger; +import com.minekube.connect.util.Utils; +import io.netty.buffer.ByteBuf; +import io.netty.buffer.ByteBufUtil; +import io.netty.channel.ChannelHandler.Sharable; +import io.netty.channel.ChannelHandlerContext; +import io.netty.channel.ChannelOutboundHandlerAdapter; +import io.netty.channel.ChannelPromise; +import java.util.concurrent.atomic.AtomicInteger; + +/** + * Outbound recorder used when the channel's pipeline has no encoder to sit in front of. + * + *

{@link ChannelOutDebugHandler} can only record {@link ByteBuf} messages, so at the pipeline tail - + * where a write is still the platform's own packet object - it would silently record nothing and make a + * live backend look silent. This recorder logs whatever the platform is writing (type plus a hex dump + * when it is already bytes) and forwards it unchanged, so the direction is visible even from a degraded + * position. + */ +@Sharable +public final class ChannelOutObjectDebugHandler extends ChannelOutboundHandlerAdapter { + private final String direction; + private final ConnectLogger logger; + private final AtomicInteger packetCount; + + public ChannelOutObjectDebugHandler( + String implementationType, + boolean toServer, + AtomicInteger packetCount, + ConnectLogger logger) { + this.direction = implementationType + (toServer ? " -> Server" : " -> Player"); + this.packetCount = packetCount; + this.logger = logger; + } + + @Override + public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) { + try { + if (packetCount.getAndIncrement() < Utils.MAX_DEBUG_PACKET_COUNT) { + logger.info("{} {}:\n{}", direction, packetCount.get(), describe(msg)); + } + } catch (Exception e) { + e.printStackTrace(); + } + ctx.write(msg, promise); + } + + private static String describe(Object msg) { + if (msg instanceof ByteBuf) { + ByteBuf buf = (ByteBuf) msg; + return ByteBufUtil.prettyHexDump(buf); + } + return "(pre-encoding) " + msg.getClass().getName() + ": " + msg; + } +} diff --git a/core/src/test/java/com/minekube/connect/addon/DebugAddonCaptureTest.java b/core/src/test/java/com/minekube/connect/addon/DebugAddonCaptureTest.java new file mode 100644 index 000000000..63a6fc40e --- /dev/null +++ b/core/src/test/java/com/minekube/connect/addon/DebugAddonCaptureTest.java @@ -0,0 +1,298 @@ +package com.minekube.connect.addon; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import com.minekube.connect.api.logger.ConnectLogger; +import io.netty.buffer.Unpooled; +import io.netty.channel.ChannelHandlerContext; +import io.netty.channel.ChannelInboundHandlerAdapter; +import io.netty.channel.embedded.EmbeddedChannel; +import io.netty.handler.codec.MessageToMessageEncoder; +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.CopyOnWriteArrayList; +import org.junit.jupiter.api.Test; + +/** + * Guards the operator-facing contract of {@code debug: true}: a debug dump must show both + * directions of the tunneled connection, and a direction that cannot be recorded must say so loudly. + * + *

Defect this reproduces (Paper 26.3, connect-spot 0.15.17, case t_dc27dadd §6): the outbound + * recorder was installed only in front of the configured {@code encoder} name. Paper 26.3 names the + * outbound packet encoder {@code outbound_config} on the injected, configuration-capable connection + * ({@code Connection.outboundHandlerName}), so the recorder was never installed, the skip was logged at + * debug level, and a full successful join produced 25 {@code Player -> Spigot} lines and zero + * {@code Spigot -> Player} lines. Three support rounds read that as "Paper sent nothing". + * + *

Also guarded: the recorders must log at WARN when they cannot sit in front of an encoder, and each + * direction needs its own packet budget - the old shared counter let the direction that spoke first + * consume {@code MAX_DEBUG_PACKET_COUNT} and silence the other one entirely. + */ +class DebugAddonCaptureTest { + private static final String PLATFORM = "Spigot"; + private static final String CONFIGURED_ENCODER = "encoder"; + private static final String CONFIG_STATE_ENCODER = "outbound_config"; + private static final String DECODER = "decoder"; + + private final RecordingLogger logger = new RecordingLogger(); + + @Test + void recordsTheOutboundDirectionWhenThePlatformNamesItsEncoderDifferently() { + // The pipeline shape measured on Paper 26.3 for the injected connection. + EmbeddedChannel channel = configStatePipeline(); + try { + DebugAddon.installRecorders( + channel, PLATFORM, false, CONFIGURED_ENCODER, DECODER, logger); + + List names = channel.pipeline().names(); + assertEquals( + names.indexOf(CONFIG_STATE_ENCODER) - 1, + names.indexOf(DebugAddon.OUT_HANDLER_NAME), + "the recorder must sit in front of the encoder the platform actually installed: " + + names); + + channel.writeOutbound(new FakePacket("login_success")); + channel.writeInbound(Unpooled.wrappedBuffer(new byte[]{0x01, 0x00})); + + assertEquals( + 1, + logger.lines("Spigot -> Player "), + "outbound entries must be recorded: " + String.join("\n", logger.all())); + assertEquals(1, logger.lines("Player -> Spigot "), String.join("\n", logger.all())); + + String warning = String.join("\n", logger.warnings); + assertTrue(warning.contains(CONFIG_STATE_ENCODER), warning); + assertTrue(warning.contains(CONFIGURED_ENCODER), warning); + } finally { + channel.finishAndReleaseAll(); + } + } + + @Test + void recordsInFrontOfTheConfiguredEncoderWithoutAWarning() { + EmbeddedChannel channel = configStatePipeline(); + try { + channel.pipeline().addBefore("packet_handler", CONFIGURED_ENCODER, new PassThrough()); + DebugAddon.installRecorders( + channel, PLATFORM, false, CONFIGURED_ENCODER, DECODER, logger); + + List names = channel.pipeline().names(); + assertEquals( + names.indexOf(CONFIGURED_ENCODER) - 1, + names.indexOf(DebugAddon.OUT_HANDLER_NAME), + "the recorder still sits directly in front of the configured encoder: " + names); + assertTrue(logger.warnings.isEmpty(), String.join("\n", logger.all())); + } finally { + channel.finishAndReleaseAll(); + } + } + + @Test + void recordsAtTheTailAndWarnsWhenThePipelineHasNoEncoderAtAll() { + EmbeddedChannel channel = new EmbeddedChannel(new PassThrough()); + channel.pipeline().addLast(DECODER, new PassThrough()); + channel.pipeline().addLast("packet_handler", new PassThrough()); + try { + DebugAddon.installRecorders( + channel, PLATFORM, false, CONFIGURED_ENCODER, DECODER, logger); + + assertNotNull( + channel.pipeline().get(DebugAddon.OUT_HANDLER_NAME), + "the outbound recorder must exist even without any encoder: " + + channel.pipeline().names()); + assertTrue( + channel.pipeline().names().indexOf(DebugAddon.OUT_HANDLER_NAME) + > channel.pipeline().names().indexOf("packet_handler"), + "without an encoder the recorder belongs at the tail: " + channel.pipeline().names()); + + channel.writeOutbound(new FakePacket("login_success")); + assertEquals(1, logger.lines("Spigot -> Player "), String.join("\n", logger.all())); + assertTrue( + logger.matching("Spigot -> Player ").get(0).contains("(pre-encoding)"), + "a pre-encoding capture must say so instead of recording nothing: " + + String.join("\n", logger.all())); + + String warning = String.join("\n", logger.warnings); + assertTrue(warning.contains("tail"), warning); + assertTrue(warning.contains("no packet encoder"), warning); + } finally { + channel.finishAndReleaseAll(); + } + } + + @Test + void saysOutLoudWhenTheInboundDirectionCannotBeRecorded() { + EmbeddedChannel channel = new EmbeddedChannel(new PassThrough()); + channel.pipeline().addLast("packet_handler", new PassThrough()); + try { + DebugAddon.installRecorders( + channel, PLATFORM, false, CONFIGURED_ENCODER, DECODER, logger); + + assertNull(channel.pipeline().get(DebugAddon.IN_HANDLER_NAME)); + String warning = String.join("\n", logger.warnings); + assertTrue(warning.contains(DECODER), warning); + assertTrue(warning.contains("one-sided"), warning); + } finally { + channel.finishAndReleaseAll(); + } + } + + @Test + void givesEachDirectionItsOwnPacketBudget() { + EmbeddedChannel channel = configStatePipeline(); + try { + DebugAddon.installRecorders( + channel, PLATFORM, false, CONFIGURED_ENCODER, DECODER, logger); + + // The direction that speaks first must not exhaust the budget of the other one. + for (int i = 0; i < 30; i++) { + channel.writeInbound(Unpooled.wrappedBuffer(new byte[]{(byte) i})); + } + for (int i = 0; i < 30; i++) { + channel.writeOutbound(new FakePacket("config-" + i)); + } + + assertEquals(25, logger.lines("Player -> Spigot "), "inbound budget"); + assertEquals(25, logger.lines("Spigot -> Player "), "outbound budget"); + } finally { + channel.finishAndReleaseAll(); + } + } + + /** Mirrors Paper 26.3: decoder, framing prepender, then the config-state packet encoder. */ + private static EmbeddedChannel configStatePipeline() { + EmbeddedChannel channel = new EmbeddedChannel(new PassThrough()); + channel.pipeline().addLast("splitter", new PassThrough()); + channel.pipeline().addLast(DECODER, new PassThrough()); + channel.pipeline().addLast("prepender", new PassThrough()); + channel.pipeline().addLast(CONFIG_STATE_ENCODER, new FakePacketEncoder()); + channel.pipeline().addLast("hackfix", new PassThrough()); + channel.pipeline().addLast("packet_handler", new PassThrough()); + return channel; + } + + /** Stands in for a packet on the wire, before encoding. */ + private static final class FakePacket { + private final String name; + + private FakePacket(String name) { + this.name = name; + } + + @Override + public String toString() { + return "FakePacket(" + name + ")"; + } + } + + /** Encodes a packet into the ByteBuf the recorder must see. */ + private static final class FakePacketEncoder extends MessageToMessageEncoder { + @Override + protected void encode(ChannelHandlerContext ctx, Object msg, List out) { + out.add(Unpooled.wrappedBuffer(new byte[]{0x02, 0x21, 0x30})); + } + } + + private static final class PassThrough extends ChannelInboundHandlerAdapter { + @Override + public void channelRead(ChannelHandlerContext ctx, Object msg) { + ctx.fireChannelRead(msg); + } + } + + private static final class RecordingLogger implements ConnectLogger { + private final List infos = new CopyOnWriteArrayList<>(); + private final List warnings = new CopyOnWriteArrayList<>(); + private final List debugLines = new CopyOnWriteArrayList<>(); + + @Override + public void error(String message, Object... args) { + // not asserted + } + + @Override + public void error(String message, Throwable throwable, Object... args) { + // not asserted + } + + @Override + public void warn(String message, Object... args) { + warnings.add(format(message, args)); + } + + @Override + public void info(String message, Object... args) { + infos.add(format(message, args)); + } + + @Override + public void translatedInfo(String message, Object... args) { + infos.add(format(message, args)); + } + + @Override + public void debug(String message, Object... args) { + debugLines.add(format(message, args)); + } + + @Override + public void trace(String message, Object... args) { + debugLines.add(format(message, args)); + } + + @Override + public void enableDebug() { + } + + @Override + public void disableDebug() { + } + + @Override + public boolean isDebug() { + return true; + } + + int lines(String prefix) { + return matching(prefix).size(); + } + + List matching(String prefix) { + List matched = new ArrayList<>(); + for (String line : infos) { + if (line.startsWith(prefix)) { + matched.add(line); + } + } + return matched; + } + + List all() { + List all = new ArrayList<>(warnings); + all.addAll(infos); + all.addAll(debugLines); + return all; + } + + private static String format(String message, Object... args) { + if (args == null || args.length == 0) { + return message; + } + StringBuilder out = new StringBuilder(); + int arg = 0; + int from = 0; + int at; + while ((at = message.indexOf("{}", from)) != -1) { + out.append(message, from, at); + out.append(arg < args.length ? String.valueOf(args[arg]) : "{}"); + arg++; + from = at + 2; + } + out.append(message.substring(from)); + return out.toString(); + } + } +} diff --git a/spigot/src/main/java/com/minekube/connect/addon/data/SpigotDataHandler.java b/spigot/src/main/java/com/minekube/connect/addon/data/SpigotDataHandler.java index c9ef7367f..3e217b4bb 100644 --- a/spigot/src/main/java/com/minekube/connect/addon/data/SpigotDataHandler.java +++ b/spigot/src/main/java/com/minekube/connect/addon/data/SpigotDataHandler.java @@ -44,6 +44,7 @@ import java.lang.reflect.Field; import java.net.InetSocketAddress; import java.net.SocketAddress; +import java.util.function.BooleanSupplier; import java.util.function.UnaryOperator; import javax.annotation.Nullable; @@ -229,15 +230,15 @@ public boolean channelRead(Object packet) throws Exception { // LoginListener#callPlayerPreLoginEvents(GameProfile) returns modified GameProfile // LoginListener#startClientVerification(GameProfile) - Object returnedProfile = ClassNames.CALL_PLAYER_PRE_LOGIN_EVENTS.invoke(packetListener, gameProfile); - GameProfile profileToUse = returnedProfile != null ? (GameProfile) returnedProfile : gameProfile; - - if (config.isDebug()) { - debug("callPlayerPreLoginEvents returned a profile for " + logPlayer()); + boolean handedOver = runPostLoginInjection( + new ReflectivePostLoginListener(packetListener), + gameProfile, + () -> ctx.channel().isActive()); + if (!handedOver) { + debug("Paper ended the login during the pre-login events; not continuing the injection"); + } else { + debug("startClientVerification completed"); } - - ClassNames.START_CLIENT_VERIFICATION.invoke(packetListener, profileToUse); - debug("startClientVerification completed"); } removeSelf(); @@ -246,6 +247,71 @@ public boolean channelRead(Object packet) throws Exception { return true; } + /** + * Paper's post-1.20.4 fake login cycle, as the connector drives it. + * + *

{@link #callPlayerPreLoginEvents} fires {@code AsyncPlayerPreLoginEvent} / + * {@code PlayerLoginEvent} and lets Paper issue its own {@code Disconnect}; the event result decides + * whether the connection survives that call. {@link #startClientVerification} then hands the + * (possibly rewritten) profile to Paper's verification step, which is what eventually sends + * {@code LoginSuccess}. + */ + interface PostLoginListener { + @Nullable + GameProfile callPlayerPreLoginEvents(GameProfile requested) throws Exception; + + void startClientVerification(GameProfile profile) throws Exception; + } + + /** + * Drives Paper's post-1.20.4 fake login cycle and reports whether the login was handed over. + * + *

{@code callPlayerPreLoginEvents} can end the login itself: {@code PlayerPreLoginEvent} / + * {@code PlayerLoginEvent} denials and the Velocity-forwarding refusal all make Paper send its own + * {@code ClientboundLoginDisconnectPacket} and close the connection - and Paper still returns the + * profile in those cases (see {@code ServerLoginPacketListenerImpl#callPlayerPreLoginEvents} in + * Paper, which only ever returns {@code null} for its own "no profile" error path). Continuing with + * {@code startClientVerification} would therefore push {@code LoginSuccess} onto a refused + * connection and race the kick the player is supposed to see. So the decision is taken on the + * connection state rather than on the return value alone, and nothing is invoked once Paper has + * ended the login; the disconnect packet stays Paper's own, unmodified. + */ + static boolean runPostLoginInjection( + PostLoginListener listener, + GameProfile requestedProfile, + BooleanSupplier connectionOpen) throws Exception { + GameProfile returnedProfile = listener.callPlayerPreLoginEvents(requestedProfile); + if (returnedProfile == null || !connectionOpen.getAsBoolean()) { + return false; + } + listener.startClientVerification(returnedProfile); + return true; + } + + /** Adapts the reflected Paper login listener to {@link PostLoginListener}. */ + private final class ReflectivePostLoginListener implements PostLoginListener { + private final Object packetListener; + + private ReflectivePostLoginListener(Object packetListener) { + this.packetListener = packetListener; + } + + @Override + public GameProfile callPlayerPreLoginEvents(GameProfile requested) throws Exception { + GameProfile returned = + (GameProfile) ClassNames.CALL_PLAYER_PRE_LOGIN_EVENTS.invoke(packetListener, requested); + if (config.isDebug()) { + debug("callPlayerPreLoginEvents returned a profile for " + logPlayer()); + } + return returned; + } + + @Override + public void startClientVerification(GameProfile profile) throws Exception { + ClassNames.START_CLIENT_VERIFICATION.invoke(packetListener, profile); + } + } + private String logPlayer() { return sessionCtx.getSessionProposal().hasBedrockPrincipalV2() ? "" diff --git a/spigot/src/test/java/com/minekube/connect/addon/data/SpigotLoginRefusalTest.java b/spigot/src/test/java/com/minekube/connect/addon/data/SpigotLoginRefusalTest.java new file mode 100644 index 000000000..6db71a506 --- /dev/null +++ b/spigot/src/test/java/com/minekube/connect/addon/data/SpigotLoginRefusalTest.java @@ -0,0 +1,115 @@ +package com.minekube.connect.addon.data; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import com.mojang.authlib.GameProfile; +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicBoolean; +import org.junit.jupiter.api.Test; + +/** + * Guards the post-1.20.4 fake login cycle against finishing a login that Paper has already refused. + * + *

Defect reproduced against connect-spot 0.15.17 (Paper 26.3, case t_dc27dadd §4): the connector + * called {@code callPlayerPreLoginEvents} - which lets Paper fire {@code AsyncPlayerPreLoginEvent} / + * {@code PlayerLoginEvent} and issue its own {@code Disconnect} for any denial - and then called + * {@code startClientVerification} unconditionally, driving {@code LoginSuccess} onto a connection + * Paper had already ended. Whatever the client then sees, it is not Paper's kick message. + * + *

The refusal must be honoured: no verification call, no rewritten kick text, and the injection + * reported as not handed over. These tests drive the real flow method, so the ordering of the two + * reflective calls is under test rather than assumed. + */ +class SpigotLoginRefusalTest { + private static final GameProfile PROFILE = + new GameProfile(UUID.fromString("0a1b2c3d-4e5f-4071-8293-a4b5c6d7e8f9"), "NotListed"); + + @Test + void doesNotStartClientVerificationWhenPaperRefusedDuringThePreLoginEvents() throws Exception { + FakeLoginListener listener = new FakeLoginListener(); + listener.finishWithKick("You are not whitelisted on this server!"); + + boolean handedOver = SpigotDataHandler.runPostLoginInjection(listener, PROFILE, listener::open); + + assertFalse(handedOver, "a refused login must not be reported as handed over"); + assertTrue(listener.verified.isEmpty(), + "startClientVerification must not run after Paper's refusal: " + listener.verified); + assertEquals("You are not whitelisted on this server!", listener.kickMessage, + "Paper's own kick text must reach the client unmodified"); + } + + @Test + void doesNotStartClientVerificationWhenThePreLoginCallReturnsNoProfile() throws Exception { + FakeLoginListener listener = new FakeLoginListener(); + listener.returnedProfile = null; + listener.connectionStaysOpen = true; + + boolean handedOver = SpigotDataHandler.runPostLoginInjection(listener, PROFILE, listener::open); + + assertFalse(handedOver, "a null pre-login result means Paper did not hand the login back"); + assertTrue(listener.verified.isEmpty(), listener.verified.toString()); + } + + @Test + void handsTheProfilePaperReturnedToVerificationOnAnAllowedLogin() throws Exception { + FakeLoginListener listener = new FakeLoginListener(); + + boolean handedOver = SpigotDataHandler.runPostLoginInjection(listener, PROFILE, listener::open); + + assertTrue(handedOver); + assertEquals(1, listener.verified.size(), listener.verified.toString()); + assertSame(listener.returnedProfile, listener.verified.get(0), + "the profile Paper returned must be the one verified"); + } + + @Test + void verifiesTheRequestedProfileWhenPaperEchoesItBackUnchanged() throws Exception { + FakeLoginListener listener = new FakeLoginListener(); + + boolean handedOver = SpigotDataHandler.runPostLoginInjection(listener, PROFILE, listener::open); + + assertTrue(handedOver); + assertEquals(List.of(PROFILE), listener.verified); + assertTrue(listener.kickMessage == null, "an allowed login must not be kicked"); + } + + /** + * Stands in for Paper's {@code ServerLoginPacketListenerImpl}: the pre-login call can end the + * connection (and record Paper's kick message) exactly like {@code disconnect(String)} does. + */ + private static final class FakeLoginListener implements SpigotDataHandler.PostLoginListener { + private final AtomicBoolean connectionOpen = new AtomicBoolean(true); + private final List verified = new ArrayList<>(); + private GameProfile returnedProfile = PROFILE; + private String kickMessage; + private boolean connectionStaysOpen; + + void finishWithKick(String message) { + this.kickMessage = message; + this.connectionOpen.set(false); + } + + boolean open() { + return connectionOpen.get(); + } + + @Override + public GameProfile callPlayerPreLoginEvents(GameProfile requested) { + if (kickMessage != null && !connectionStaysOpen) { + // Paper's disconnect(): the connection is gone once the event was denied. + connectionOpen.set(false); + } + return returnedProfile; + } + + @Override + public void startClientVerification(GameProfile profile) { + verified.add(profile); + } + } +}