Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions java/grus-demo-minestom/build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,10 @@ val mainClassName = "net.onelitefeather.grus.demo.DemoServer"
dependencies {
implementation(project(":grus-minestom"))
implementation(libs.minestom)

testImplementation(platform(libs.junit.bom))
testImplementation(libs.junit.jupiter)
testRuntimeOnly(libs.junit.platform.launcher)
}

application {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,13 +12,24 @@
import net.minestom.server.instance.block.Block;
import net.onelitefeather.grus.minestom.GrusMinestom;

import java.io.IOException;
import java.io.UncheckedIOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Map;
import java.util.Optional;
import java.util.function.Function;

/**
* Minimal lobby for the Grus prototype: a flat world, Velocity modern forwarding when
* {@code VELOCITY_SECRET} is set, a {@code /hub} command, and the Grus integration.
* Minimal lobby for the Grus prototype: a flat world, Velocity modern forwarding when a secret is
* configured, a {@code /hub} command, and the Grus integration.
*
* <p>Environment: {@code GRUS_PORT} (default 25565), {@code GRUS_INSTANCE} (shown in the welcome
* message), {@code VELOCITY_SECRET} (optional), plus the {@code GRUS_*} variables read by
* {@link GrusMinestom}.
* message), {@code VELOCITY_SECRET} (optional forwarding secret), {@code VELOCITY_SECRET_FILE}
* (optional path, relative to the working directory, to a file holding the secret; used when
* {@code VELOCITY_SECRET} is empty and fails startup if the file cannot be read), plus the
* {@code GRUS_*} variables read by {@link GrusMinestom}.
*/
public final class DemoServer {

Expand All @@ -28,10 +39,10 @@ private DemoServer() {
}

public static void main(String[] args) {
String velocitySecret = System.getenv("VELOCITY_SECRET");
MinecraftServer server = velocitySecret == null || velocitySecret.isEmpty()
? MinecraftServer.init()
: MinecraftServer.init(new Auth.Velocity(velocitySecret));
Optional<String> velocitySecret = velocitySecret(System.getenv(), DemoServer::readSecretFile);
MinecraftServer server = velocitySecret.isPresent()
? MinecraftServer.init(new Auth.Velocity(velocitySecret.get()))
: MinecraftServer.init();

// SIGTERM (docker stop, kubelet) runs the shutdown hook, which saves and disconnects players.
Runtime.getRuntime().addShutdownHook(new Thread(MinecraftServer::stopCleanly, "grus-demo-shutdown"));
Expand Down Expand Up @@ -66,6 +77,43 @@ public static void main(String[] args) {
GrusMinestom.install().ifPresent(GrusMinestom::ready);
}

/**
* Resolves the Velocity forwarding secret. {@code VELOCITY_SECRET} wins when set and non-empty;
* otherwise a set {@code VELOCITY_SECRET_FILE} is read through {@code readFile} and stripped.
* A requested file that cannot be read or is blank is an error, so the server never starts
* without forwarding when a secret was asked for.
*/
static Optional<String> velocitySecret(Map<String, String> env, Function<Path, String> readFile) {
String secret = env.get("VELOCITY_SECRET");
if (secret != null && !secret.isEmpty()) {
return Optional.of(secret);
}
String file = env.get("VELOCITY_SECRET_FILE");
if (file == null || file.isEmpty()) {
return Optional.empty();
}
Path path = Path.of(file);
String content;
try {
content = readFile.apply(path);
} catch (RuntimeException e) {
throw new IllegalStateException("VELOCITY_SECRET_FILE is set but cannot be read: " + path, e);
}
String stripped = content == null ? "" : content.strip();
if (stripped.isEmpty()) {
throw new IllegalStateException("VELOCITY_SECRET_FILE is empty: " + path);
}
return Optional.of(stripped);
}

private static String readSecretFile(Path path) {
try {
return Files.readString(path, StandardCharsets.UTF_8);
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}

private static int parsePort(String raw) {
if (raw == null || raw.isBlank()) {
return 25565;
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,125 @@
package net.onelitefeather.grus.demo;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.assertThrows;

import java.nio.file.Path;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.function.Function;
import org.junit.jupiter.api.Test;

class VelocitySecretTest {

private static final String FILE_KEY = "VELOCITY_SECRET_FILE";

@Test
void returnsEmptyWhenNeitherVariableIsSet() {
Optional<String> secret = DemoServer.velocitySecret(Map.of(), failingReader());

assertFalse(secret.isPresent(), "no forwarding secret must be configured when no variable is set");
}

@Test
void returnsEnvSecretWithoutReadingTheFile() {
Map<String, String> env = Map.of("VELOCITY_SECRET", "from-env", FILE_KEY, "/run/secret");

Optional<String> secret = DemoServer.velocitySecret(env, failingReader());

assertEquals(Optional.of("from-env"), secret, "an env secret must win over the file");
}

@Test
void readsSecretFromFileWhenEnvSecretIsAbsent() {
Map<String, String> env = Map.of(FILE_KEY, "secrets/velocity.txt");

Optional<String> secret = DemoServer.velocitySecret(env, readerReturning("secrets/velocity.txt", "from-file"));

assertEquals(Optional.of("from-file"), secret, "the file content must be used as the secret");
}

@Test
void readsSecretFromFileWhenEnvSecretIsEmpty() {
Map<String, String> env = Map.of("VELOCITY_SECRET", "", FILE_KEY, "secrets/velocity.txt");

Optional<String> secret = DemoServer.velocitySecret(env, readerReturning("secrets/velocity.txt", "from-file"));

assertEquals(Optional.of("from-file"), secret, "an empty env secret must not block the file");
}

@Test
void trimsTrailingNewlineFromFileSecret() {
Map<String, String> env = Map.of(FILE_KEY, "velocity.txt");

Optional<String> secret = DemoServer.velocitySecret(env, readerReturning("velocity.txt", " s3cret\n"));

assertEquals(Optional.of("s3cret"), secret, "surrounding whitespace of the file must be stripped");
}

@Test
void resolvesFileSecretPathExactlyAsGiven() {
List<Path> requested = new ArrayList<>();
Function<Path, String> reader = path -> {
requested.add(path);
return "secret";
};

DemoServer.velocitySecret(Map.of(FILE_KEY, "config/velocity.txt"), reader);

assertEquals(List.of(Path.of("config/velocity.txt")), requested,
"a relative path must be handed to the reader unchanged so it resolves against the working directory");
}

@Test
void failsWhenRequestedFileCannotBeRead() {
Map<String, String> env = Map.of(FILE_KEY, "missing/velocity.txt");
Function<Path, String> reader = path -> {
throw new IllegalStateException("no such file");
};

IllegalStateException error = assertThrows(IllegalStateException.class,
() -> DemoServer.velocitySecret(env, reader));

assertTrue(error.getMessage().contains("missing/velocity.txt"),
"the error must name the file so the operator can fix the mount or path");
}

@Test
void failsWhenRequestedFileIsBlank() {
Map<String, String> env = Map.of(FILE_KEY, "velocity.txt");

IllegalStateException error = assertThrows(IllegalStateException.class,
() -> DemoServer.velocitySecret(env, readerReturning("velocity.txt", " \n")));

assertTrue(error.getMessage().contains("empty"),
"a blank secret file must not silently start the server without forwarding");
}

@Test
void ignoresBlankFileVariableWhenNoSecretIsSet() {
Map<String, String> env = new HashMap<>();
env.put(FILE_KEY, "");

Optional<String> secret = DemoServer.velocitySecret(env, failingReader());

assertEquals(Optional.empty(), secret, "an empty file variable counts as unset");
}

private static Function<Path, String> failingReader() {
return path -> {
throw new AssertionError("the file must not be read: " + path);
};
}

private static Function<Path, String> readerReturning(String expectedPath, String content) {
return path -> {
assertEquals(Path.of(expectedPath), path, "unexpected file requested");
return content;
};
}
}