diff --git a/CHANGELOG.md b/CHANGELOG.md index 04cefbb..77b1eb1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,20 @@ # Changelog +## 1.2.0 (2026-11-16) + +### Upgrading from 1.1.x + +Replace the JAR and restart. Your `config.yml` and `messages.yml` keep working unchanged and behave as before: every new setting is optional and off when missing, and missing new messages use the bundled text. The new `origingate_list` table is created automatically. To use the new features, copy the whole new section from the [default config](https://github.com/kaizen-network/OriginGate/blob/main/core/src/main/resources/config.yml): a `discord` or `accounts-per-ip` section with a missing inner key is refused. + +### Added + +- `allow-networks` rule: lets in networks you list by AS number when the `vpn`, `proxy`, or `hosting` rule would kick them, for example a school or mobile carrier that a provider wrongly flags. `deny-networks` and `country` still apply. Off by default. +- Storage for allow and deny list entries (table `origingate_list`, created automatically). Entries can expire, carry a note, and are kept in memory, so logins never wait on the database. +- The allow and deny lists are checked on every login before any lookup. A deny list entry kicks with the new `deny-list` rule and message (`kick.deny-list`, bundled text is used when missing). An allow list entry lets the player in with no lookup. `origingate status` shows the entry counts. The hourly cleanup deletes expired entries. +- Commands `origingate allow` and `origingate deny` with `add [duration] [note]`, `remove`, and `list [page]`, with separate permissions `origingate.command.allow` and `origingate.command.deny`. `deny add` disconnects matching players who are online on that server. +- `accounts-per-ip` rule: kicks a player when `max` players (1 to 100, default 3) are already online from exactly the same address, with the new `accounts-per-ip` message (`kick.accounts-per-ip`, bundled text is used when missing). It counts players on this server or proxy only, has no bypass permissions (use the allow list), and is off by default. +- Discord webhook: set `discord.webhook-url` to post kicks, bypasses, and lookup problems and recoveries to a Discord channel. Posts within 5 seconds are combined, up to 10 lines each, then `And more.`. Player and network text is escaped and posts never ping anyone. IP addresses are left out unless `discord.show-ip` is `true`. The URL must be https, is never logged, and the webhook is off while it is empty. `origingate status` shows `Discord webhook: on` or `off`. + ## 1.1.1 (2026-11-07) ### Fixed diff --git a/MODRINTH.md b/MODRINTH.md index 346762d..0d01d0d 100644 --- a/MODRINTH.md +++ b/MODRINTH.md @@ -5,9 +5,11 @@ Kick players who connect through a VPN or proxy, or from a country you do not al ## Features - Rules for VPNs, proxies (with allowed countries), hosting and datacenter networks, country allowlists or denylists, networks by AS number or name, and IP addresses or ranges you list. -- Every rule has its own bypass permissions, plus a global bypass by player, IP, or permission. +- Most rules have their own bypass permissions (the deny-list and accounts-per-ip rules have none, and allow-networks is an allow rule), plus a global bypass by player, IP, or permission. - IP data from proxycheck.io, IPHub, ip-api.com, IPinfo, or a local MaxMind GeoLite2 file. Combine them, with fallback to the next one. - Each IP is looked up at most once every 30 days by default, saved in SQLite or MySQL/MariaDB. +- Allow and deny lists you manage with `origingate allow` and `origingate deny`, with optional expiry, and a rule that lets in networks you list by AS number. +- A limit on players online from one address (`accounts-per-ip`), and an optional Discord webhook for kicks and bypasses. - Dry-run mode shows who would be kicked, without kicking anyone. - One console line per check, daily log files, and staff alerts in chat, including when a lookup provider stops answering. `origingate status` shows how lookups are doing. - A lookups-per-minute limit keeps bot floods from using up your provider's daily quota. diff --git a/README.md b/README.md index fd324d2..0d8a7e7 100644 --- a/README.md +++ b/README.md @@ -6,8 +6,9 @@ OriginGate checks where each player connects from on Bukkit/Spigot/Paper, Bungee - IP data from proxycheck.io, IPHub, ip-api.com, IPinfo, or a local MaxMind GeoLite2 file. You choose which, and can combine them. - Lookups are saved (SQLite, or MySQL/MariaDB), so each IP is looked up at most once every 30 days by default. -- Rules for VPNs, proxies, hosting networks, countries, and networks or addresses you list. Every rule is optional and has its own bypass permissions. +- Rules for VPNs, proxies, hosting networks, countries, and networks or addresses you list. Every rule is optional. Most have their own bypass permissions; the deny-list and accounts-per-ip rules have none (use the allow list), and allow-networks is an allow rule. - Staff alerts when a lookup provider stops answering, `origingate status`, and a lookups-per-minute limit against bot floods. +- Allow and deny lists you manage with commands, entries that can expire, a limit on players per address, and an optional Discord webhook. - Dry-run mode shows what would happen without kicking anyone. ## Requirements diff --git a/core/src/main/java/io/github/origingate/core/Commands.java b/core/src/main/java/io/github/origingate/core/Commands.java index ab88d45..dac4dd8 100644 --- a/core/src/main/java/io/github/origingate/core/Commands.java +++ b/core/src/main/java/io/github/origingate/core/Commands.java @@ -1,30 +1,44 @@ package io.github.origingate.core; +import io.github.origingate.core.lists.ListEntry; import io.github.origingate.core.lookup.IpInfo; import io.github.origingate.core.lookup.LookupService; import io.github.origingate.core.net.Addresses; import io.github.origingate.core.report.DecisionLine; import io.github.origingate.core.rules.Decision; import io.github.origingate.core.rules.LoginAttempt; +import io.github.origingate.core.rules.Rule; import java.net.InetAddress; +import java.time.Instant; import java.time.ZoneId; import java.time.format.DateTimeFormatter; import java.util.ArrayList; import java.util.List; import java.util.Locale; +import java.util.Arrays; import java.util.Optional; import java.util.concurrent.CompletableFuture; import java.util.concurrent.TimeUnit; +import java.util.function.Predicate; +import java.util.regex.Matcher; +import java.util.regex.Pattern; -/** {@code /origingate check|status|reload|cache clear}, independent of the platform. */ +/** {@code /origingate check|status|reload|cache clear|allow|deny}, independent of the platform. */ public final class Commands { public static final String CHECK = "origingate.command.check"; public static final String RELOAD = "origingate.command.reload"; public static final String CACHE = "origingate.command.cache"; public static final String STATUS = "origingate.command.status"; + public static final String ALLOW = "origingate.command.allow"; + public static final String DENY = "origingate.command.deny"; /** Every command permission, for platforms that look them up before running a command elsewhere. */ - public static final List PERMISSIONS = io.github.origingate.core.util.Compat.list(CHECK, STATUS, RELOAD, CACHE); + public static final List PERMISSIONS = io.github.origingate.core.util.Compat.list(CHECK, STATUS, RELOAD, CACHE, ALLOW, DENY); + private static final DateTimeFormatter LIST_TIME = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm z"); + private static final Pattern DURATION = Pattern.compile("([0-9]+)([smhdw])"); + private static final int PAGE_SIZE = 10; + private static final int MAX_NOTE = 255; + private static final long MAX_SECONDS = 3650L * 86400; private static final DateTimeFormatter TIME = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss z"); public interface Sender { @@ -32,6 +46,9 @@ public interface Sender { /** May be called from any thread. */ void reply(String line); + + /** Who ran the command, for the list entries they add. */ + default String name() { return "console"; } } public interface Platform { @@ -45,6 +62,9 @@ public interface Platform { /** Loads the files again. Returns the message to show. */ String reload(); + + /** Disconnects every online player the test matches, with the kick message of the decision's rule. Called from a worker thread. */ + default void kick(Predicate who, Decision decision) { } } private final Platform platform; @@ -92,10 +112,185 @@ public void execute(String[] args, Sender sender) { clear(args[2], sender); break; } + case "allow": + case "deny": { + ListEntry.Kind kind = kindOf(sub); + if (!allowed(sender, permission(kind))) return; + list(kind, args, sender); + break; + } default: usage(sender); } } + private static ListEntry.Kind kindOf(String word) { + return word.equalsIgnoreCase("allow") ? ListEntry.Kind.ALLOW : word.equalsIgnoreCase("deny") ? ListEntry.Kind.DENY : null; + } + + private static String permission(ListEntry.Kind kind) { return kind == ListEntry.Kind.ALLOW ? ALLOW : DENY; } + + private static String listUsage(ListEntry.Kind kind) { + return "Usage: /origingate " + kind.id() + " add [duration] [note], remove , list [page]"; + } + + private void list(ListEntry.Kind kind, String[] args, Sender sender) { + String action = args.length < 2 ? "" : args[1].toLowerCase(Locale.ROOT); + int page = 1; + boolean valid; + switch (action) { + case "add": valid = args.length >= 3; break; + case "remove": valid = args.length == 3; break; + case "list": + valid = args.length <= 3; + if (valid && args.length == 3) { + try { + page = Integer.parseInt(args[2]); + } catch (NumberFormatException ex) { + page = 0; + } + valid = page >= 1; + } + break; + default: valid = false; + } + if (!valid) { + sender.reply(listUsage(kind)); + return; + } + OriginGateRuntime runtime = running(sender); + if (runtime == null) return; + if (action.equals("add")) add(runtime, kind, args, sender); + else if (action.equals("remove")) remove(runtime, kind, args[2], sender); + else show(runtime, kind, page, sender); + } + + private void add(OriginGateRuntime runtime, ListEntry.Kind kind, String[] args, Sender sender) { + String target; + try { + target = ListEntry.normalize(args[2]); + } catch (IllegalArgumentException ex) { + sender.reply(ex.getMessage()); + return; + } + Instant now = Instant.now(); + Instant expires = null; + int noteFrom = 3; + if (args.length > 3) { + String word = args[3].toLowerCase(Locale.ROOT); + Matcher duration = DURATION.matcher(word); + if (word.equals("never")) { + noteFrom = 4; + } else if (duration.matches()) { + long seconds = seconds(duration); + if (seconds < 1 || seconds > MAX_SECONDS) { + sender.reply("Durations go from 1s to 3650d, or never."); + return; + } + expires = now.plusSeconds(seconds); + noteFrom = 4; + } else if (!word.isEmpty() && Character.isDigit(word.charAt(0))) { + // A mistyped duration (30min, 1y) would otherwise start the note and the entry would never expire. + sender.reply(args[3] + " is not a duration. Use s, m, h, d, or w, like 30m or 7d. For a note that starts with a number, put never first."); + return; + } + } + String note = String.join(" ", Arrays.copyOfRange(args, noteFrom, args.length)); + if (note.length() > MAX_NOTE) { + sender.reply("Notes can be up to " + MAX_NOTE + " characters."); + return; + } + ListEntry entry = new ListEntry(kind, target, expires, note.isEmpty() ? null : note, sender.name(), now); + // Replacing the target's entry on the other list needs that list's permission too. + ListEntry.Kind other = kind == ListEntry.Kind.ALLOW ? ListEntry.Kind.DENY : ListEntry.Kind.ALLOW; + runtime.lists().add(entry, sender.hasPermission(permission(other))).whenComplete((added, error) -> { + if (error != null) { + sender.reply("Could not change the " + kind.id() + " list: " + Text.message(error)); + return; + } + if (!added) { + sender.reply(target + " is on the " + other.id() + " list. Changing that list needs " + permission(other) + "."); + return; + } + boolean dryRun = runtime.config().dryRun(); + if (kind == ListEntry.Kind.DENY && !dryRun) { + // Exactly the players the login check would now turn away by the deny list (bypasses and allow entries spare the rest). + try { + platform.kick(attempt -> { + try { + Optional verdict = runtime.gate().beforeLookup(attempt); + return verdict.isPresent() && verdict.get().outcome() == Decision.Outcome.DENY && verdict.get().rule() == Rule.DENY_LIST; + } catch (RuntimeException ex) { + return false; + } + }, new Decision(Decision.Outcome.DENY, Rule.DENY_LIST, entry.note(), null, false)); + } catch (RuntimeException ex) { + // The entry is saved, so the reply below still goes out. + } + } + String text = "Added " + target + " to the " + kind.id() + " list, " + expiry(entry.expiresAt()) + + (entry.note() == null ? "" : ", note: " + entry.note()) + "."; + if (!runtime.lists().persistent()) text += " Kept in memory only until a restart."; + if (kind == ListEntry.Kind.DENY && dryRun) text += " Dry run is on: nobody online is disconnected."; + sender.reply(text); + }); + } + + /** Seconds in a duration such as 7d, or -1 when the number is too big to be in range. */ + private static long seconds(Matcher duration) { + String digits = duration.group(1); + if (digits.length() > 10) return -1; + long unit; + switch (duration.group(2)) { + case "s": unit = 1; break; + case "m": unit = 60; break; + case "h": unit = 3600; break; + case "d": unit = 86400; break; + default: unit = 604800; + } + return Long.parseLong(digits) * unit; + } + + private static String expiry(Instant expires) { + return expires == null ? "never expires" : "expires " + LIST_TIME.format(expires.atZone(ZoneId.systemDefault())); + } + + private void remove(OriginGateRuntime runtime, ListEntry.Kind kind, String input, Sender sender) { + String target; + try { + target = ListEntry.normalize(input); + } catch (IllegalArgumentException ex) { + sender.reply(ex.getMessage()); + return; + } + runtime.lists().remove(kind, target).whenComplete((removed, error) -> { + if (error != null) sender.reply("Could not change the " + kind.id() + " list: " + Text.message(error)); + else sender.reply(removed ? "Removed " + target + " from the " + kind.id() + " list." : target + " is not on the " + kind.id() + " list."); + }); + } + + private void show(OriginGateRuntime runtime, ListEntry.Kind kind, int page, Sender sender) { + runtime.lists().active(kind).whenComplete((entries, error) -> { + if (error != null) { + sender.reply("Could not read the " + kind.id() + " list: " + Text.message(error)); + return; + } + if (entries.isEmpty()) { + sender.reply("The " + kind.id() + " list is empty."); + return; + } + int pages = (entries.size() + PAGE_SIZE - 1) / PAGE_SIZE; + if (page > pages) { + sender.reply("There is no page " + page + ". The " + kind.id() + " list has " + pages + (pages == 1 ? " page." : " pages.")); + return; + } + sender.reply((kind == ListEntry.Kind.ALLOW ? "Allow" : "Deny") + " list, page " + page + " of " + pages + " (" + entries.size() + " entries):"); + for (ListEntry entry : entries.subList((page - 1) * PAGE_SIZE, Math.min(entries.size(), page * PAGE_SIZE))) { + sender.reply(" " + entry.target() + " (by " + entry.addedBy() + ", " + expiry(entry.expiresAt()) + + (entry.note() == null ? "" : ", note: " + entry.note()) + ")"); + } + }); + } + public List suggest(String[] args, Sender sender) { List options = new ArrayList<>(); if (args.length <= 1) { @@ -103,6 +298,8 @@ public List suggest(String[] args, Sender sender) { if (sender.hasPermission(STATUS)) options.add("status"); if (sender.hasPermission(RELOAD)) options.add("reload"); if (sender.hasPermission(CACHE)) options.add("cache"); + if (sender.hasPermission(ALLOW)) options.add("allow"); + if (sender.hasPermission(DENY)) options.add("deny"); } else if (args.length == 2 && args[0].equalsIgnoreCase("check") && sender.hasPermission(CHECK)) { options.addAll(platform.onlinePlayerNames()); } else if (args.length == 3 && args[0].equalsIgnoreCase("check") && sender.hasPermission(CHECK)) { @@ -111,12 +308,24 @@ public List suggest(String[] args, Sender sender) { options.add("clear"); } else if (args.length == 3 && args[0].equalsIgnoreCase("cache") && sender.hasPermission(CACHE)) { options.add("all"); + } else if (kindOf(args[0]) != null && sender.hasPermission(permission(kindOf(args[0])))) { + suggestList(kindOf(args[0]), args, options); } String prefix = args.length == 0 ? "" : args[args.length - 1].toLowerCase(Locale.ROOT); options.removeIf(option -> !option.toLowerCase(Locale.ROOT).startsWith(prefix)); return options; } + private void suggestList(ListEntry.Kind kind, String[] args, List options) { + if (args.length == 2) { + options.addAll(Arrays.asList("add", "remove", "list")); + } else if (args.length == 3 && args[1].equalsIgnoreCase("add")) { + options.addAll(platform.onlinePlayerNames()); + } else if (args.length == 3 && args[1].equalsIgnoreCase("remove") && platform.runtime() != null) { + options.addAll(platform.runtime().lists().targets(kind)); + } + } + private void check(String target, boolean refresh, Sender sender) { OriginGateRuntime runtime = running(sender); if (runtime == null) return; @@ -220,5 +429,7 @@ private static void usage(Sender sender) { if (sender.hasPermission(STATUS)) sender.reply(" /origingate status"); if (sender.hasPermission(RELOAD)) sender.reply(" /origingate reload"); if (sender.hasPermission(CACHE)) sender.reply(" /origingate cache clear "); + if (sender.hasPermission(ALLOW)) sender.reply(" " + listUsage(ListEntry.Kind.ALLOW).substring("Usage: ".length())); + if (sender.hasPermission(DENY)) sender.reply(" " + listUsage(ListEntry.Kind.DENY).substring("Usage: ".length())); } } diff --git a/core/src/main/java/io/github/origingate/core/OriginGateRuntime.java b/core/src/main/java/io/github/origingate/core/OriginGateRuntime.java index 5723e0d..58683ae 100644 --- a/core/src/main/java/io/github/origingate/core/OriginGateRuntime.java +++ b/core/src/main/java/io/github/origingate/core/OriginGateRuntime.java @@ -4,17 +4,23 @@ import io.github.origingate.core.config.ConfigLoader; import io.github.origingate.core.config.Messages; import io.github.origingate.core.config.OriginGateConfig; +import io.github.origingate.core.lists.AccessLists; +import io.github.origingate.core.lists.ListEntry; +import io.github.origingate.core.lists.ListTable; import io.github.origingate.core.lookup.LookupService; import io.github.origingate.core.lookup.MemoryCache; import io.github.origingate.core.lookup.Providers; import io.github.origingate.core.report.DecisionFile; +import io.github.origingate.core.report.DiscordWebhook; import io.github.origingate.core.rules.Gate; +import io.github.origingate.core.rules.OnlineCount; import io.github.origingate.core.storage.IpStorage; import io.github.origingate.core.storage.SqlIpStorage; import io.github.origingate.core.storage.SqliteUnavailableException; import java.io.IOException; import java.io.InputStream; +import java.net.URI; import io.github.origingate.core.net.HttpTransport; import java.nio.file.Files; import java.nio.file.Path; @@ -23,6 +29,8 @@ import java.time.Duration; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.CompletableFuture; +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; @@ -47,7 +55,10 @@ public final class OriginGateRuntime implements AutoCloseable { private final Providers providers; private final ThreadPoolExecutor workers; private final Gate gate; + private final AccessLists lists; private final DecisionFile decisionFile; + /** Null when {@code discord.webhook-url} is empty. */ + private volatile DiscordWebhook webhook; private final Clock clock; private final LookupStats stats; /** False once replaced or closed, so a retired runtime sends no more alerts. */ @@ -56,12 +67,15 @@ public final class OriginGateRuntime implements AutoCloseable { private final String storageName; /** Why storage is memory-only, or null. */ private final String storageProblem; + /** Re-reads persistent lists every 30 seconds; null for memory-only lists. */ + private final ScheduledExecutorService listTimer; private volatile boolean closed; private OriginGateRuntime(OriginGateConfig config, Messages messages, IpStorage storage, HttpTransport http, - Providers providers, ThreadPoolExecutor workers, Gate gate, DecisionFile decisionFile, + Providers providers, ThreadPoolExecutor workers, Gate gate, AccessLists lists, DecisionFile decisionFile, + DiscordWebhook webhook, Clock clock, LookupStats stats, AtomicBoolean current, String storageName, - String storageProblem) { + String storageProblem, ScheduledExecutorService listTimer) { this.config = config; this.messages = messages; this.storage = storage; @@ -69,12 +83,15 @@ private OriginGateRuntime(OriginGateConfig config, Messages messages, IpStorage this.providers = providers; this.workers = workers; this.gate = gate; + this.lists = lists; this.decisionFile = decisionFile; + this.webhook = webhook; this.clock = clock; this.stats = stats; this.current = current; this.storageName = storageName; this.storageProblem = storageProblem; + this.listTimer = listTimer; } /** Copies the default config.yml and messages.yml when they do not exist yet. */ @@ -103,6 +120,21 @@ public static OriginGateRuntime load(Path dataDirectory, Log baseLog, LookupStat /** {@code namesUnverified}: anyone may join with any name, so name and permission bypasses get a caution. */ public static OriginGateRuntime load(Path dataDirectory, Log baseLog, LookupStats stats, Alerts alerts, boolean namesUnverified) throws ConfigException, SQLException { + return load(dataDirectory, baseLog, stats, alerts, namesUnverified, OnlineCount.NONE); + } + + public static OriginGateRuntime load(Path dataDirectory, Log baseLog, LookupStats stats, Alerts alerts, + boolean namesUnverified, OnlineCount online) throws ConfigException, SQLException { + return load(dataDirectory, baseLog, stats, alerts, namesUnverified, online, null); + } + + /** + * {@code online} counts the players connected from one address, for accounts-per-ip. {@code previous} is the lists + * of the runtime being replaced, or null, so a reload does not drop entries. + */ + public static OriginGateRuntime load(Path dataDirectory, Log baseLog, LookupStats stats, Alerts alerts, + boolean namesUnverified, OnlineCount online, AccessLists previous) + throws ConfigException, SQLException { OriginGateConfig config = ConfigLoader.load(dataDirectory); Messages messages = Messages.load(dataDirectory); Log log = Log.withDebug(baseLog, config.consoleLog() == OriginGateConfig.ConsoleLog.DEBUG); @@ -111,9 +143,11 @@ public static OriginGateRuntime load(Path dataDirectory, Log baseLog, LookupStat IpStorage storage; String storageName = settings.type(); String storageProblem = null; + boolean storageReady = true; if (settings.type().equals("mysql")) { SqlIpStorage mysql = SqlIpStorage.mysql(settings.mysql()); - if (!mysql.ready()) { + storageReady = mysql.ready(); + if (!storageReady) { log.warn("The database cannot be reached. OriginGate keeps checking connections without saved lookups " + "and sets up the table once the database answers.", null); } @@ -153,9 +187,28 @@ public static OriginGateRuntime load(Path dataDirectory, Log baseLog, LookupStat config.lookup().maxLookupsPerMinute(), stats, whileCurrent, // Only answers that a rule acts on are kept for a whole IPv6 /64; clean answers stay per address. info -> Gate.match(config.rules(), info).isPresent()); + boolean persistent = storage instanceof ListTable; + // With the database down, a second blocking connection here would stall startup; the timer reads the lists later. + AccessLists lists = AccessLists.load(persistent ? (ListTable) storage : ListTable.memory(), persistent, clock, workers, log, + previous, storageReady); + ScheduledExecutorService listTimer = persistent ? listTimer(lists) : null; DecisionFile decisionFile = config.logFile() ? new DecisionFile(dataDirectory.resolve("logs"), clock) : null; - return new OriginGateRuntime(config, messages, storage, http, providers, workers, new Gate(config, lookups, log, namesUnverified), - decisionFile, clock, stats, current, storageName, storageProblem); + DiscordWebhook webhook = config.discord().enabled() + ? new DiscordWebhook(URI.create(config.discord().webhookUrl()), config.discord().showIp(), http, log, "OriginGate/" + VERSION) + : null; + return new OriginGateRuntime(config, messages, storage, http, providers, workers, + new Gate(config, lookups, log, namesUnverified, lists, online), lists, decisionFile, webhook, clock, stats, current, storageName, storageProblem, listTimer); + } + + private static ScheduledExecutorService listTimer(AccessLists lists) { + ScheduledExecutorService timer = Executors.newSingleThreadScheduledExecutor(task -> { + Thread thread = new Thread(task, "OriginGate Lists"); + thread.setDaemon(true); + return thread; + }); + long seconds = AccessLists.REFRESH.getSeconds(); + timer.scheduleWithFixedDelay(lists::refresh, seconds, seconds, TimeUnit.SECONDS); + return timer; } private static java.util.concurrent.ThreadFactory threads() { @@ -170,33 +223,37 @@ private static java.util.concurrent.ThreadFactory threads() { public static final class Cleanup { private final int rows; private final int files; + private final int listEntries; - public Cleanup(int rows, int files) { + public Cleanup(int rows, int files, int listEntries) { this.rows = rows; this.files = files; + this.listEntries = listEntries; } public int rows() { return rows; } public int files() { return files; } + public int listEntries() { return listEntries; } @Override public boolean equals(Object other) { if (this == other) return true; if (!(other instanceof Cleanup)) return false; Cleanup that = (Cleanup) other; return java.util.Objects.equals(rows, that.rows) - && java.util.Objects.equals(files, that.files); + && java.util.Objects.equals(files, that.files) + && java.util.Objects.equals(listEntries, that.listEntries); } - @Override public int hashCode() { return java.util.Objects.hash(rows, files); } - @Override public String toString() { return "Cleanup[" + "rows=" + rows + ", " + "files=" + files + "]"; } + @Override public int hashCode() { return java.util.Objects.hash(rows, files, listEntries); } + @Override public String toString() { return "Cleanup[" + "rows=" + rows + ", " + "files=" + files + ", " + "listEntries=" + listEntries + "]"; } } - /** Deletes stored lookups older than {@code keep-days} and log files older than {@code log-file-keep-days}. Blocks. */ + /** Deletes stored lookups older than {@code keep-days}, log files older than {@code log-file-keep-days}, and expired list entries. Blocks. */ public Cleanup deleteExpired() throws SQLException, IOException { int keepDays = config.storage().keepDays(); int rows = keepDays == 0 ? 0 : storage.deleteOlderThan(clock.instant().minus(Duration.ofDays(keepDays))); int logDays = config.logFileKeepDays(); int files = decisionFile == null || logDays == 0 ? 0 : decisionFile.deleteOlderThan(logDays); - return new Cleanup(rows, files); + return new Cleanup(rows, files, lists.deleteExpired()); } /** Forgets one IP, or every IP with "all", in memory and in OriginGate's own table. */ @@ -226,6 +283,8 @@ public CompletableFuture clearCache(String target) { public Gate gate() { return gate; } + public AccessLists lists() { return lists; } + /** The lines of {@code origingate status}: lookups since the plugin started, the budget, and each provider. */ public List status() { List lines = new ArrayList<>(); @@ -241,6 +300,8 @@ public List status() { : lookups.budgetUsed() + " of " + lookups.budgetPerMinute() + " lookups in the last minute")); lines.add("Memory cache: " + lookups.cache().size() + " entries. Storage: " + storageName + (storageProblem == null ? "" : " (" + storageProblem + ")")); + lines.add("Lists: " + lists.count(ListEntry.Kind.ALLOW) + " allow and " + lists.count(ListEntry.Kind.DENY) + " deny entries"); + lines.add("Discord webhook: " + (webhook == null ? "off" : "on")); lines.add("Providers (" + providers.chain().describe() + "):"); for (String line : providers.chain().status()) lines.add(" " + line); lines.add("On lookup failure: " + config.lookup().onFailure().name().toLowerCase(java.util.Locale.ROOT) @@ -252,6 +313,16 @@ public List status() { /** For the startup line, for example "country from maxmind, proxycheck | vpn from proxycheck". */ public String lookupSummary() { return providers.chain().describe(); } + /** Null when {@code discord.webhook-url} is empty. */ + public DiscordWebhook webhook() { return webhook; } + + /** For tests: swaps in a webhook that posts to a local server, since the config only accepts https. */ + void attachWebhook(DiscordWebhook replacement) { + DiscordWebhook old = webhook; + webhook = replacement; + if (old != null) old.close(); + } + /** Null when {@code log-file: false}. */ public DecisionFile decisionFile() { return decisionFile; } @@ -285,6 +356,7 @@ public void retire() { if (closed) return; closed = true; current.set(false); + if (listTimer != null) listTimer.shutdownNow(); workers.shutdown(); try { // The HTTP client refuses new requests once shut down, so wait for queued lookups first. @@ -293,6 +365,8 @@ public void retire() { Thread.currentThread().interrupt(); } providers.close(); + DiscordWebhook hook = webhook; + if (hook != null) hook.close(); http.close(); storage.close(); } diff --git a/core/src/main/java/io/github/origingate/core/RuntimeController.java b/core/src/main/java/io/github/origingate/core/RuntimeController.java index e65be5f..b37e58b 100644 --- a/core/src/main/java/io/github/origingate/core/RuntimeController.java +++ b/core/src/main/java/io/github/origingate/core/RuntimeController.java @@ -2,6 +2,7 @@ import io.github.origingate.core.config.OriginGateConfig; import io.github.origingate.core.report.DecisionLine; +import io.github.origingate.core.report.DiscordWebhook; import io.github.origingate.core.rules.*; import java.nio.file.Path; import java.util.*; @@ -25,6 +26,7 @@ public interface StaffAlerts { private final Supplier mode; private final LookupStats stats = new LookupStats(); private final Alerts alerts; + private final OnlineCount online; private final AtomicInteger droppedReports = new AtomicInteger(); private final ThreadPoolExecutor reports = new ThreadPoolExecutor(1, 1, 30, TimeUnit.SECONDS, new ArrayBlockingQueue<>(256), task -> { @@ -42,6 +44,12 @@ public RuntimeController(Path directory, Log log) { /** {@code mode} tells how the platform checks player names, for the offline-mode warning. */ public RuntimeController(Path directory, Log log, Supplier mode, StaffAlerts staff) { + this(directory, log, mode, staff, OnlineCount.NONE); + } + + /** {@code online} counts the players connected from one address, for accounts-per-ip. */ + public RuntimeController(Path directory, Log log, Supplier mode, StaffAlerts staff, OnlineCount online) { + this.online = online; this.directory = directory; this.log = log; this.mode = mode; @@ -50,12 +58,20 @@ public RuntimeController(Path directory, Log log, Supplier 0 || cleanup.files() > 0) { - log.info("Deleted " + cleanup.rows() + " expired lookups and " + cleanup.files() + " old log files"); + if (cleanup.rows() > 0 || cleanup.files() > 0 || cleanup.listEntries() > 0) { + log.info("Deleted " + cleanup.rows() + " expired lookups, " + cleanup.files() + " old log files, and " + + cleanup.listEntries() + " expired list entries"); } } catch (Exception ex) { log.warn("Could not delete expired OriginGate data: " + Text.message(ex), null); @@ -122,6 +141,9 @@ public void cleanup() { /** Decision logging never blocks platform events or the shared lookup deadline thread. */ public void report(OriginGateRuntime active, LoginAttempt attempt, Decision decision) { if (closed) return; + // Before the early return below: the webhook posts kicks and bypasses whatever the console and log file show. + DiscordWebhook webhook = active.webhook(); + if (webhook != null) webhook.decision(attempt, decision); if (!active.config().consoleLog().shows(decision) && (active.decisionFile() == null || decision.rule() == null)) return; try { reports.execute(() -> { diff --git a/core/src/main/java/io/github/origingate/core/config/ConfigLoader.java b/core/src/main/java/io/github/origingate/core/config/ConfigLoader.java index 6c20d20..5e6d7f7 100644 --- a/core/src/main/java/io/github/origingate/core/config/ConfigLoader.java +++ b/core/src/main/java/io/github/origingate/core/config/ConfigLoader.java @@ -61,7 +61,7 @@ public static OriginGateConfig load(Path dataDirectory) throws ConfigException { Path root = dataDirectory.toAbsolutePath().normalize(); YamlSection config = YamlSection.load(root.resolve("config.yml")); config.allowOnly("config-version", "dry-run", "console-log", "lookup", "storage", "bypass", "rules", "alerts", "log-file", - "log-file-keep-days"); + "log-file-keep-days", "discord"); config.integer("config-version", 1, 1); Lookup lookup = lookup(root, config.section("lookup")); Rules rules = rules(config.section("rules")); @@ -73,13 +73,40 @@ public static OriginGateConfig load(Path dataDirectory) throws ConfigException { throw new ConfigException("rules.hosting needs proxycheck or ip-api in lookup.vpn-from; the other providers " + "do not report hosting networks separately"); } - if (rules.denyNetworks().enabled() && lookup.inUse().equals(io.github.origingate.core.util.Compat.list("maxmind"))) { + boolean maxmindOnly = lookup.inUse().equals(io.github.origingate.core.util.Compat.list("maxmind")); + if (rules.denyNetworks().enabled() && maxmindOnly) { throw new ConfigException("rules.deny-networks needs a provider other than maxmind; MaxMind country files have " + "no ASN or organisation"); } + if (rules.allowNetworks().enabled() && maxmindOnly) { + throw new ConfigException("rules.allow-networks needs a provider other than maxmind; MaxMind country files have " + + "no ASN or organisation"); + } return new OriginGateConfig(config.bool("dry-run"), config.choice("console-log", OriginGateConfig.ConsoleLog.class), lookup, storage(root, config.section("storage")), bypass(config.section("bypass")), rules, - alerts(config.section("alerts")), config.bool("log-file"), config.integer("log-file-keep-days", 0, 3650)); + alerts(config.section("alerts")), config.bool("log-file"), config.integer("log-file-keep-days", 0, 3650), + discord(config)); + } + + /** Added in 1.2.0; a config from before has no such section, which means the webhook is off. */ + private static OriginGateConfig.Discord discord(YamlSection config) throws ConfigException { + if (!config.has("discord")) return new OriginGateConfig.Discord("", false); + YamlSection section = config.section("discord"); + section.allowOnly("webhook-url", "show-ip"); + String url = section.text("webhook-url", 0, 512).trim(); + boolean showIp = section.bool("show-ip"); + if (url.isEmpty()) return new OriginGateConfig.Discord("", showIp); + // The URL is a secret, so no message here repeats it. + java.net.URI uri; + try { + uri = new java.net.URI(url); + } catch (java.net.URISyntaxException ex) { + throw new ConfigException(section.key("webhook-url") + " is not a valid URL"); + } + if (!"https".equalsIgnoreCase(uri.getScheme()) || uri.getHost() == null) { + throw new ConfigException(section.key("webhook-url") + " must be an https URL, or empty to turn the webhook off"); + } + return new OriginGateConfig.Discord(url, showIp); } private static Lookup lookup(Path root, YamlSection lookup) throws ConfigException { @@ -237,7 +264,7 @@ private static Bypass bypass(YamlSection bypass) throws ConfigException { } private static Rules rules(YamlSection rules) throws ConfigException { - rules.allowOnly("deny-addresses", "deny-networks", "vpn", "proxy", "hosting", "country"); + rules.allowOnly("deny-addresses", "accounts-per-ip", "deny-networks", "allow-networks", "vpn", "proxy", "hosting", "country"); YamlSection deny = rules.section("deny-addresses"); deny.allowOnly("enabled", "list", "bypass-permissions"); YamlSection vpn = rules.section("vpn"); @@ -248,7 +275,9 @@ private static Rules rules(YamlSection rules) throws ConfigException { country.allowOnly("enabled", "mode", "countries", "bypass-permissions"); return new Rules( new AddressRule(deny.bool("enabled"), ranges(deny, "list"), permissions(deny, "bypass-permissions")), - denyNetworks(rules), + accountsPerIp(rules), + networks(rules, "deny-networks", true), + networks(rules, "allow-networks", false), new BasicRule(vpn.bool("enabled"), permissions(vpn, "bypass-permissions")), new ProxyRule(proxy.bool("enabled"), countries(proxy, "allowed-countries"), permissions(proxy, "bypass-permissions")), hosting(rules), @@ -256,6 +285,14 @@ private static Rules rules(YamlSection rules) throws ConfigException { countries(country, "countries"), permissions(country, "bypass-permissions"))); } + /** Added in 1.2.0; a config from before has no such section, which means the rule is off. */ + private static OriginGateConfig.AccountsRule accountsPerIp(YamlSection rules) throws ConfigException { + if (!rules.has("accounts-per-ip")) return new OriginGateConfig.AccountsRule(false, 3); + YamlSection section = rules.section("accounts-per-ip"); + section.allowOnly("enabled", "max"); + return new OriginGateConfig.AccountsRule(section.bool("enabled"), section.integer("max", 1, 100)); + } + /** Added in 1.1.0; a config from before has no such section, which means the rule is off. */ private static BasicRule hosting(YamlSection rules) throws ConfigException { if (!rules.has("hosting")) return new BasicRule(false, io.github.origingate.core.util.Compat.list()); @@ -264,12 +301,13 @@ private static BasicRule hosting(YamlSection rules) throws ConfigException { return new BasicRule(hosting.bool("enabled"), permissions(hosting, "bypass-permissions")); } - /** Added in 1.1.0; a config from before has no such section, which means the rule is off. */ - private static NetworkRule denyNetworks(YamlSection rules) throws ConfigException { + /** deny-networks (1.1.0) and allow-networks (1.2.0); a config from before has no such section, which means the rule is off. */ + private static NetworkRule networks(YamlSection rules, String name, boolean hasBypassPermissions) throws ConfigException { List none = io.github.origingate.core.util.Compat.list(); - if (!rules.has("deny-networks")) return new NetworkRule(false, none, none, none); - YamlSection section = rules.section("deny-networks"); - section.allowOnly("enabled", "asns", "organisations", "bypass-permissions"); + if (!rules.has(name)) return new NetworkRule(false, none, none, none); + YamlSection section = rules.section(name); + if (hasBypassPermissions) section.allowOnly("enabled", "asns", "organisations", "bypass-permissions"); + else section.allowOnly("enabled", "asns"); List asns = new ArrayList<>(); for (String value : section.list("asns", MAX_LIST)) { String asn = value.toUpperCase(Locale.ROOT); @@ -280,14 +318,16 @@ private static NetworkRule denyNetworks(YamlSection rules) throws ConfigExceptio asns.add(asn); } List organisations = new ArrayList<>(); - for (String value : section.list("organisations", MAX_LIST)) { + // allow-networks matches AS numbers only: a name match in an allow rule would let in any VPN with that text in its name. + if (hasBypassPermissions) for (String value : section.list("organisations", MAX_LIST)) { if (value.length() < 3) { throw new ConfigException(section.key("organisations") + " entries need at least 3 characters: " + value); } organisations.add(value.toLowerCase(Locale.ROOT)); } return new NetworkRule(section.bool("enabled"), io.github.origingate.core.util.Compat.listCopy(asns), - io.github.origingate.core.util.Compat.listCopy(organisations), permissions(section, "bypass-permissions")); + io.github.origingate.core.util.Compat.listCopy(organisations), + hasBypassPermissions ? permissions(section, "bypass-permissions") : none); } private static List alerts(YamlSection alerts) throws ConfigException { diff --git a/core/src/main/java/io/github/origingate/core/config/Messages.java b/core/src/main/java/io/github/origingate/core/config/Messages.java index 57514e0..db9a26d 100644 --- a/core/src/main/java/io/github/origingate/core/config/Messages.java +++ b/core/src/main/java/io/github/origingate/core/config/Messages.java @@ -3,7 +3,9 @@ import io.github.origingate.core.rules.Rule; import java.nio.file.Path; +import java.util.ArrayList; import java.util.EnumMap; +import java.util.List; import java.util.Map; /** MiniMessage templates from messages.yml. Rendering is left to the platform. */ @@ -62,10 +64,10 @@ public static Messages load(Path dataDirectory) throws ConfigException { YamlSection kick = messages.section("kick"); YamlSection defaultKick = defaults.section("kick"); Map kicks = new EnumMap<>(Rule.class); - String[] names = new String[Rule.values().length]; - for (Rule rule : Rule.values()) names[rule.ordinal()] = rule.id(); - kick.allowOnly(names); - for (Rule rule : Rule.values()) kicks.put(rule, optional(kick, defaultKick, rule.id(), 1, 4096, rule.addedLater())); + List names = new ArrayList<>(); + for (Rule rule : Rule.values()) if (rule.kicks()) names.add(rule.id()); + kick.allowOnly(names.toArray(new String[0])); + for (Rule rule : Rule.values()) if (rule.kicks()) kicks.put(rule, optional(kick, defaultKick, rule.id(), 1, 4096, rule.addedLater())); YamlSection alerts = messages.section("alerts"); YamlSection defaultAlerts = defaults.section("alerts"); alerts.allowOnly("denied", "bypassed", "lookup-problem", "lookup-recovered"); diff --git a/core/src/main/java/io/github/origingate/core/config/OriginGateConfig.java b/core/src/main/java/io/github/origingate/core/config/OriginGateConfig.java index 1749b16..ef3d88f 100644 --- a/core/src/main/java/io/github/origingate/core/config/OriginGateConfig.java +++ b/core/src/main/java/io/github/origingate/core/config/OriginGateConfig.java @@ -19,8 +19,9 @@ public final class OriginGateConfig { private final List alertPermissions; private final boolean logFile; private final int logFileKeepDays; + private final Discord discord; - public OriginGateConfig(boolean dryRun, ConsoleLog consoleLog, Lookup lookup, Storage storage, Bypass bypass, Rules rules, List alertPermissions, boolean logFile, int logFileKeepDays) { + public OriginGateConfig(boolean dryRun, ConsoleLog consoleLog, Lookup lookup, Storage storage, Bypass bypass, Rules rules, List alertPermissions, boolean logFile, int logFileKeepDays, Discord discord) { this.dryRun = dryRun; this.consoleLog = consoleLog; this.lookup = lookup; @@ -30,6 +31,7 @@ public OriginGateConfig(boolean dryRun, ConsoleLog consoleLog, Lookup lookup, St this.alertPermissions = alertPermissions; this.logFile = logFile; this.logFileKeepDays = logFileKeepDays; + this.discord = discord; } public boolean dryRun() { return dryRun; } @@ -41,6 +43,7 @@ public OriginGateConfig(boolean dryRun, ConsoleLog consoleLog, Lookup lookup, St public List alertPermissions() { return alertPermissions; } public boolean logFile() { return logFile; } public int logFileKeepDays() { return logFileKeepDays; } + public Discord discord() { return discord; } @Override public boolean equals(Object other) { if (this == other) return true; @@ -54,9 +57,34 @@ public OriginGateConfig(boolean dryRun, ConsoleLog consoleLog, Lookup lookup, St && java.util.Objects.equals(rules, that.rules) && java.util.Objects.equals(alertPermissions, that.alertPermissions) && java.util.Objects.equals(logFile, that.logFile) - && java.util.Objects.equals(logFileKeepDays, that.logFileKeepDays); + && java.util.Objects.equals(logFileKeepDays, that.logFileKeepDays) + && java.util.Objects.equals(discord, that.discord); + } + @Override public int hashCode() { return java.util.Objects.hash(dryRun, consoleLog, lookup, storage, bypass, rules, alertPermissions, logFile, logFileKeepDays, discord); } + + /** The Discord webhook. {@code webhookUrl} is a secret: empty when off, and never part of {@link #toString}. */ + public static final class Discord { + private final String webhookUrl; + private final boolean showIp; + + public Discord(String webhookUrl, boolean showIp) { + this.webhookUrl = webhookUrl; + this.showIp = showIp; + } + + public String webhookUrl() { return webhookUrl; } + public boolean showIp() { return showIp; } + public boolean enabled() { return !webhookUrl.isEmpty(); } + + @Override public boolean equals(Object other) { + if (this == other) return true; + if (!(other instanceof Discord)) return false; + Discord that = (Discord) other; + return webhookUrl.equals(that.webhookUrl) && showIp == that.showIp; + } + @Override public int hashCode() { return java.util.Objects.hash(webhookUrl, showIp); } + @Override public String toString() { return "Discord[" + "webhookUrl=" + (enabled() ? "" : "") + ", " + "showIp=" + showIp + "]"; } } - @Override public int hashCode() { return java.util.Objects.hash(dryRun, consoleLog, lookup, storage, bypass, rules, alertPermissions, logFile, logFileKeepDays); } /** How much the console shows per login. Each level includes the ones before it. */ @@ -433,16 +461,20 @@ public Bypass(List permissions, Set players, List public static final class Rules { private final AddressRule denyAddresses; + private final AccountsRule accountsPerIp; private final NetworkRule denyNetworks; + private final NetworkRule allowNetworks; private final BasicRule vpn; private final ProxyRule proxy; private final BasicRule hosting; private final CountryRule country; - public Rules(AddressRule denyAddresses, NetworkRule denyNetworks, BasicRule vpn, ProxyRule proxy, BasicRule hosting, - CountryRule country) { + public Rules(AddressRule denyAddresses, AccountsRule accountsPerIp, NetworkRule denyNetworks, NetworkRule allowNetworks, BasicRule vpn, ProxyRule proxy, + BasicRule hosting, CountryRule country) { this.denyAddresses = denyAddresses; + this.accountsPerIp = accountsPerIp; this.denyNetworks = denyNetworks; + this.allowNetworks = allowNetworks; this.vpn = vpn; this.proxy = proxy; this.hosting = hosting; @@ -450,7 +482,9 @@ public Rules(AddressRule denyAddresses, NetworkRule denyNetworks, BasicRule vpn, } public AddressRule denyAddresses() { return denyAddresses; } + public AccountsRule accountsPerIp() { return accountsPerIp; } public NetworkRule denyNetworks() { return denyNetworks; } + public NetworkRule allowNetworks() { return allowNetworks; } public BasicRule vpn() { return vpn; } public ProxyRule proxy() { return proxy; } public BasicRule hosting() { return hosting; } @@ -467,16 +501,41 @@ public List> bypassPermissions() { if (!(other instanceof Rules)) return false; Rules that = (Rules) other; return java.util.Objects.equals(denyAddresses, that.denyAddresses) + && java.util.Objects.equals(accountsPerIp, that.accountsPerIp) && java.util.Objects.equals(denyNetworks, that.denyNetworks) + && java.util.Objects.equals(allowNetworks, that.allowNetworks) && java.util.Objects.equals(vpn, that.vpn) && java.util.Objects.equals(proxy, that.proxy) && java.util.Objects.equals(hosting, that.hosting) && java.util.Objects.equals(country, that.country); } - @Override public int hashCode() { return java.util.Objects.hash(denyAddresses, denyNetworks, vpn, proxy, hosting, country); } - @Override public String toString() { return "Rules[" + "denyAddresses=" + denyAddresses + ", " + "denyNetworks=" + denyNetworks + ", " + "vpn=" + vpn + ", " + "proxy=" + proxy + ", " + "hosting=" + hosting + ", " + "country=" + country + "]"; } + @Override public int hashCode() { return java.util.Objects.hash(denyAddresses, accountsPerIp, denyNetworks, allowNetworks, vpn, proxy, hosting, country); } + @Override public String toString() { return "Rules[" + "denyAddresses=" + denyAddresses + ", " + "accountsPerIp=" + accountsPerIp + ", " + "denyNetworks=" + denyNetworks + ", " + "allowNetworks=" + allowNetworks + ", " + "vpn=" + vpn + ", " + "proxy=" + proxy + ", " + "hosting=" + hosting + ", " + "country=" + country + "]"; } } + /** accounts-per-ip: {@code max} is the most players online at once from one address. */ + public static final class AccountsRule { + private final boolean enabled; + private final int max; + + public AccountsRule(boolean enabled, int max) { + this.enabled = enabled; + this.max = max; + } + + public boolean enabled() { return enabled; } + public int max() { return max; } + + @Override public boolean equals(Object other) { + if (this == other) return true; + if (!(other instanceof AccountsRule)) return false; + AccountsRule that = (AccountsRule) other; + return enabled == that.enabled && max == that.max; + } + @Override public int hashCode() { return java.util.Objects.hash(enabled, max); } + @Override public String toString() { return "AccountsRule[" + "enabled=" + enabled + ", " + "max=" + max + "]"; } + } + public static final class AddressRule { private final boolean enabled; private final List list; diff --git a/core/src/main/java/io/github/origingate/core/lists/AccessLists.java b/core/src/main/java/io/github/origingate/core/lists/AccessLists.java new file mode 100644 index 0000000..5f68319 --- /dev/null +++ b/core/src/main/java/io/github/origingate/core/lists/AccessLists.java @@ -0,0 +1,251 @@ +package io.github.origingate.core.lists; + +import io.github.origingate.core.Log; +import io.github.origingate.core.Text; +import io.github.origingate.core.util.Compat; + +import java.net.InetAddress; +import java.sql.SQLException; +import java.time.Clock; +import java.time.Duration; +import java.time.Instant; +import java.util.ArrayList; +import java.util.Comparator; +import java.util.List; +import java.util.Optional; +import java.util.ServiceConfigurationError; +import java.util.UUID; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.Executor; +import java.util.concurrent.RejectedExecutionException; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicLong; + +/** + * The allow and deny lists, kept in memory so a login never waits on the database. The copy is read again in the + * background when it is older than {@link #REFRESH} and by a timer every {@link #REFRESH}, so entries added on another + * server that shares the database apply within about that time. Commands on this server re-read at once. + */ +public final class AccessLists { + public static final Duration REFRESH = Duration.ofSeconds(30); + + private final ListTable table; + private final boolean persistent; + private final Clock clock; + private final Executor executor; + private final Log log; + private final AtomicBoolean reading = new AtomicBoolean(); + private final AtomicLong started = new AtomicLong(); + private final Object apply = new Object(); + private long applied; + private volatile boolean failing; + private volatile List entries = Compat.list(); + private volatile Instant readAt; + + private AccessLists(ListTable table, boolean persistent, Clock clock, Executor executor, Log log) { + this.table = table; + this.persistent = persistent; + this.clock = clock; + this.executor = executor; + this.log = log; + this.readAt = clock.instant(); + } + + /** Reads the table now. When it cannot be read, starts empty, logs one warning, and tries again when stale. */ + public static AccessLists load(ListTable table, boolean persistent, Clock clock, Executor executor, Log log) { + return load(table, persistent, clock, executor, log, null, true); + } + + /** For a reload: {@code previous} is the lists of the runtime being replaced, or null. */ + public static AccessLists load(ListTable table, boolean persistent, Clock clock, Executor executor, Log log, AccessLists previous) { + return load(table, persistent, clock, executor, log, previous, true); + } + + /** + * Memory-only lists keep the entries of {@code previous}. When the table cannot be read (or {@code read} is + * false because the database is known to be down), the copy from {@code previous} is used, or none, and the + * refresh timer tries again. + */ + public static AccessLists load(ListTable table, boolean persistent, Clock clock, Executor executor, Log log, + AccessLists previous, boolean read) { + boolean sameMemory = !persistent && previous != null && !previous.persistent; + AccessLists lists = new AccessLists(sameMemory ? previous.table : table, persistent, clock, executor, log); + if (read) { + try { + // Database lists falling back to memory start from their last copy, so the entries keep applying. + if (!persistent && previous != null && previous.persistent) for (ListEntry entry : previous.entries) table.put(entry); + lists.readOrThrow(); + return lists; + } catch (SQLException | RuntimeException | ServiceConfigurationError | LinkageError ex) { + lists.firstReadFailed(previous, Text.message(ex)); + return lists; + } + } + lists.firstReadFailed(previous, null); + return lists; + } + + private void firstReadFailed(AccessLists previous, String reason) { + if (previous != null) entries = previous.entries; + readAt = clock.instant(); + failing = true; + if (reason == null) return; + log.warn("Could not read the allow and deny lists: " + reason + (previous != null + ? ". Using the entries from before the reload until the database answers." + : ". Entries do not apply until the database answers; OriginGate tries again every " + + REFRESH.getSeconds() + " seconds."), null); + } + + /** Reads the table again now, on the calling thread. The runtime calls this every {@link #REFRESH}. */ + public void refresh() { + readNow(); + } + + /** Lists that live in memory only. */ + public static AccessLists empty() { + return new AccessLists(ListTable.memory(), false, Clock.systemUTC(), Runnable::run, Log.NONE); + } + + public boolean persistent() { return persistent; } + + /** The entry that decides this login, if any. Never blocks. A player entry beats an address entry; allow beats deny. */ + public Optional match(String username, UUID uuid, InetAddress address) { + refreshIfStale(); + Instant now = clock.instant(); + ListEntry best = null; + int bestRank = -1; + for (ListEntry entry : entries) { + if (!entry.activeAt(now)) continue; + boolean hit = entry.isAddress() ? entry.matchesAddress(address) : entry.matchesPlayer(username, uuid); + if (!hit) continue; + int rank = (entry.isAddress() ? 0 : 2) + (entry.kind() == ListEntry.Kind.ALLOW ? 1 : 0); + if (rank > bestRank) { + best = entry; + bestRank = rank; + } + } + return Optional.ofNullable(best); + } + + /** Saves the entry, replacing any entry for the same target on either list. Completes with true. */ + public CompletableFuture add(ListEntry entry) { + return add(entry, true); + } + + /** + * Like {@link #add(ListEntry)}, but when {@code replaceOther} is false and the target has an unexpired entry on the + * other list (read fresh from the table), nothing is saved and it completes with false. + */ + public CompletableFuture add(ListEntry entry, boolean replaceOther) { + return submit(() -> { + if (!replaceOther) { + Instant now = clock.instant(); + for (ListEntry other : readOrThrow()) { + if (other.kind() != entry.kind() && other.target().equals(entry.target()) && other.activeAt(now)) return false; + } + } + table.put(entry); + readNow(); + return true; + }); + } + + /** Completes with true when an entry was removed. */ + public CompletableFuture remove(ListEntry.Kind kind, String target) { + return submit(() -> { + int removed = table.remove(kind, target); + readNow(); + return removed > 0; + }); + } + + /** A fresh read of the unexpired entries of one list, oldest first. */ + public CompletableFuture> active(ListEntry.Kind kind) { + return submit(() -> { + Instant now = clock.instant(); + List result = new ArrayList<>(); + for (ListEntry entry : readOrThrow()) if (entry.kind() == kind && entry.activeAt(now)) result.add(entry); + result.sort(Comparator.comparing(ListEntry::addedAt)); + return result; + }); + } + + public int deleteExpired() throws SQLException { + return table.deleteExpired(clock.instant()); + } + + public int count(ListEntry.Kind kind) { + Instant now = clock.instant(); + int count = 0; + for (ListEntry entry : entries) if (entry.kind() == kind && entry.activeAt(now)) count++; + return count; + } + + public List targets(ListEntry.Kind kind) { + Instant now = clock.instant(); + List targets = new ArrayList<>(); + for (ListEntry entry : entries) if (entry.kind() == kind && entry.activeAt(now)) targets.add(entry.target()); + return targets; + } + + private void refreshIfStale() { + if (!persistent || clock.instant().isBefore(readAt.plus(REFRESH))) return; + if (!reading.compareAndSet(false, true)) return; + try { + executor.execute(() -> { + try { + readNow(); + } finally { + reading.set(false); + } + }); + } catch (RejectedExecutionException ex) { + reading.set(false); + } + } + + /** Reads the table. A failure, also a driver that will not load, is logged once until a read works again, and the next try waits for the next refresh. */ + private void readNow() { + try { + readOrThrow(); + failing = false; + } catch (SQLException | RuntimeException | ServiceConfigurationError | LinkageError ex) { + readAt = clock.instant(); + if (!failing) log.warn("The allow and deny lists could not be read, so they may be out of date: " + Text.message(ex), null); + failing = true; + } + } + + private List readOrThrow() throws SQLException { + long order = started.incrementAndGet(); + Instant at = clock.instant(); + List read = Compat.listCopy(table.all()); + // A slow read that started before a newer one finished must not replace the newer copy. + synchronized (apply) { + if (order > applied) { + applied = order; + entries = read; + readAt = at; + } + } + return read; + } + + private CompletableFuture submit(SqlTask task) { + CompletableFuture future = new CompletableFuture<>(); + try { + executor.execute(() -> { + try { + future.complete(task.run()); + } catch (SQLException | RuntimeException | ServiceConfigurationError | LinkageError ex) { + future.completeExceptionally(ex); + } + }); + } catch (RejectedExecutionException ex) { + future.completeExceptionally(ex); + } + return future; + } + + private interface SqlTask { T run() throws SQLException; } +} diff --git a/core/src/main/java/io/github/origingate/core/lists/ListEntry.java b/core/src/main/java/io/github/origingate/core/lists/ListEntry.java new file mode 100644 index 0000000..ee90927 --- /dev/null +++ b/core/src/main/java/io/github/origingate/core/lists/ListEntry.java @@ -0,0 +1,128 @@ +package io.github.origingate.core.lists; + +import io.github.origingate.core.net.AddressRange; +import io.github.origingate.core.net.Addresses; + +import java.net.InetAddress; +import java.time.Instant; +import java.util.Locale; +import java.util.Objects; +import java.util.UUID; +import java.util.regex.Pattern; + +/** One allow or deny list entry: a player name, a UUID, an IP address, or a CIDR range. */ +public final class ListEntry { + public enum Kind { + ALLOW("allow"), DENY("deny"); + + private final String id; + + Kind(String id) { this.id = id; } + + public String id() { return id; } + + /** The kind stored under this id, or null. */ + public static Kind ofId(String id) { + for (Kind kind : values()) if (kind.id.equals(id)) return kind; + return null; + } + } + + private static final Pattern UUID_TEXT = Pattern.compile("[0-9A-Fa-f]{8}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{12}"); + private static final Pattern NAME = Pattern.compile("[A-Za-z0-9_.*-]{1,32}"); + private static final Pattern UUID_NO_DASHES = Pattern.compile("[0-9A-Fa-f]{32}"); + /** Digits and dots that did not parse as an address, such as 203.0.113.256: a typo, never a name. */ + private static final Pattern BAD_IPV4 = Pattern.compile("[0-9]+(\\.[0-9]+)+"); + + private final Kind kind; + private final String target; + private final Instant expiresAt; + private final String note; + private final String addedBy; + private final Instant addedAt; + private final AddressRange range; + + /** The target is in the form {@link #normalize} returns. A null {@code expiresAt} means never; a null note means none. */ + public ListEntry(Kind kind, String target, Instant expiresAt, String note, String addedBy, Instant addedAt) { + this.kind = Objects.requireNonNull(kind); + this.target = Objects.requireNonNull(target); + this.expiresAt = expiresAt; + this.note = note; + this.addedBy = Objects.requireNonNull(addedBy); + this.addedAt = Objects.requireNonNull(addedAt); + AddressRange parsed; + try { + parsed = AddressRange.parse(target); + } catch (IllegalArgumentException ex) { + parsed = null; + } + this.range = parsed; + } + + public Kind kind() { return kind; } + + public String target() { return target; } + + public Instant expiresAt() { return expiresAt; } + + public String note() { return note; } + + public String addedBy() { return addedBy; } + + public Instant addedAt() { return addedAt; } + + public boolean activeAt(Instant now) { return expiresAt == null || now.isBefore(expiresAt); } + + /** True for an IP address or a CIDR range, false for a name or a UUID. */ + public boolean isAddress() { return range != null; } + + public boolean matchesPlayer(String username, UUID uuid) { + if (range != null) return false; + return (username != null && target.equals(username.toLowerCase(Locale.ROOT))) + || (uuid != null && target.equals(uuid.toString())); + } + + public boolean matchesAddress(InetAddress address) { + return range != null && address != null && range.contains(address); + } + + /** + * The stored form of a target: an address or a range's network address (with {@code /prefix} only when shorter + * than the whole address), else a UUID (dashes added when left out), else a player name, in lower case. + * @throws IllegalArgumentException when the input is none of these + */ + public static String normalize(String input) { + String value = input == null ? "" : input.trim(); + int slash = value.indexOf('/'); + if (Addresses.parse(slash < 0 ? value : value.substring(0, slash)).isPresent()) { + try { + return AddressRange.parse(value).canonical(); + } catch (IllegalArgumentException ex) { + throw invalid(input); + } + } + if (BAD_IPV4.matcher(value).matches()) throw invalid(input); + if (UUID_NO_DASHES.matcher(value).matches()) value = value.replaceFirst("(.{8})(.{4})(.{4})(.{4})(.{12})", "$1-$2-$3-$4-$5"); + if (UUID_TEXT.matcher(value).matches() || NAME.matcher(value).matches()) return value.toLowerCase(Locale.ROOT); + throw invalid(input); + } + + private static IllegalArgumentException invalid(String input) { + return new IllegalArgumentException(input + " is not a player name, UUID, IP address, or CIDR range"); + } + + @Override public boolean equals(Object other) { + if (this == other) return true; + if (!(other instanceof ListEntry)) return false; + ListEntry that = (ListEntry) other; + return kind == that.kind && target.equals(that.target) && Objects.equals(expiresAt, that.expiresAt) + && Objects.equals(note, that.note) && addedBy.equals(that.addedBy) && addedAt.equals(that.addedAt); + } + + @Override public int hashCode() { return Objects.hash(kind, target, expiresAt, note, addedBy, addedAt); } + + @Override public String toString() { + return "ListEntry{" + kind.id() + " " + target + ", expiresAt=" + expiresAt + ", note=" + note + + ", addedBy=" + addedBy + ", addedAt=" + addedAt + "}"; + } +} diff --git a/core/src/main/java/io/github/origingate/core/lists/ListTable.java b/core/src/main/java/io/github/origingate/core/lists/ListTable.java new file mode 100644 index 0000000..f48a5fe --- /dev/null +++ b/core/src/main/java/io/github/origingate/core/lists/ListTable.java @@ -0,0 +1,48 @@ +package io.github.origingate.core.lists; + +import io.github.origingate.core.util.Compat; + +import java.sql.SQLException; +import java.time.Instant; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +/** Where list entries are kept. One entry per target: {@link #put} replaces any entry with the same target. */ +public interface ListTable { + List all() throws SQLException; + + void put(ListEntry entry) throws SQLException; + + /** Removes the entry for {@code target} when it is on the {@code kind} list. Returns how many rows went. */ + int remove(ListEntry.Kind kind, String target) throws SQLException; + + /** Deletes entries that expired at or before {@code now}. */ + int deleteExpired(Instant now) throws SQLException; + + /** Entries that live only in memory, for when no database can be used. */ + static ListTable memory() { + return new ListTable() { + private final Map rows = new LinkedHashMap<>(); + + @Override public synchronized List all() { return Compat.listCopy(rows.values()); } + + @Override public synchronized void put(ListEntry entry) { rows.put(entry.target(), entry); } + + @Override public synchronized int remove(ListEntry.Kind kind, String target) { + ListEntry found = rows.get(target); + if (found == null || found.kind() != kind) return 0; + rows.remove(target); + return 1; + } + + @Override public synchronized int deleteExpired(Instant now) { + List expired = new ArrayList<>(); + for (ListEntry entry : rows.values()) if (!entry.activeAt(now)) expired.add(entry.target()); + for (String target : expired) rows.remove(target); + return expired.size(); + } + }; + } +} diff --git a/core/src/main/java/io/github/origingate/core/net/AddressRange.java b/core/src/main/java/io/github/origingate/core/net/AddressRange.java index 4929a3b..6eb7b4e 100644 --- a/core/src/main/java/io/github/origingate/core/net/AddressRange.java +++ b/core/src/main/java/io/github/origingate/core/net/AddressRange.java @@ -1,6 +1,7 @@ package io.github.origingate.core.net; import java.net.InetAddress; +import java.net.UnknownHostException; import java.util.Arrays; /** A single IP address or a CIDR range such as {@code 203.0.113.0/24}. */ @@ -48,5 +49,15 @@ private static byte[] mask(byte[] bytes, int prefix) { return result; } + /** The network address, then {@code /prefix} only when the range is shorter than a whole address. */ + public String canonical() { + try { + String host = Addresses.text(InetAddress.getByAddress(network)); + return prefix < network.length * 8 ? host + "/" + prefix : host; + } catch (UnknownHostException ex) { + throw new IllegalStateException(ex); // Never: the network is always 4 or 16 bytes. + } + } + @Override public String toString() { return text; } } diff --git a/core/src/main/java/io/github/origingate/core/net/Addresses.java b/core/src/main/java/io/github/origingate/core/net/Addresses.java index 7778c3e..4d3f27f 100644 --- a/core/src/main/java/io/github/origingate/core/net/Addresses.java +++ b/core/src/main/java/io/github/origingate/core/net/Addresses.java @@ -24,6 +24,10 @@ public static Optional parse(String text) { boolean v4 = IPV4.matcher(value).matches(); boolean v6 = !v4 && value.indexOf(':') >= 0 && IPV6.matcher(value).matches(); if (!v4 && !v6) return Optional.empty(); + // Only a hex digit or ':' can start an IP literal. Anything else would make Java call the system resolver. + char first = value.charAt(0); + boolean hex = (first >= '0' && first <= '9') || (first >= 'a' && first <= 'f') || (first >= 'A' && first <= 'F'); + if (!hex && first != ':') return Optional.empty(); try { // A string that is already a literal is only validated, never resolved. return Optional.of(InetAddress.getByName(value)); diff --git a/core/src/main/java/io/github/origingate/core/net/HttpRequest.java b/core/src/main/java/io/github/origingate/core/net/HttpRequest.java index 85a51d2..49b6276 100644 --- a/core/src/main/java/io/github/origingate/core/net/HttpRequest.java +++ b/core/src/main/java/io/github/origingate/core/net/HttpRequest.java @@ -10,8 +10,10 @@ public final class HttpRequest { final Duration timeout; final String method; final Map headers; + /** Null unless the method is POST. */ + final byte[] body; private HttpRequest(Builder builder) { - uri = builder.uri; timeout = builder.timeout; method = builder.method; + uri = builder.uri; timeout = builder.timeout; method = builder.method; body = builder.body; headers = Collections.unmodifiableMap(new LinkedHashMap<>(builder.headers)); } public static Builder newBuilder(URI uri) { return new Builder(uri); } @@ -19,6 +21,7 @@ public static final class Builder { private final URI uri; private Duration timeout = Duration.ofSeconds(30); private String method = "GET"; + private byte[] body; private final Map headers = new LinkedHashMap<>(); private Builder(URI uri) { this.uri = Objects.requireNonNull(uri); @@ -30,11 +33,13 @@ public Builder timeout(Duration value) { timeout = value; return this; } public Builder header(String name, String value) { headers.put(name, value); return this; } - public Builder GET() { method = "GET"; return this; } + public Builder GET() { method = "GET"; body = null; return this; } + /** Sends {@code content} as the request body. The caller sets Content-Type. */ + public Builder POST(byte[] content) { method = "POST"; body = content.clone(); return this; } /** GET or HEAD: requests have no body. */ public Builder method(String value) { if (!"GET".equals(value) && !"HEAD".equals(value)) throw new IllegalArgumentException("Unsupported HTTP method"); - method = value; return this; + method = value; body = null; return this; } public HttpRequest build() { return new HttpRequest(this); } } diff --git a/core/src/main/java/io/github/origingate/core/net/HttpTransport.java b/core/src/main/java/io/github/origingate/core/net/HttpTransport.java index 4338ba9..a6a1c25 100644 --- a/core/src/main/java/io/github/origingate/core/net/HttpTransport.java +++ b/core/src/main/java/io/github/origingate/core/net/HttpTransport.java @@ -43,12 +43,16 @@ public HttpResponse send(HttpRequest request, HttpResponse.BodyHandler connection.setInstanceFollowRedirects(false); connection.setRequestMethod(request.method); request.headers.forEach(connection::setRequestProperty); + if (request.body != null) { + connection.setDoOutput(true); + connection.setFixedLengthStreamingMode(request.body.length); + } active.add(connection); // Whoever sets this first owns the outcome: the exchange hands over its response, or the caller gives up. final AtomicBoolean settled = new AtomicBoolean(); final Future> exchange; try { - exchange = exchanges.submit(() -> exchange(connection, handler, settled)); + exchange = exchanges.submit(() -> exchange(connection, request.body, handler, settled)); } catch (RejectedExecutionException ex) { disconnect(connection); throw new IOException("HTTP transport is closed", ex); } @@ -70,16 +74,19 @@ public HttpResponse send(HttpRequest request, HttpResponse.BodyHandler throw new IOException(cause); } } - private HttpResponse exchange(HttpURLConnection connection, HttpResponse.BodyHandler handler, AtomicBoolean settled) + private HttpResponse exchange(HttpURLConnection connection, byte[] body, HttpResponse.BodyHandler handler, AtomicBoolean settled) throws IOException { boolean handed = false; try { connection.connect(); if (settled.get()) throw new HttpTimeoutException("HTTP request timed out"); + if (body != null) { + try (OutputStream output = connection.getOutputStream()) { output.write(body); } + } int status = connection.getResponseCode(); InputStream raw = status >= 400 ? connection.getErrorStream() : connection.getInputStream(); - T body = handler.read(new Body(raw == null ? new ByteArrayInputStream(new byte[0]) : raw, connection)); - HttpResponse response = new HttpResponse<>(status, body, connection.getHeaderFields()); + T result = handler.read(new Body(raw == null ? new ByteArrayInputStream(new byte[0]) : raw, connection)); + HttpResponse response = new HttpResponse<>(status, result, connection.getHeaderFields()); if (!settled.compareAndSet(false, true)) { close(response); throw new HttpTimeoutException("HTTP request timed out"); diff --git a/core/src/main/java/io/github/origingate/core/report/DiscordWebhook.java b/core/src/main/java/io/github/origingate/core/report/DiscordWebhook.java new file mode 100644 index 0000000..13bef24 --- /dev/null +++ b/core/src/main/java/io/github/origingate/core/report/DiscordWebhook.java @@ -0,0 +1,258 @@ +package io.github.origingate.core.report; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonArray; +import com.google.gson.JsonObject; +import io.github.origingate.core.Log; +import io.github.origingate.core.Text; +import io.github.origingate.core.lookup.IpInfo; +import io.github.origingate.core.net.Addresses; +import io.github.origingate.core.net.HttpRequest; +import io.github.origingate.core.net.HttpResponse; +import io.github.origingate.core.net.HttpTransport; +import io.github.origingate.core.rules.Decision; +import io.github.origingate.core.rules.LoginAttempt; + +import java.net.URI; +import java.nio.charset.StandardCharsets; +import java.time.Duration; +import java.util.ArrayDeque; +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.TimeUnit; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +/** + * Posts kicks, bypasses, and lookup alerts to a Discord webhook. Callers only queue a line. A daemon thread posts the + * queue every 5 seconds as one message, so a flood of kicks becomes a short summary. A failed post never reaches a + * login: it is caught, logged once without the URL (a secret), and its lines are dropped. + */ +public final class DiscordWebhook implements AutoCloseable { + private static final int INTERVAL_SECONDS = 5; + private static final int SHOWN_LINES = 10; + private static final int MAX_QUEUED = 10_000; + /** 10 lines of at most this many characters, plus the "And n more." line, stay under Discord's 2000. */ + private static final int MAX_LINE = 190; + private static final String SPECIAL = "\\*_~`|>[]()#"; + private static final String HIDDEN = "IP hidden"; + /** A run of address characters with an optional /prefix; {@link Addresses#parse} confirms it. */ + private static final Pattern RUN = Pattern.compile("[0-9A-Fa-f:.]{2,45}(?:/[0-9]{1,3})?"); + private static final Pattern DOTTED_QUAD = Pattern.compile("[0-9]{1,3}(?:[.][0-9]{1,3}){3}(?:/[0-9]{1,3})?"); + private static final Gson GSON = new GsonBuilder().disableHtmlEscaping().create(); + + private final URI url; + private final boolean showIp; + private final HttpTransport http; + private final Log log; + private final String userAgent; + private final ScheduledExecutorService timer = Executors.newSingleThreadScheduledExecutor(task -> { + Thread thread = new Thread(task, "OriginGate Discord"); + thread.setDaemon(true); + return thread; + }); + /** Guards {@link #queue}, {@link #overflow}, and {@link #closed}. */ + private final Object lock = new Object(); + private final ArrayDeque queue = new ArrayDeque<>(); + private int overflow; + private boolean closed; + /** One post at a time. Also guards {@link #failing}. */ + private final Object sending = new Object(); + private boolean failing; + + public DiscordWebhook(URI url, boolean showIp, HttpTransport http, Log log, String userAgent) { + this.url = url; + this.showIp = showIp; + this.http = http; + this.log = log; + this.userAgent = userAgent; + timer.scheduleWithFixedDelay(this::flushQuietly, INTERVAL_SECONDS, INTERVAL_SECONDS, TimeUnit.SECONDS); + } + + /** Queues a kick or a bypass. Dry-run decisions and allowed logins are not posted. */ + public void decision(LoginAttempt attempt, Decision decision) { + try { + if (decision.rule() == null || decision.dryRun()) return; + String start; + if (decision.kicks()) start = "Kicked **" + escape(attempt.username()) + "** by the " + decision.rule().id() + " rule"; + else if (decision.outcome() == Decision.Outcome.BYPASS) start = "Let in **" + escape(attempt.username()) + "** with a " + decision.rule().id() + " bypass"; + else return; + StringBuilder line = new StringBuilder(start); + if (decision.note() != null) line.append(": ").append(text(decision.note())); + if (decision.lookup() != null) { + IpInfo info = decision.lookup().info(); + line.append(" (").append(text(Text.dash(info.provider()))).append(" / ") + .append(text(Text.dash(info.displayOrganisation()))).append(", ") + .append(text(Text.dash(info.country()))).append(')'); + } + // The address and the caution go last, so a long line is cut before them. + String ip = showIp ? " IP " + Addresses.text(attempt.address()) : ""; + String caution = decision.caution() == null ? "" : " Caution: " + text(decision.caution()) + "."; + String head = cut(line.toString(), MAX_LINE - ip.length() - caution.length() - 1) + ip; + // End the sentence before the caution, so it does not read as part of the note. + if (!caution.isEmpty() && !head.endsWith(".")) head += "."; + enqueue(head + caution); + } catch (RuntimeException ex) { + // A webhook problem must never reach a login. + } + } + + /** Queues a lookup problem or its recovery, the same messages that staff see in chat. */ + public void alert(boolean recovered, String message) { + try { + enqueue((recovered ? "Recovered: " : "Alert: ") + text(message)); + } catch (RuntimeException ex) { + // A webhook problem must never reach a login. + } + } + + /** Free text for a post: IP addresses become "IP hidden" unless show-ip is on, then Discord's markdown is escaped. */ + private String text(String free) { + return escape(showIp ? free : hideAddresses(free)); + } + + /** + * Fails closed. Every dotted quad goes, whatever surrounds it (a port, a colon). Every run of address characters + * goes when it, or the run without leading or trailing colons and dots, parses as an IP literal (no DNS). + */ + static String hideAddresses(String text) { + Matcher matcher = RUN.matcher(text); + StringBuffer result = new StringBuffer(); + while (matcher.find()) matcher.appendReplacement(result, Matcher.quoteReplacement(hideRun(matcher.group()))); + matcher.appendTail(result); + return DOTTED_QUAD.matcher(result).replaceAll(HIDDEN); + } + + private static String hideRun(String run) { + int slash = run.indexOf('/'); + String core = slash < 0 ? run : run.substring(0, slash); + int length = core.length(); + for (int start = 0; start <= length; start++) { + if (start > 0 && ":.".indexOf(core.charAt(start - 1)) < 0) break; + for (int end = length; end > start; end--) { + if (end < length && ":.".indexOf(core.charAt(end)) < 0) break; + if (Addresses.parse(core.substring(start, end)).isPresent()) { + return core.substring(0, start) + HIDDEN + core.substring(end); + } + } + } + return run; + } + + private void enqueue(String line) { + String cut = cut(line, MAX_LINE); + synchronized (lock) { + if (closed) return; + if (queue.size() >= MAX_QUEUED) overflow++; + else queue.add(cut); + } + } + + private static String cut(String line, int max) { + return line.length() <= max ? line : line.substring(0, safeCut(line, Math.max(0, max - 3))) + "..."; + } + + private static int safeCut(String text, int index) { + return index > 0 && Character.isHighSurrogate(text.charAt(index - 1)) ? index - 1 : index; + } + + /** Backslash-escapes Discord's markdown characters and replaces line breaks and other control characters. */ + static String escape(String text) { + StringBuilder result = new StringBuilder(text.length() + 8); + for (int i = 0; i < text.length(); i++) { + char c = text.charAt(i); + if (Character.isISOControl(c)) result.append(' '); + else { + if (SPECIAL.indexOf(c) >= 0) result.append('\\'); + result.append(c); + } + } + return result.toString(); + } + + private void flushQuietly() { + try { + flush(Duration.ofSeconds(10)); + } catch (RuntimeException ex) { + // The timer thread must survive anything. + } + } + + /** Posts everything queued as one message. Lines beyond the first 10 are only counted. */ + void flush() { + flush(Duration.ofSeconds(10)); + } + + private void flush(Duration timeout) { + synchronized (sending) { + List lines = new ArrayList<>(); + int more; + synchronized (lock) { + more = overflow; + overflow = 0; + while (!queue.isEmpty()) { + String line = queue.poll(); + if (lines.size() < SHOWN_LINES) lines.add(line); + else more++; + } + } + if (lines.isEmpty()) return; + if (more > 0) lines.add("And " + more + " more."); + post(String.join("\n", lines), timeout); + } + } + + private void post(String content, Duration timeout) { + JsonObject mentions = new JsonObject(); + mentions.add("parse", new JsonArray()); + JsonObject body = new JsonObject(); + body.addProperty("username", "OriginGate"); + body.addProperty("content", content); + body.add("allowed_mentions", mentions); + // 4 = suppress embeds, so a URL in a note or organisation gets no link preview. + body.addProperty("flags", 4); + String problem = null; + try { + HttpRequest request = HttpRequest.newBuilder(url).timeout(timeout) + .header("Content-Type", "application/json").header("User-Agent", userAgent) + .POST(GSON.toJson(body).getBytes(StandardCharsets.UTF_8)).build(); + int status = http.send(request, HttpResponse.BodyHandlers.discarding()).statusCode(); + if (status < 200 || status > 299) problem = "Discord answered with status " + status; + } catch (InterruptedException ex) { + Thread.currentThread().interrupt(); + problem = "the post was interrupted"; + } catch (Exception ex) { + // Only the exception type: some messages carry the host or the full address. + problem = ex.getClass().getSimpleName(); + } + if (problem != null) { + if (!failing) log.warn("Could not post to the Discord webhook: " + problem + ". Later failures are not logged until a post works.", null); + failing = true; + } else if (failing) { + failing = false; + log.info("The Discord webhook works again."); + } + } + + /** Posts what is queued once, then stops the thread. Call before closing the HTTP transport. */ + @Override public void close() { + synchronized (lock) { + if (closed) return; + closed = true; + } + timer.shutdown(); + try { + timer.awaitTermination(15, TimeUnit.SECONDS); + } catch (InterruptedException ex) { + Thread.currentThread().interrupt(); + } + try { + flush(Duration.ofSeconds(5)); + } catch (RuntimeException ex) { + // Closing must finish. + } + } +} diff --git a/core/src/main/java/io/github/origingate/core/rules/Gate.java b/core/src/main/java/io/github/origingate/core/rules/Gate.java index 150de7a..afda93c 100644 --- a/core/src/main/java/io/github/origingate/core/rules/Gate.java +++ b/core/src/main/java/io/github/origingate/core/rules/Gate.java @@ -5,6 +5,8 @@ import io.github.origingate.core.config.OriginGateConfig; import io.github.origingate.core.config.OriginGateConfig.CountryMode; import io.github.origingate.core.config.OriginGateConfig.FailureMode; +import io.github.origingate.core.lists.AccessLists; +import io.github.origingate.core.lists.ListEntry; import io.github.origingate.core.lookup.IpInfo; import io.github.origingate.core.lookup.LookupService; import io.github.origingate.core.net.AddressRange; @@ -24,8 +26,9 @@ import java.util.concurrent.TimeoutException; /** - * Decides whether a connection may join. Order: global bypass, deny-addresses, private-address skip, - * lookup, then the deny-networks, vpn, proxy, hosting, and country rules. The first rule that matches decides. + * Decides whether a connection may join. Order: global bypass, allow list, deny list, deny-addresses, private-address skip, + * accounts-per-ip, lookup, then the deny-networks, allow-networks, vpn, proxy, hosting, and country rules. The first rule that matches + * decides. A network on allow-networks skips only the vpn, proxy, and hosting rules. */ public final class Gate { /** Added to name and permission bypasses where names are not checked, for the log line and staff alert. */ @@ -36,6 +39,8 @@ public final class Gate { private final Log log; private final Set permissionNames; private final String bypassCaution; + private final AccessLists lists; + private final OnlineCount online; public Gate(OriginGateConfig config, LookupService lookups, Log log) { this(config, lookups, log, false); @@ -43,6 +48,17 @@ public Gate(OriginGateConfig config, LookupService lookups, Log log) { /** {@code namesUnverified}: offline mode or BungeeCord IP forwarding, where anyone can join with any name. */ public Gate(OriginGateConfig config, LookupService lookups, Log log, boolean namesUnverified) { + this(config, lookups, log, namesUnverified, AccessLists.empty()); + } + + public Gate(OriginGateConfig config, LookupService lookups, Log log, boolean namesUnverified, AccessLists lists) { + this(config, lookups, log, namesUnverified, lists, OnlineCount.NONE); + } + + public Gate(OriginGateConfig config, LookupService lookups, Log log, boolean namesUnverified, AccessLists lists, + OnlineCount online) { + this.lists = lists; + this.online = online; this.config = config; this.lookups = lookups; this.log = log; @@ -112,6 +128,17 @@ public Optional beforeLookup(LoginAttempt attempt) { return Optional.of(allow("player has a global bypass permission", null, bypassCaution)); } + Optional listed = lists.match(attempt.username(), attempt.uuid(), address); + if (listed.isPresent()) { + ListEntry entry = listed.get(); + String suffix = entry.note() == null || entry.note().isEmpty() ? "" : ": " + entry.note(); + String kind = entry.kind() == ListEntry.Kind.ALLOW ? "allow" : "deny"; + String note = (entry.isAddress() ? "address is on the " + kind + " list (" + entry.target() + ")" + : "player is on the " + kind + " list") + suffix; + if (entry.kind() == ListEntry.Kind.ALLOW) return Optional.of(allow(note, null, entry.isAddress() ? null : bypassCaution)); + return Optional.of(matched(attempt, Rule.DENY_LIST, Collections.emptyList(), null, note)); + } + OriginGateConfig.AddressRule deny = config.rules().denyAddresses(); if (deny.enabled() && contains(deny.list(), address)) { return Optional.of(matched(attempt, Rule.DENY_ADDRESSES, deny.bypassPermissions(), null, "address is on the deny list")); @@ -119,6 +146,15 @@ public Optional beforeLookup(LoginAttempt attempt) { if (config.lookup().skipPrivateAddresses() && Addresses.isPrivate(address)) { return Optional.of(allow("private address, lookup skipped", null)); } + OriginGateConfig.AccountsRule accounts = config.rules().accountsPerIp(); + if (accounts.enabled()) { + // ponytail: logins at the same moment can each see a count below the limit; count in-flight logins if bots exploit it. + int count = online.sameAddress(address, attempt.uuid()); + if (count >= accounts.max()) { + return Optional.of(matched(attempt, Rule.ACCOUNTS_PER_IP, Collections.emptyList(), null, + count + (count == 1 ? " player is" : " players are") + " already online from this address")); + } + } return Optional.empty(); } @@ -142,7 +178,7 @@ public static final class Match { /** * The first of the deny-networks, vpn, proxy, hosting, and country rules that matches {@code info}, or empty. * A match kicks unless the player has a bypass permission, so the lookup cache shares only such answers - * across an IPv6 /64. + * across an IPv6 /64. The vpn, proxy, and hosting rules are skipped for a network on allow-networks. */ public static Optional match(OriginGateConfig.Rules rules, IpInfo info) { OriginGateConfig.NetworkRule networks = rules.denyNetworks(); @@ -153,12 +189,9 @@ public static Optional match(OriginGateConfig.Rules rules, IpInfo info) { "network is on the deny list (" + listed.get() + ")")); } } - if (rules.vpn().enabled() && info.vpn()) return Optional.of(new Match(Rule.VPN, rules.vpn().bypassPermissions(), "flagged as VPN")); - if (rules.proxy().enabled() && info.proxy() && !Countries.matchesAny(info, rules.proxy().allowedCountries())) { - return Optional.of(new Match(Rule.PROXY, rules.proxy().bypassPermissions(), "flagged as proxy")); - } - if (rules.hosting().enabled() && info.hosting()) { - return Optional.of(new Match(Rule.HOSTING, rules.hosting().bypassPermissions(), "hosting or datacenter network")); + if (!allowedNetwork(rules, info).isPresent()) { + Optional flagged = flagged(rules, info); + if (flagged.isPresent()) return flagged; } OriginGateConfig.CountryRule country = rules.country(); if (country.enabled()) { @@ -171,14 +204,39 @@ public static Optional match(OriginGateConfig.Rules rules, IpInfo info) { return Optional.empty(); } - /** Applies the deny-networks, vpn, proxy, hosting, and country rules to a finished lookup. */ + /** The first of the vpn, proxy, and hosting rules that matches {@code info}, ignoring allow-networks. */ + private static Optional flagged(OriginGateConfig.Rules rules, IpInfo info) { + if (rules.vpn().enabled() && info.vpn()) return Optional.of(new Match(Rule.VPN, rules.vpn().bypassPermissions(), "flagged as VPN")); + if (rules.proxy().enabled() && info.proxy() && !Countries.matchesAny(info, rules.proxy().allowedCountries())) { + return Optional.of(new Match(Rule.PROXY, rules.proxy().bypassPermissions(), "flagged as proxy")); + } + if (rules.hosting().enabled() && info.hosting()) { + return Optional.of(new Match(Rule.HOSTING, rules.hosting().bypassPermissions(), "hosting or datacenter network")); + } + return Optional.empty(); + } + + private static Optional allowedNetwork(OriginGateConfig.Rules rules, IpInfo info) { + OriginGateConfig.NetworkRule allow = rules.allowNetworks(); + return allow.enabled() ? listedNetwork(info, allow) : Optional.empty(); + } + + /** Applies the deny-networks, allow-networks, vpn, proxy, hosting, and country rules to a finished lookup. */ public Decision afterLookup(LoginAttempt attempt, LookupService.Result result) { IpInfo info = result.info(); Optional match = match(config.rules(), info); log.debug("Rules for " + info.ip() + " (vpn " + yesNo(info.vpn()) + ", proxy " + yesNo(info.proxy()) + ", hosting " + yesNo(info.hosting()) + ", country " + Text.dash(info.countryCode()) + ", " + Text.dash(info.asn()) + "): " + (match.isPresent() ? match.get().rule().id() + " matched" : "none matched")); - if (!match.isPresent()) return allow("no rule matched", result); + if (!match.isPresent()) { + // Only an exemption that stopped a vpn, proxy, or hosting kick is worth a rule in the log. + Optional allowed = allowedNetwork(config.rules(), info); + if (allowed.isPresent() && flagged(config.rules(), info).isPresent()) { + return new Decision(Outcome.ALLOW, Rule.ALLOW_NETWORKS, "network is on the allow list (" + allowed.get() + ")", + result, config.dryRun()); + } + return allow("no rule matched", result); + } Match matched = match.get(); return matched(attempt, matched.rule(), matched.bypassPermissions(), result, matched.note()); } diff --git a/core/src/main/java/io/github/origingate/core/rules/OnlineCount.java b/core/src/main/java/io/github/origingate/core/rules/OnlineCount.java new file mode 100644 index 0000000..25020a0 --- /dev/null +++ b/core/src/main/java/io/github/origingate/core/rules/OnlineCount.java @@ -0,0 +1,13 @@ +package io.github.origingate.core.rules; + +import java.net.InetAddress; +import java.util.UUID; + +/** Counts the players online from one address. Read on login threads, so it must not block. */ +@FunctionalInterface +public interface OnlineCount { + /** Players online from exactly {@code address}, not counting {@code except} (may be null). */ + int sameAddress(InetAddress address, UUID except); + + OnlineCount NONE = (address, except) -> 0; +} diff --git a/core/src/main/java/io/github/origingate/core/rules/Rule.java b/core/src/main/java/io/github/origingate/core/rules/Rule.java index fabcc5a..48acfa1 100644 --- a/core/src/main/java/io/github/origingate/core/rules/Rule.java +++ b/core/src/main/java/io/github/origingate/core/rules/Rule.java @@ -2,8 +2,11 @@ /** Rules in the order they are checked, plus the lookup-failure outcome. */ public enum Rule { + DENY_LIST("deny-list"), DENY_ADDRESSES("deny-addresses"), + ACCOUNTS_PER_IP("accounts-per-ip"), DENY_NETWORKS("deny-networks"), + ALLOW_NETWORKS("allow-networks"), VPN("vpn"), PROXY("proxy"), HOSTING("hosting"), @@ -18,5 +21,8 @@ public enum Rule { public String id() { return id; } /** Rules added after 1.0.0, whose config section and kick message may be missing from older files. */ - public boolean addedLater() { return this == DENY_NETWORKS || this == HOSTING; } + public boolean addedLater() { return this == DENY_LIST || this == ACCOUNTS_PER_IP || this == DENY_NETWORKS || this == HOSTING; } + + /** False for a rule that only lets players in, so it has no kick message. */ + public boolean kicks() { return this != ALLOW_NETWORKS; } } diff --git a/core/src/main/java/io/github/origingate/core/storage/SqlIpStorage.java b/core/src/main/java/io/github/origingate/core/storage/SqlIpStorage.java index 4d69864..576d592 100644 --- a/core/src/main/java/io/github/origingate/core/storage/SqlIpStorage.java +++ b/core/src/main/java/io/github/origingate/core/storage/SqlIpStorage.java @@ -1,6 +1,8 @@ package io.github.origingate.core.storage; import io.github.origingate.core.config.OriginGateConfig; +import io.github.origingate.core.lists.ListEntry; +import io.github.origingate.core.lists.ListTable; import io.github.origingate.core.lookup.IpInfo; import java.io.IOException; @@ -13,6 +15,8 @@ import java.sql.Statement; import java.sql.Types; import java.time.Instant; +import java.util.ArrayList; +import java.util.List; import java.util.Objects; import java.util.Optional; import java.util.Properties; @@ -23,8 +27,9 @@ * One connection per operation; callers bound concurrency with their worker pool. The table is created * on the first connection that works, so a database that is down at startup is set up once it answers. */ -public final class SqlIpStorage implements IpStorage { +public final class SqlIpStorage implements IpStorage, ListTable { public static final String TABLE = "origingate_ip_cache"; + public static final String LIST_TABLE = "origingate_list"; private static final String COLUMNS = "ip,provider,organisation,operator_name,city,region,country,country_code,asn,vpn,proxy,type,checked_at"; private static final String CREATE_COLUMNS = "ip VARCHAR(45) NOT NULL PRIMARY KEY, provider VARCHAR(255), " @@ -32,6 +37,10 @@ public final class SqlIpStorage implements IpStorage { + "country VARCHAR(255), country_code CHAR(2), asn VARCHAR(32), vpn BOOLEAN NOT NULL, " + "proxy BOOLEAN NOT NULL, type VARCHAR(64), checked_at BIGINT NOT NULL"; + private static final String LIST_COLUMNS = "target,kind,expires_at,note,added_by,added_at"; + private static final String LIST_CREATE_COLUMNS = "target VARCHAR(64) NOT NULL PRIMARY KEY, kind VARCHAR(5) NOT NULL, " + + "expires_at BIGINT NULL, note VARCHAR(255), added_by VARCHAR(64) NOT NULL, added_at BIGINT NOT NULL"; + @FunctionalInterface public interface Connections { Connection open() throws SQLException; } private final Connections connections; @@ -125,9 +134,12 @@ private void setup(Connection connection) throws SQLException { if (mysql) { statement.execute("CREATE TABLE IF NOT EXISTS " + TABLE + " (" + CREATE_COLUMNS + ", INDEX " + TABLE + "_checked_at (checked_at)) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4"); + statement.execute("CREATE TABLE IF NOT EXISTS " + LIST_TABLE + " (" + LIST_CREATE_COLUMNS + + ") ENGINE=InnoDB DEFAULT CHARSET=utf8mb4"); } else { statement.execute("CREATE TABLE IF NOT EXISTS " + TABLE + " (" + CREATE_COLUMNS + ")"); statement.execute("CREATE INDEX IF NOT EXISTS " + TABLE + "_checked_at ON " + TABLE + " (checked_at)"); + statement.execute("CREATE TABLE IF NOT EXISTS " + LIST_TABLE + " (" + LIST_CREATE_COLUMNS + ")"); } } ready = true; @@ -211,6 +223,53 @@ private Connection connection() throws SQLException { } } + @Override public List all() throws SQLException { + List entries = new ArrayList<>(); + try (Connection connection = connection(); Statement statement = connection.createStatement(); + ResultSet row = statement.executeQuery("SELECT " + LIST_COLUMNS + " FROM " + LIST_TABLE + " ORDER BY added_at, target")) { + while (row.next()) { + ListEntry.Kind kind = ListEntry.Kind.ofId(row.getString("kind")); + if (kind == null) continue; // Not written by OriginGate. + long expires = row.getLong("expires_at"); + Instant expiresAt = row.wasNull() ? null : Instant.ofEpochSecond(expires); + entries.add(new ListEntry(kind, row.getString("target"), expiresAt, row.getString("note"), + row.getString("added_by"), Instant.ofEpochSecond(row.getLong("added_at")))); + } + } + return entries; + } + + @Override public void put(ListEntry entry) throws SQLException { + try (Connection connection = connection(); PreparedStatement statement = connection.prepareStatement( + "REPLACE INTO " + LIST_TABLE + " (" + LIST_COLUMNS + ") VALUES (?,?,?,?,?,?)")) { + statement.setString(1, entry.target()); + statement.setString(2, entry.kind().id()); + if (entry.expiresAt() == null) statement.setNull(3, Types.BIGINT); + else statement.setLong(3, entry.expiresAt().getEpochSecond()); + text(statement, 4, entry.note(), 255); + text(statement, 5, entry.addedBy(), 64); + statement.setLong(6, entry.addedAt().getEpochSecond()); + statement.executeUpdate(); + } + } + + @Override public int remove(ListEntry.Kind kind, String target) throws SQLException { + try (Connection connection = connection(); PreparedStatement statement = connection.prepareStatement( + "DELETE FROM " + LIST_TABLE + " WHERE target=? AND kind=?")) { + statement.setString(1, target); + statement.setString(2, kind.id()); + return statement.executeUpdate(); + } + } + + @Override public int deleteExpired(Instant now) throws SQLException { + try (Connection connection = connection(); PreparedStatement statement = connection.prepareStatement( + "DELETE FROM " + LIST_TABLE + " WHERE expires_at IS NOT NULL AND expires_at<=?")) { + statement.setLong(1, now.getEpochSecond()); + return statement.executeUpdate(); + } + } + private static void text(PreparedStatement statement, int index, String value, int max) throws SQLException { if (value == null) statement.setNull(index, Types.VARCHAR); else statement.setString(index, value.length() > max ? value.substring(0, max) : value); diff --git a/core/src/main/resources/config.yml b/core/src/main/resources/config.yml index 006d530..1188e6d 100644 --- a/core/src/main/resources/config.yml +++ b/core/src/main/resources/config.yml @@ -112,6 +112,13 @@ rules: # IP addresses or CIDR ranges, for example ["203.0.113.0/24"]. list: [] bypass-permissions: [] + # Kicks a player when this many players are already online from the same IP address, for example bot accounts from + # one machine. Mobile carriers, schools, and families often share one address, so keep it off or set it generously. + # Put players who share an address on the allow list. Counts players on this server or proxy only. + accounts-per-ip: + enabled: false + # Most players online at once from one address (1-100). + max: 3 # Kicks networks you list by AS number or name, for example a hosting company that VPN services rent from. # Works with every provider except maxmind, which has no network data. deny-networks: @@ -122,6 +129,13 @@ rules: # For example ["Example Hosting"]. At least 3 characters each. organisations: [] bypass-permissions: ["origingate.bypass.deny-networks"] + # Lets in networks you list by AS number when the vpn, proxy, or hosting rule would kick them, for example a school + # or mobile carrier that a provider wrongly flags. deny-networks and country still apply. "origingate check " + # shows an address's AS number. Works with every provider except maxmind, which has no network data. + allow-networks: + enabled: false + # AS numbers, for example [AS64496]. + asns: [] # Kicks IPs that the vpn-from provider flags as a VPN. vpn: enabled: true @@ -152,6 +166,14 @@ alerts: # provider stops answering or the lookup budget is used up, and one when that is over. permissions: ["origingate.alerts"] +# Posts kicks, bypasses, and lookup alerts (what staff with an alert permission see in chat) to a Discord channel. +# Posts within 5 seconds are combined into one, so a flood of kicks becomes a short summary. +discord: + # The channel's webhook URL, from the channel's settings under Integrations, Webhooks. Leave empty to turn off. + webhook-url: "" + # Show players' IP addresses in posts. Off by default, so addresses stay on this server. + show-ip: false + # Write every login where a rule matched or the lookup failed to daily files in the logs folder. log-file: true # Log files older than this many days (0-3650) are deleted. 0 keeps them forever. diff --git a/core/src/main/resources/messages.yml b/core/src/main/resources/messages.yml index 6593061..f6414d9 100644 --- a/core/src/main/resources/messages.yml +++ b/core/src/main/resources/messages.yml @@ -13,6 +13,20 @@ kick: Contact the server staff if you think this is a mistake. + Username: + Time: + deny-list: |- + You are not allowed on this server. + + Contact the server staff if you think this is a mistake. + + Username: + Time: + accounts-per-ip: |- + Too many players are already connected from your address. + + Contact the server staff if you think this is a mistake. + Username: Time: vpn: |- diff --git a/core/src/test/java/io/github/origingate/core/ListCommandsTest.java b/core/src/test/java/io/github/origingate/core/ListCommandsTest.java new file mode 100644 index 0000000..82c0692 --- /dev/null +++ b/core/src/test/java/io/github/origingate/core/ListCommandsTest.java @@ -0,0 +1,342 @@ +package io.github.origingate.core; + +import io.github.origingate.core.lists.ListEntry; +import io.github.origingate.core.rules.Decision; +import io.github.origingate.core.rules.LoginAttempt; +import io.github.origingate.core.rules.Rule; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +import java.nio.file.Files; +import java.nio.file.Path; +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.Statement; +import java.time.Duration; +import java.time.Instant; +import java.time.ZoneId; +import java.time.format.DateTimeFormatter; +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; +import java.util.Set; +import java.util.concurrent.BlockingQueue; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.concurrent.LinkedBlockingQueue; +import java.util.concurrent.TimeUnit; +import java.util.function.Predicate; + +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; + +/** The allow and deny commands against a real runtime on SQLite. */ +class ListCommandsTest { + private static final String ALLOW_USAGE = + "Usage: /origingate allow add [duration] [note], remove , list [page]"; + private static final DateTimeFormatter TIME = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm z"); + + @TempDir Path directory; + private OriginGateRuntime runtime; + private final List kicks = new CopyOnWriteArrayList<>(); + private volatile boolean kickFails; + + @AfterEach void stop() { + if (runtime != null) runtime.close(); + } + + private record Kick(Predicate who, Decision decision) { } + + private void load(Object... changes) throws Exception { + TestSupport.writeConfig(directory, changes); + runtime = OriginGateRuntime.load(directory, Log.NONE); + } + + private Commands commands() { + return new Commands(new Commands.Platform() { + @Override public OriginGateRuntime runtime() { return runtime; } + @Override public Optional onlinePlayer(String name) { return Optional.empty(); } + @Override public List onlinePlayerNames() { return List.of("Alex"); } + @Override public String reload() { return "reloaded"; } + @Override public void kick(Predicate who, Decision decision) { + kicks.add(new Kick(who, decision)); + if (kickFails) throw new IllegalStateException("kick failed (test)"); + } + }); + } + + private static final class Replies implements Commands.Sender { + final BlockingQueue lines = new LinkedBlockingQueue<>(); + final Set permissions; + + Replies(String... permissions) { this.permissions = Set.of(permissions); } + + @Override public boolean hasPermission(String permission) { return permissions.contains(permission); } + + @Override public void reply(String line) { lines.add(line); } + + String next() throws InterruptedException { + String line = lines.poll(10, TimeUnit.SECONDS); + assertNotNull(line, "no reply"); + return line; + } + + String waitFor(String text) throws InterruptedException { + List seen = new ArrayList<>(); + while (true) { + String line = next(); + seen.add(line); + if (line.contains(text)) return line; + assertTrue(seen.size() < 50, "no reply containing " + text + "; saw " + seen); + } + } + } + + private Replies run(Replies sender, String... args) { + commands().execute(args, sender); + return sender; + } + + private static Replies both() { return new Replies(Commands.ALLOW, Commands.DENY); } + + private static String time(Instant instant) { return TIME.format(instant.atZone(ZoneId.systemDefault())); } + + @Test void addWithDurationAndNote() throws Exception { + load(); + Replies sender = run(both(), "allow", "add", "Kai", "7d", "trusted", "tester"); + String reply = sender.waitFor("Added kai"); + ListEntry stored = runtime.lists().active(ListEntry.Kind.ALLOW).join().get(0); + assertEquals("Added kai to the allow list, expires " + time(stored.expiresAt()) + ", note: trusted tester.", reply); + assertTrue(Duration.between(Instant.now(), stored.expiresAt()).toDays() >= 6); + assertEquals("console", stored.addedBy()); + + run(sender, "allow", "list"); + sender.waitFor("Allow list, page 1 of 1 (1 entries):"); + String line = sender.next(); + assertTrue(line.contains("kai") && line.contains("by console") && line.contains("trusted tester"), line); + } + + @Test void noteWithoutDurationNeverExpires() throws Exception { + load(); + Replies sender = run(both(), "deny", "add", "203.0.113.7", "spam", "bot"); + assertEquals("Added 203.0.113.7 to the deny list, never expires, note: spam bot.", sender.waitFor("Added")); + assertNull(runtime.lists().active(ListEntry.Kind.DENY).join().get(0).expiresAt()); + } + + @Test void denyAddKicksMatchingOnlinePlayers() throws Exception { + load(); + Replies sender = run(both(), "deny", "add", "203.0.113.7", "spam"); + sender.waitFor("Added"); + assertEquals(1, kicks.size()); + Kick kick = kicks.get(0); + assertTrue(kick.who().test(TestSupport.player("Alex", "203.0.113.7"))); + assertTrue(!kick.who().test(TestSupport.player("Alex", "192.0.2.10"))); + assertEquals(Decision.Outcome.DENY, kick.decision().outcome()); + assertEquals(Rule.DENY_LIST, kick.decision().rule()); + + run(sender, "allow", "add", "203.0.113.8"); + sender.waitFor("Added"); + assertEquals(1, kicks.size()); + } + + @Test void denyAddSparesPlayersTheLoginWouldLetIn() throws Exception { + load("bypass.players", List.of("lee")); + runtime.lists().add(new ListEntry(ListEntry.Kind.ALLOW, "kai", null, null, "console", Instant.now())).join(); + Replies sender = run(both(), "deny", "add", "203.0.113.0/24"); + sender.waitFor("Added"); + Predicate who = kicks.get(0).who(); + assertTrue(!who.test(TestSupport.player("Kai", "203.0.113.7"))); + assertTrue(!who.test(TestSupport.player("Lee", "203.0.113.9"))); + assertTrue(who.test(TestSupport.player("Alex", "203.0.113.8"))); + } + + @Test void denyAddInDryRunKicksNobody() throws Exception { + load("dry-run", true); + Replies sender = run(both(), "deny", "add", "Kai"); + assertTrue(sender.waitFor("Added").endsWith("Dry run is on: nobody online is disconnected.")); + assertTrue(kicks.isEmpty()); + } + + @Test void removeOnlyFromNamedList() throws Exception { + load(); + Replies sender = run(both(), "allow", "add", "kai"); + sender.waitFor("Added"); + run(sender, "deny", "remove", "kai"); + sender.waitFor("kai is not on the deny list."); + run(sender, "allow", "remove", "Kai"); + sender.waitFor("Removed kai from the allow list."); + assertEquals(0, runtime.lists().count(ListEntry.Kind.ALLOW)); + } + + @Test void replacingAnEntryOnTheOtherListNeedsThatListsPermission() throws Exception { + load(); + Replies admin = run(both(), "deny", "add", "Kai"); + admin.waitFor("Added"); + kicks.clear(); + Replies helper = run(new Replies(Commands.ALLOW), "allow", "add", "Kai"); + assertEquals("kai is on the deny list. Changing that list needs origingate.command.deny.", helper.next()); + assertEquals(1, runtime.lists().count(ListEntry.Kind.DENY)); + assertEquals(0, runtime.lists().count(ListEntry.Kind.ALLOW)); + + run(admin, "allow", "add", "Kai"); + admin.waitFor("Added kai to the allow list"); + assertEquals(0, runtime.lists().count(ListEntry.Kind.DENY)); + Replies moderator = run(new Replies(Commands.DENY), "deny", "add", "kai"); + assertEquals("kai is on the allow list. Changing that list needs origingate.command.allow.", moderator.next()); + assertEquals(1, runtime.lists().count(ListEntry.Kind.ALLOW)); + assertTrue(kicks.isEmpty()); + + runtime.lists().add(new ListEntry(ListEntry.Kind.DENY, "sam", Instant.now().minusSeconds(60), null, "console", Instant.now().minusSeconds(120))).join(); + run(helper, "allow", "add", "Sam"); + helper.waitFor("Added sam to the allow list"); + } + + @Test void rejectsBadInput() throws Exception { + load(); + Replies sender = both(); + run(sender, "allow", "add", "two words?"); + assertEquals("two words? is not a player name, UUID, IP address, or CIDR range", sender.next()); + run(sender, "allow", "add", "Kai", "0d"); + assertEquals("Durations go from 1s to 3650d, or never.", sender.next()); + run(sender, "allow", "add", "Kai", "99999d"); + assertEquals("Durations go from 1s to 3650d, or never.", sender.next()); + run(sender, "allow", "add", "Kai", "99999999999999999999d"); + assertEquals("Durations go from 1s to 3650d, or never.", sender.next()); + run(sender, "allow", "add", "Kai", "30min", "griefing"); + assertEquals("30min is not a duration. Use s, m, h, d, or w, like 30m or 7d. For a note that starts with a number, put never first.", sender.next()); + run(sender, "allow", "add", "Kai", "1y"); + assertEquals("1y is not a duration. Use s, m, h, d, or w, like 30m or 7d. For a note that starts with a number, put never first.", sender.next()); + run(sender, "allow", "add", "Kai", "never", "x".repeat(256)); + assertEquals("Notes can be up to 255 characters.", sender.next()); + run(sender, "allow", "add"); + assertEquals(ALLOW_USAGE, sender.next()); + run(sender, "allow"); + assertEquals(ALLOW_USAGE, sender.next()); + run(sender, "allow", "remove"); + assertEquals(ALLOW_USAGE, sender.next()); + run(sender, "allow", "list", "x"); + assertEquals(ALLOW_USAGE, sender.next()); + run(sender, "deny", "add"); + assertEquals(ALLOW_USAGE.replace("allow", "deny"), sender.next()); + assertEquals(0, runtime.lists().count(ListEntry.Kind.ALLOW)); + } + + @Test void acceptsLongestDurationAndNever() throws Exception { + load(); + Replies sender = run(both(), "allow", "add", "Kai", "3650d"); + sender.waitFor("Added"); + run(sender, "allow", "add", "Alex", "never", "forever"); + assertEquals("Added alex to the allow list, never expires, note: forever.", sender.waitFor("Added")); + } + + @Test void permissionsAreSeparate() throws Exception { + load(); + Replies sender = run(new Replies(Commands.ALLOW), "deny", "add", "kai"); + assertEquals("You do not have permission to use this command.", sender.next()); + assertTrue(Commands.PERMISSIONS.contains(Commands.ALLOW) && Commands.PERMISSIONS.contains(Commands.DENY)); + assertEquals(0, runtime.lists().count(ListEntry.Kind.DENY)); + } + + @Test void pagesTenPerPage() throws Exception { + load(); + for (int i = 0; i < 12; i++) { + String target = String.format("player%02d", i); + runtime.lists().add(new ListEntry(ListEntry.Kind.ALLOW, target, null, null, "console", Instant.now().plusSeconds(i))).join(); + } + Replies sender = run(both(), "allow", "list", "2"); + sender.waitFor("Allow list, page 2 of 2 (12 entries):"); + assertTrue(sender.next().contains("player10")); + assertTrue(sender.next().contains("player11")); + assertNull(sender.lines.poll(200, TimeUnit.MILLISECONDS)); + run(sender, "allow", "list", "3"); + assertEquals("There is no page 3. The allow list has 2 pages.", sender.next()); + run(sender, "deny", "list"); + assertEquals("The deny list is empty.", sender.next()); + } + + @Test void storageErrorIsReported() throws Exception { + load(); + try (Connection connection = DriverManager.getConnection("jdbc:sqlite:" + directory.resolve("data/origingate.db")); + Statement statement = connection.createStatement()) { + statement.execute("DROP TABLE origingate_list"); + } + Replies sender = run(both(), "allow", "add", "kai"); + sender.waitFor("Could not change the allow list: "); + assertTrue(kicks.isEmpty()); + } + + @Test void suggestsSubcommandsAndTargets() throws Exception { + load(); + runtime.lists().add(new ListEntry(ListEntry.Kind.DENY, "kai", null, null, "console", Instant.now())).join(); + runtime.lists().add(new ListEntry(ListEntry.Kind.DENY, "203.0.113.7", null, null, "console", Instant.now())).join(); + Replies sender = both(); + assertTrue(commands().suggest(new String[] {"allow"}, sender).contains("allow")); + assertEquals(List.of("remove"), commands().suggest(new String[] {"allow", "r"}, sender)); + assertEquals(List.of("add", "remove", "list"), commands().suggest(new String[] {"deny", ""}, sender)); + List targets = commands().suggest(new String[] {"deny", "remove", ""}, sender); + assertEquals(Set.of("kai", "203.0.113.7"), Set.copyOf(targets)); + assertEquals(List.of("Alex"), commands().suggest(new String[] {"deny", "add", "a"}, sender)); + assertTrue(commands().suggest(new String[] {"deny", "remove", ""}, new Replies(Commands.ALLOW)).isEmpty()); + } + + @Test void memoryOnlyReplySaysSo() throws Exception { + // A folder where the SQLite file should be makes storage fall back to memory. + Files.createDirectories(directory.resolve("data/origingate.db")); + load(); + Replies sender = run(both(), "allow", "add", "kai"); + assertTrue(sender.waitFor("Added").endsWith(" Kept in memory only until a restart.")); + } + + private OriginGateRuntime reload() throws Exception { + OriginGateRuntime next = OriginGateRuntime.load(directory, Log.NONE, new io.github.origingate.core.lookup.LookupStats(), + Alerts.NONE, false, io.github.origingate.core.rules.OnlineCount.NONE, runtime.lists()); + runtime.close(); + runtime = next; + return next; + } + + @Test void memoryOnlyEntriesSurviveAReload() throws Exception { + Files.createDirectories(directory.resolve("data/origingate.db")); + load(); + run(both(), "deny", "add", "kai").waitFor("Added"); + reload(); + assertEquals(1, runtime.lists().count(ListEntry.Kind.DENY)); + } + + @Test void unreadableTableAtReloadKeepsTheEntries() throws Exception { + load(); + run(both(), "deny", "add", "kai").waitFor("Added"); + try (Connection connection = DriverManager.getConnection("jdbc:sqlite:" + directory.resolve("data/origingate.db")); + Statement statement = connection.createStatement()) { + statement.execute("ALTER TABLE origingate_list RENAME COLUMN note TO note_old"); + } + reload(); + assertEquals(1, runtime.lists().count(ListEntry.Kind.DENY)); + } + + @Test void persistentListsRunARefreshThreadThatStopsOnClose() throws Exception { + load(); + assertTrue(listThreads() >= 1); + runtime.close(); + for (int i = 0; i < 50 && listThreads() > 0; i++) Thread.sleep(100); + assertEquals(0, listThreads()); + } + + private static long listThreads() { + return Thread.getAllStackTraces().keySet().stream().filter(t -> t.getName().equals("OriginGate Lists") && t.isAlive()).count(); + } + + @Test void denyAddReplyComesEvenWhenTheKickThrows() throws Exception { + load(); + kickFails = true; + assertTrue(run(both(), "deny", "add", "203.0.113.7").waitFor("Added").startsWith("Added 203.0.113.7 to the deny list")); + } + + @Test void aThrowingKickCheckDoesNotDisconnect() throws Exception { + load(); + run(both(), "deny", "add", "203.0.113.7").waitFor("Added"); + assertTrue(!kicks.get(0).who().test(null)); + } +} diff --git a/core/src/test/java/io/github/origingate/core/RuntimeCommandsTest.java b/core/src/test/java/io/github/origingate/core/RuntimeCommandsTest.java index 178bebc..ced3279 100644 --- a/core/src/test/java/io/github/origingate/core/RuntimeCommandsTest.java +++ b/core/src/test/java/io/github/origingate/core/RuntimeCommandsTest.java @@ -1,6 +1,7 @@ package io.github.origingate.core; import com.sun.net.httpserver.HttpServer; +import io.github.origingate.core.lists.ListEntry; import io.github.origingate.core.lookup.IpInfo; import io.github.origingate.core.rules.LoginAttempt; import io.github.origingate.core.storage.SqlIpStorage; @@ -31,7 +32,9 @@ import java.util.concurrent.atomic.AtomicInteger; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertTrue; /** Loads a real runtime (SQLite, HTTP provider) against a local stub server and drives the commands. */ @@ -227,9 +230,67 @@ private void awaitStoredRows(int expected) throws Exception { Path logs = Files.createDirectories(directory.resolve("logs")); Files.writeString(logs.resolve(LocalDate.now().minusDays(400) + ".log"), "old\n"); - assertEquals(new OriginGateRuntime.Cleanup(0, 0), runtime.deleteExpired()); + assertEquals(new OriginGateRuntime.Cleanup(0, 0, 0), runtime.deleteExpired()); load(); - assertEquals(new OriginGateRuntime.Cleanup(1, 1), runtime.deleteExpired()); + assertEquals(new OriginGateRuntime.Cleanup(1, 1, 0), runtime.deleteExpired()); + } + + @Test void statusShowsListCounts() throws Exception { + load(); + runtime.lists().add(entry(ListEntry.Kind.ALLOW, "kai", null)).join(); + runtime.lists().add(entry(ListEntry.Kind.DENY, "198.51.100.0/24", null)).join(); + runtime.lists().add(entry(ListEntry.Kind.DENY, "alex", null)).join(); + Replies sender = new Replies(Commands.STATUS); + commands().execute(new String[] {"status"}, sender); + sender.waitFor("Lists: 1 allow and 2 deny entries"); + } + + @Test void cleanupDeletesExpiredEntries() throws Exception { + load("storage.keep-days", 0, "log-file-keep-days", 0); + runtime.lists().add(entry(ListEntry.Kind.DENY, "kai", Instant.now().minusSeconds(60))).join(); + runtime.lists().add(entry(ListEntry.Kind.DENY, "alex", Instant.now().plus(Duration.ofDays(1)))).join(); + assertEquals(new OriginGateRuntime.Cleanup(0, 0, 1), runtime.deleteExpired()); + assertEquals(new OriginGateRuntime.Cleanup(0, 0, 0), runtime.deleteExpired()); + } + + private static ListEntry entry(ListEntry.Kind kind, String target, Instant expiresAt) { + return new ListEntry(kind, target, expiresAt, null, "console", Instant.now()); + } + + @Test void statusShowsDiscordWebhook() throws Exception { + load(); + assertNull(runtime.webhook()); + assertTrue(runtime.status().contains("Discord webhook: off"), runtime.status().toString()); + load("discord.webhook-url", "https://discord.example/api/webhooks/1/secret-token"); + assertNotNull(runtime.webhook()); + assertTrue(runtime.status().contains("Discord webhook: on"), runtime.status().toString()); + assertFalse(String.join(" ", runtime.status()).contains("secret-token")); + } + + @Test void reportPostsKickEvenWithConsoleLogNone() throws Exception { + List bodies = new java.util.concurrent.CopyOnWriteArrayList<>(); + server.createContext("/hook", exchange -> { + bodies.add(new String(exchange.getRequestBody().readAllBytes(), java.nio.charset.StandardCharsets.UTF_8)); + exchange.sendResponseHeaders(204, -1); + exchange.close(); + }); + TestSupport.writeConfig(directory, "console-log", "none", "log-file", false); + RuntimeController controller = new RuntimeController(directory, Log.NONE); + controller.reload(); + OriginGateRuntime active = controller.runtime(); + io.github.origingate.core.net.HttpTransport http = io.github.origingate.core.net.HttpTransport.newHttpClient(); + try { + active.attachWebhook(new io.github.origingate.core.report.DiscordWebhook( + java.net.URI.create("http://127.0.0.1:" + server.getAddress().getPort() + "/hook"), false, http, Log.NONE, "OriginGate/test")); + controller.report(active, TestSupport.player("Kai", "203.0.113.7"), + new io.github.origingate.core.rules.Decision(io.github.origingate.core.rules.Decision.Outcome.DENY, + io.github.origingate.core.rules.Rule.VPN, "flagged as VPN", null, false)); + controller.stop(5000); + } finally { + http.close(); + } + assertEquals(1, bodies.size(), bodies.toString()); + assertTrue(bodies.get(0).contains("Kicked **Kai** by the vpn rule: flagged as VPN"), bodies.get(0)); } @Test void commandsExplainWhenNotRunning() throws Exception { diff --git a/core/src/test/java/io/github/origingate/core/TestSupport.java b/core/src/test/java/io/github/origingate/core/TestSupport.java index cbcb51e..df39931 100644 --- a/core/src/test/java/io/github/origingate/core/TestSupport.java +++ b/core/src/test/java/io/github/origingate/core/TestSupport.java @@ -135,8 +135,9 @@ public static final class RecordingAlerts extends Alerts.Once { /** Keeps warnings so tests can check them. */ public static final class RecordingLog implements Log { public final List warnings = new CopyOnWriteArrayList<>(); + public final List infos = new CopyOnWriteArrayList<>(); - @Override public void info(String message) { } + @Override public void info(String message) { infos.add(message); } @Override public void warn(String message, Throwable cause) { warnings.add(message); } diff --git a/core/src/test/java/io/github/origingate/core/config/ConfigLoaderTest.java b/core/src/test/java/io/github/origingate/core/config/ConfigLoaderTest.java index 24fc888..74724ea 100644 --- a/core/src/test/java/io/github/origingate/core/config/ConfigLoaderTest.java +++ b/core/src/test/java/io/github/origingate/core/config/ConfigLoaderTest.java @@ -109,6 +109,70 @@ private String failure(Object... changes) { assertTrue(failure("rules.hosting.typo", true).contains("Unknown setting: rules.hosting.typo")); } + @Test void allowNetworksNeedsNetworkData() throws Exception { + assertTrue(failure("rules.allow-networks.enabled", true, "lookup.country-from", List.of("maxmind"), + "lookup.vpn-from", List.of(), "rules.vpn.enabled", false, "rules.proxy.enabled", false) + .contains("rules.allow-networks")); + } + + @Test void allowNetworksRejectsOrganisations() throws Exception { + assertTrue(failure("rules.allow-networks.organisations", List.of("Example School")) + .contains("Unknown setting: rules.allow-networks.organisations")); + } + + @Test void oldConfigTurnsNewFeaturesOff() throws Exception { + TestSupport.copyResource("/upgrade/config-1.0.0.yml", directory.resolve("config.yml")); + TestSupport.copyResource("/upgrade/messages-1.0.0.yml", directory.resolve("messages.yml")); + OriginGateConfig legacy = ConfigLoader.load(directory); + assertFalse(legacy.rules().allowNetworks().enabled()); + assertFalse(legacy.rules().accountsPerIp().enabled()); + assertFalse(legacy.discord().enabled()); + assertEquals("", legacy.discord().webhookUrl()); + Messages messages = Messages.load(directory); + assertTrue(messages.kick(io.github.origingate.core.rules.Rule.DENY_LIST).startsWith("You are not allowed on this server.")); + assertTrue(messages.kick(io.github.origingate.core.rules.Rule.ACCOUNTS_PER_IP).startsWith("Too many players are already connected")); + } + + @Test void config111TurnsNewFeaturesOff() throws Exception { + TestSupport.copyResource("/upgrade/config-1.1.1.yml", directory.resolve("config.yml")); + TestSupport.copyResource("/upgrade/messages-1.1.1.yml", directory.resolve("messages.yml")); + OriginGateConfig legacy = ConfigLoader.load(directory); + assertFalse(legacy.rules().allowNetworks().enabled()); + assertFalse(legacy.rules().accountsPerIp().enabled()); + assertFalse(legacy.discord().enabled()); + Messages messages = Messages.load(directory); + assertTrue(messages.kick(io.github.origingate.core.rules.Rule.DENY_LIST).startsWith("You are not allowed on this server.")); + assertTrue(messages.kick(io.github.origingate.core.rules.Rule.ACCOUNTS_PER_IP).startsWith("Too many players are already connected")); + } + + @Test void discordUrlMustBeHttps() throws Exception { + OriginGateConfig off = TestSupport.config(directory); + assertFalse(off.discord().enabled()); + assertFalse(off.discord().showIp()); + String url = "https://discord.com/api/webhooks/123/secret-token"; + OriginGateConfig on = TestSupport.config(directory, "discord.webhook-url", url, "discord.show-ip", true); + assertTrue(on.discord().enabled()); + assertEquals(url, on.discord().webhookUrl()); + assertTrue(on.discord().showIp()); + assertFalse(on.discord().toString().contains("secret-token")); + assertFalse(on.toString().contains("secret-token")); + String message = failure("discord.webhook-url", "http://discord.com/api/webhooks/123/secret-token"); + assertTrue(message.contains("discord.webhook-url") && message.contains("https"), message); + assertFalse(message.contains("secret-token")); + assertTrue(failure("discord.webhook-url", "not a url").contains("discord.webhook-url")); + assertTrue(failure("discord.extra", true).contains("Unknown setting")); + } + + @Test void accountsPerIpChecksItsLimit() throws Exception { + OriginGateConfig config = TestSupport.config(directory); + assertFalse(config.rules().accountsPerIp().enabled()); + assertEquals(3, config.rules().accountsPerIp().max()); + assertEquals(1, TestSupport.config(directory, "rules.accounts-per-ip.max", 1).rules().accountsPerIp().max()); + assertEquals(100, TestSupport.config(directory, "rules.accounts-per-ip.max", 100).rules().accountsPerIp().max()); + assertEquals("rules.accounts-per-ip.max must be a whole number from 1 to 100", failure("rules.accounts-per-ip.max", 0)); + assertEquals("rules.accounts-per-ip.max must be a whole number from 1 to 100", failure("rules.accounts-per-ip.max", 101)); + } + @Test void olderConfigWithoutProviderSettingsUsesProxycheck() throws Exception { OriginGateConfig config = TestSupport.config(directory, "lookup.country-from", TestSupport.REMOVE, "lookup.vpn-from", TestSupport.REMOVE, "lookup.iphub", TestSupport.REMOVE, "lookup.ip-api", TestSupport.REMOVE, @@ -265,7 +329,7 @@ private static List shown(OriginGateConfig.ConsoleLog level, List"), "default kick screens do not show the IP"); String text = Files.readString(directory.resolve("messages.yml")); Files.writeString(directory.resolve("messages.yml"), text.replace(" country: |-", " countri: |-")); diff --git a/core/src/test/java/io/github/origingate/core/lists/AccessListsTest.java b/core/src/test/java/io/github/origingate/core/lists/AccessListsTest.java new file mode 100644 index 0000000..c8cd7bd --- /dev/null +++ b/core/src/test/java/io/github/origingate/core/lists/AccessListsTest.java @@ -0,0 +1,288 @@ +package io.github.origingate.core.lists; + +import io.github.origingate.core.TestSupport; +import io.github.origingate.core.net.Addresses; +import io.github.origingate.core.storage.SqlIpStorage; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +import java.net.InetAddress; +import java.nio.file.Path; +import java.sql.SQLException; +import java.time.Duration; +import java.time.Instant; +import java.util.List; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicInteger; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class AccessListsTest { + private static final UUID KAI = UUID.fromString("123e4567-e89b-12d3-a456-426614174000"); + private static final InetAddress HOME = Addresses.parse("198.51.100.20").orElseThrow(); + @TempDir Path directory; + + private static ListEntry entry(ListEntry.Kind kind, String target, Instant expiresAt, Instant addedAt) { + return new ListEntry(kind, target, expiresAt, null, "console", addedAt); + } + + private static ListEntry entry(ListEntry.Kind kind, String target) { + return entry(kind, target, null, TestSupport.NOW); + } + + private static AccessLists load(ListTable table, TestSupport.MutableClock clock) { + return AccessLists.load(table, true, clock, Runnable::run, new TestSupport.RecordingLog()); + } + + @Test void sharedTableAppearsOnSecondServer() throws Exception { + Path file = directory.resolve("shared.db"); + TestSupport.MutableClock clock = new TestSupport.MutableClock(TestSupport.NOW); + AccessLists first = load(SqlIpStorage.sqlite(file), clock); + AccessLists second = load(SqlIpStorage.sqlite(file), clock); + + first.add(entry(ListEntry.Kind.DENY, "kai")).get(); + assertTrue(second.match("Kai", KAI, HOME).isEmpty()); + + clock.advance(Duration.ofSeconds(31)); + // With a direct executor the re-read may finish inside this call or the next one. + second.match("Kai", KAI, HOME); + assertTrue(second.match("Kai", KAI, HOME).isPresent()); + } + + @Test void survivesReload() throws Exception { + SqlIpStorage storage = SqlIpStorage.sqlite(directory.resolve("lists.db")); + TestSupport.MutableClock clock = new TestSupport.MutableClock(TestSupport.NOW); + load(storage, clock).add(entry(ListEntry.Kind.ALLOW, "kai")).get(); + AccessLists again = load(storage, clock); + assertEquals(ListEntry.Kind.ALLOW, again.match("Kai", KAI, HOME).orElseThrow().kind()); + } + + @Test void expiresOnTime() throws Exception { + TestSupport.MutableClock clock = new TestSupport.MutableClock(TestSupport.NOW); + AccessLists lists = load(ListTable.memory(), clock); + lists.add(entry(ListEntry.Kind.DENY, "kai", TestSupport.NOW.plus(Duration.ofHours(1)), TestSupport.NOW)).get(); + clock.advance(Duration.ofMinutes(59)); + assertTrue(lists.match("Kai", KAI, HOME).isPresent()); + assertEquals(1, lists.count(ListEntry.Kind.DENY)); + clock.advance(Duration.ofMinutes(1)); + assertTrue(lists.match("Kai", KAI, HOME).isEmpty()); + assertEquals(0, lists.count(ListEntry.Kind.DENY)); + assertTrue(lists.active(ListEntry.Kind.DENY).get().isEmpty()); + } + + @Test void playerEntryBeatsAddressEntry() throws Exception { + AccessLists lists = AccessLists.empty(); + lists.add(entry(ListEntry.Kind.ALLOW, "198.51.100.0/24")).get(); + lists.add(entry(ListEntry.Kind.DENY, "kai")).get(); + assertEquals(ListEntry.Kind.DENY, lists.match("Kai", KAI, HOME).orElseThrow().kind()); + assertEquals(ListEntry.Kind.ALLOW, lists.match("Sam", UUID.randomUUID(), HOME).orElseThrow().kind()); + } + + @Test void allowWinsOverlappingRanges() throws Exception { + AccessLists lists = AccessLists.empty(); + lists.add(entry(ListEntry.Kind.DENY, "198.51.100.20")).get(); + lists.add(entry(ListEntry.Kind.ALLOW, "198.51.100.0/24")).get(); + assertEquals("198.51.100.0/24", lists.match("Sam", UUID.randomUUID(), HOME).orElseThrow().target()); + } + + @Test void oneTargetLivesOnOneList() throws Exception { + AccessLists lists = AccessLists.empty(); + lists.add(entry(ListEntry.Kind.ALLOW, "kai")).get(); + lists.add(entry(ListEntry.Kind.DENY, "kai")).get(); + assertEquals(0, lists.count(ListEntry.Kind.ALLOW)); + assertEquals(List.of("kai"), lists.targets(ListEntry.Kind.DENY)); + assertFalse(lists.remove(ListEntry.Kind.ALLOW, "kai").get()); + assertTrue(lists.remove(ListEntry.Kind.DENY, "kai").get()); + assertTrue(lists.match("Kai", KAI, HOME).isEmpty()); + } + + @Test void activeListsOldestFirst() throws Exception { + AccessLists lists = AccessLists.empty(); + lists.add(entry(ListEntry.Kind.DENY, "sam", null, TestSupport.NOW.plusSeconds(10))).get(); + lists.add(entry(ListEntry.Kind.DENY, "kai", null, TestSupport.NOW)).get(); + lists.add(entry(ListEntry.Kind.ALLOW, "lee", null, TestSupport.NOW)).get(); + List deny = lists.active(ListEntry.Kind.DENY).get(); + assertEquals("kai", deny.get(0).target()); + assertEquals("sam", deny.get(1).target()); + assertEquals(2, deny.size()); + } + + @Test void unreadableTableStartsEmptyAndRetries() throws Exception { + AtomicInteger reads = new AtomicInteger(); + ListEntry stored = entry(ListEntry.Kind.DENY, "kai"); + ListTable flaky = new ListTable() { + @Override public List all() throws SQLException { + if (reads.getAndIncrement() == 0) throw new SQLException("down (test)"); + return List.of(stored); + } + @Override public void put(ListEntry entry) { } + @Override public int remove(ListEntry.Kind kind, String target) { return 0; } + @Override public int deleteExpired(Instant now) { return 0; } + }; + TestSupport.MutableClock clock = new TestSupport.MutableClock(TestSupport.NOW); + TestSupport.RecordingLog log = new TestSupport.RecordingLog(); + AccessLists lists = AccessLists.load(flaky, true, clock, Runnable::run, log); + assertEquals(0, lists.count(ListEntry.Kind.DENY)); + assertEquals(1, log.warnings.size()); + lists.match("Kai", KAI, HOME); + assertEquals(1, reads.get()); + + clock.advance(Duration.ofSeconds(31)); + assertTrue(lists.match("Kai", KAI, HOME).isPresent()); + assertEquals(1, lists.count(ListEntry.Kind.DENY)); + assertEquals(1, log.warnings.size()); + } + + /** A table whose calls throw what the test says; {@code failAll}/{@code failPut} pick which. */ + private static final class BrokenTable implements ListTable { + final AtomicInteger reads = new AtomicInteger(); + final ListTable inner = ListTable.memory(); + volatile Error allError; + volatile Error putError; + + @Override public List all() throws SQLException { + reads.incrementAndGet(); + if (allError != null) throw allError; + return inner.all(); + } + @Override public void put(ListEntry entry) throws SQLException { + if (putError != null) throw putError; + inner.put(entry); + } + @Override public int remove(ListEntry.Kind kind, String target) throws SQLException { return inner.remove(kind, target); } + @Override public int deleteExpired(Instant now) throws SQLException { return inner.deleteExpired(now); } + } + + @Test void driverErrorOnLoadStartsEmptyAndRetries() throws Exception { + BrokenTable table = new BrokenTable(); + table.inner.put(entry(ListEntry.Kind.DENY, "kai")); + table.allError = new LinkageError("driver (test)"); + TestSupport.MutableClock clock = new TestSupport.MutableClock(TestSupport.NOW); + TestSupport.RecordingLog log = new TestSupport.RecordingLog(); + AccessLists lists = AccessLists.load(table, true, clock, Runnable::run, log); + assertEquals(0, lists.count(ListEntry.Kind.DENY)); + assertEquals(1, log.warnings.size()); + + table.allError = null; + clock.advance(Duration.ofSeconds(31)); + assertTrue(lists.match("Kai", KAI, HOME).isPresent()); + } + + @Test void failedRereadWaitsBeforeTryingAgain() { + BrokenTable table = new BrokenTable(); + TestSupport.MutableClock clock = new TestSupport.MutableClock(TestSupport.NOW); + AccessLists lists = AccessLists.load(table, true, clock, Runnable::run, new TestSupport.RecordingLog()); + table.allError = new java.util.ServiceConfigurationError("driver (test)"); + clock.advance(Duration.ofSeconds(31)); + int before = table.reads.get(); + for (int i = 0; i < 5; i++) lists.match("Kai", KAI, HOME); + assertEquals(before + 1, table.reads.get()); + clock.advance(Duration.ofSeconds(31)); + lists.match("Kai", KAI, HOME); + assertEquals(before + 2, table.reads.get()); + } + + @Test void driverErrorOnWriteCompletesExceptionally() { + BrokenTable table = new BrokenTable(); + table.putError = new LinkageError("driver (test)"); + AccessLists lists = AccessLists.load(table, true, new TestSupport.MutableClock(TestSupport.NOW), Runnable::run, new TestSupport.RecordingLog()); + java.util.concurrent.CompletableFuture added =lists.add(entry(ListEntry.Kind.DENY, "kai")); + assertTrue(added.isCompletedExceptionally()); + } + + @Test void savedEntryCompletesEvenWhenTheRereadFails() throws Exception { + BrokenTable table = new BrokenTable(); + TestSupport.RecordingLog log = new TestSupport.RecordingLog(); + AccessLists lists = AccessLists.load(table, true, new TestSupport.MutableClock(TestSupport.NOW), Runnable::run, log); + table.allError = new LinkageError("driver (test)"); + lists.add(entry(ListEntry.Kind.DENY, "kai")).get(); + assertTrue(lists.remove(ListEntry.Kind.DENY, "kai").get()); + assertEquals(1, log.warnings.size()); + assertEquals(0, lists.count(ListEntry.Kind.DENY)); + } + + @Test void memoryOnlyListsNeverReread() throws Exception { + TestSupport.MutableClock clock = new TestSupport.MutableClock(TestSupport.NOW); + AtomicInteger reads = new AtomicInteger(); + ListTable counting = new ListTable() { + private final ListTable inner = ListTable.memory(); + @Override public List all() throws SQLException { + reads.incrementAndGet(); + return inner.all(); + } + @Override public void put(ListEntry entry) throws SQLException { inner.put(entry); } + @Override public int remove(ListEntry.Kind kind, String target) throws SQLException { return inner.remove(kind, target); } + @Override public int deleteExpired(Instant now) throws SQLException { return inner.deleteExpired(now); } + }; + AccessLists lists = AccessLists.load(counting, false, clock, Runnable::run, new TestSupport.RecordingLog()); + clock.advance(Duration.ofMinutes(5)); + lists.match("Kai", KAI, HOME); + assertEquals(1, reads.get()); + assertFalse(lists.persistent()); + } + + @Test void refreshShowsAnotherServersEntryWithoutAnyEarlierMatch() throws Exception { + Path file = directory.resolve("shared.db"); + TestSupport.MutableClock clock = new TestSupport.MutableClock(TestSupport.NOW); + AccessLists first = load(SqlIpStorage.sqlite(file), clock); + AccessLists second = load(SqlIpStorage.sqlite(file), clock); + first.add(entry(ListEntry.Kind.DENY, "kai")).get(); + // A quiet server: time passes with no login, then the timer fires. + clock.advance(Duration.ofSeconds(5)); + second.refresh(); + assertTrue(second.match("Kai", KAI, HOME).isPresent()); + } + + @Test void memoryListsKeepEntriesAcrossAReload() throws Exception { + TestSupport.MutableClock clock = new TestSupport.MutableClock(TestSupport.NOW); + AccessLists before = AccessLists.load(ListTable.memory(), false, clock, Runnable::run, new TestSupport.RecordingLog()); + before.add(entry(ListEntry.Kind.DENY, "kai")).get(); + AccessLists after = AccessLists.load(ListTable.memory(), false, clock, Runnable::run, new TestSupport.RecordingLog(), before); + assertTrue(after.match("Kai", KAI, HOME).isPresent()); + after.add(entry(ListEntry.Kind.ALLOW, "sam")).get(); + assertEquals(2, after.targets(ListEntry.Kind.DENY).size() + after.targets(ListEntry.Kind.ALLOW).size()); + } + + @Test void memoryListsAfterDatabaseListsKeepTheEntries() throws Exception { + TestSupport.MutableClock clock = new TestSupport.MutableClock(TestSupport.NOW); + AccessLists before = load(SqlIpStorage.sqlite(directory.resolve("lists.db")), clock); + before.add(entry(ListEntry.Kind.DENY, "kai")).get(); + AccessLists after = AccessLists.load(ListTable.memory(), false, clock, Runnable::run, new TestSupport.RecordingLog(), before); + assertTrue(after.match("Kai", KAI, HOME).isPresent()); + after.add(entry(ListEntry.Kind.ALLOW, "sam")).get(); + assertTrue(after.match("Kai", KAI, HOME).isPresent()); + } + + @Test void unreadableTableKeepsThePreviousCopy() throws Exception { + TestSupport.MutableClock clock = new TestSupport.MutableClock(TestSupport.NOW); + BrokenTable good = new BrokenTable(); + AccessLists before = load(good, clock); + before.add(entry(ListEntry.Kind.DENY, "kai")).get(); + BrokenTable down = new BrokenTable(); + down.allError = new LinkageError(); + TestSupport.RecordingLog log = new TestSupport.RecordingLog(); + AccessLists after = AccessLists.load(down, true, clock, Runnable::run, log, before); + assertTrue(after.match("Kai", KAI, HOME).isPresent()); + assertEquals(1, log.warnings.size()); + assertTrue(log.warnings.get(0).contains("LinkageError") && log.warnings.get(0).contains("Using the entries from before the reload"), log.warnings.get(0)); + assertFalse(log.warnings.get(0).contains("null")); + + TestSupport.RecordingLog emptyLog = new TestSupport.RecordingLog(); + AccessLists fresh = AccessLists.load(down, true, clock, Runnable::run, emptyLog); + assertEquals(0, fresh.count(ListEntry.Kind.DENY)); + assertTrue(emptyLog.warnings.get(0).contains("Entries do not apply until the database answers"), emptyLog.warnings.get(0)); + assertFalse(emptyLog.warnings.get(0).contains("out of date")); + } + + @Test void databaseKnownToBeDownIsNotReadAtStartup() throws Exception { + BrokenTable table = new BrokenTable(); + TestSupport.MutableClock clock = new TestSupport.MutableClock(TestSupport.NOW); + AccessLists lists = AccessLists.load(table, true, clock, Runnable::run, new TestSupport.RecordingLog(), null, false); + assertEquals(0, table.reads.get()); + table.inner.put(entry(ListEntry.Kind.DENY, "kai")); + lists.refresh(); + assertTrue(lists.match("Kai", KAI, HOME).isPresent()); + } +} diff --git a/core/src/test/java/io/github/origingate/core/lists/ListEntryTest.java b/core/src/test/java/io/github/origingate/core/lists/ListEntryTest.java new file mode 100644 index 0000000..9747d0b --- /dev/null +++ b/core/src/test/java/io/github/origingate/core/lists/ListEntryTest.java @@ -0,0 +1,72 @@ +package io.github.origingate.core.lists; + +import io.github.origingate.core.TestSupport; +import io.github.origingate.core.net.Addresses; +import org.junit.jupiter.api.Test; + +import java.net.InetAddress; +import java.time.Duration; +import java.time.Instant; +import java.util.UUID; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class ListEntryTest { + private static final UUID KAI = UUID.fromString("123e4567-e89b-12d3-a456-426614174000"); + + private static ListEntry entry(String target, Instant expiresAt) { + return new ListEntry(ListEntry.Kind.DENY, target, expiresAt, null, "console", TestSupport.NOW); + } + + private static InetAddress ip(String text) { + return Addresses.parse(text).orElseThrow(); + } + + @Test void normalizesTargets() { + assertEquals("kai", ListEntry.normalize("Kai")); + assertEquals("203.0.113.7", ListEntry.normalize("203.0.113.7")); + assertEquals("2001:db8:0:0:0:0:0:1", ListEntry.normalize("2001:DB8::1")); + assertEquals("198.51.100.0/24", ListEntry.normalize("198.51.100.0/24")); + assertEquals("203.0.113.7", ListEntry.normalize("203.0.113.7/32")); + assertEquals("123e4567-e89b-12d3-a456-426614174000", ListEntry.normalize("123E4567-E89B-12D3-A456-426614174000")); + assertEquals("123e4567-e89b-12d3-a456-426614174000", ListEntry.normalize("123E4567E89B12D3A456426614174000")); + assertEquals("198.51.100.0/24", ListEntry.normalize("198.51.100.77/24")); + assertEquals("2001:db8:0:0:0:0:0:0/32", ListEntry.normalize("2001:db8::1/32")); + assertEquals(".steve", ListEntry.normalize(".Steve")); + assertThrows(IllegalArgumentException.class, () -> ListEntry.normalize("203.0.113.256")); + assertThrows(IllegalArgumentException.class, () -> ListEntry.normalize("010.0.0.1")); + IllegalArgumentException refused = assertThrows(IllegalArgumentException.class, () -> ListEntry.normalize("two words")); + assertEquals("two words is not a player name, UUID, IP address, or CIDR range", refused.getMessage()); + assertThrows(IllegalArgumentException.class, () -> ListEntry.normalize("a".repeat(33))); + assertThrows(IllegalArgumentException.class, () -> ListEntry.normalize("203.0.113.7/33")); + assertThrows(IllegalArgumentException.class, () -> ListEntry.normalize("")); + } + + @Test void matching() { + ListEntry name = entry("kai", null); + assertTrue(name.matchesPlayer("KAI", UUID.randomUUID())); + assertFalse(name.matchesPlayer("Sam", KAI)); + assertFalse(name.matchesAddress(ip("203.0.113.7"))); + assertFalse(name.isAddress()); + + ListEntry byUuid = entry(KAI.toString(), null); + assertTrue(byUuid.matchesPlayer("Sam", KAI)); + assertFalse(byUuid.matchesPlayer("Sam", UUID.randomUUID())); + + ListEntry range = entry("198.51.100.0/24", null); + assertTrue(range.isAddress()); + assertTrue(range.matchesAddress(ip("198.51.100.200"))); + assertFalse(range.matchesAddress(ip("198.51.101.1"))); + assertFalse(range.matchesPlayer("198.51.100.0/24", KAI)); + + Instant end = TestSupport.NOW.plus(Duration.ofHours(1)); + ListEntry timed = entry("kai", end); + assertTrue(timed.activeAt(end.minusSeconds(1))); + assertFalse(timed.activeAt(end)); + assertFalse(timed.activeAt(end.plusSeconds(1))); + assertTrue(name.activeAt(Instant.MAX.minusSeconds(1))); + } +} diff --git a/core/src/test/java/io/github/origingate/core/net/AddressesTest.java b/core/src/test/java/io/github/origingate/core/net/AddressesTest.java index bc4f3eb..013eaf1 100644 --- a/core/src/test/java/io/github/origingate/core/net/AddressesTest.java +++ b/core/src/test/java/io/github/origingate/core/net/AddressesTest.java @@ -25,6 +25,23 @@ private static InetAddress ip(String text) { assertTrue(Addresses.parse(null).isEmpty()); } + @Test void parsingNeverAsksTheResolver() { + // The counter must see a real lookup, or the zero below would prove nothing. + CountingResolverProvider.reset(); + assertThrows(java.net.UnknownHostException.class, () -> InetAddress.getByName("counter-check.invalid")); + assertEquals(1, CountingResolverProvider.lookups(), "the counting resolver is installed"); + + CountingResolverProvider.reset(); + assertTrue(Addresses.parse(".:").isEmpty()); + assertTrue(Addresses.parse("...:").isEmpty()); + assertTrue(Addresses.parse(".1:2").isEmpty()); + assertTrue(Addresses.parse("localhost").isEmpty()); + assertTrue(Addresses.parse("192.0.2.1").isPresent()); + assertTrue(Addresses.parse("2001:db8::1").isPresent()); + assertTrue(Addresses.parse("::ffff:192.0.2.1").isPresent()); + assertEquals(0, CountingResolverProvider.lookups(), "no text is ever sent to the resolver"); + } + @Test void textIsCanonical() { assertEquals("2001:db8:0:0:0:0:0:1", Addresses.text(ip("2001:db8::1"))); assertEquals("192.0.2.1", Addresses.text(ip("192.0.2.1"))); diff --git a/core/src/test/java/io/github/origingate/core/net/CountingResolverProvider.java b/core/src/test/java/io/github/origingate/core/net/CountingResolverProvider.java new file mode 100644 index 0000000..d24f440 --- /dev/null +++ b/core/src/test/java/io/github/origingate/core/net/CountingResolverProvider.java @@ -0,0 +1,37 @@ +package io.github.origingate.core.net; + +import java.net.InetAddress; +import java.net.UnknownHostException; +import java.net.spi.InetAddressResolver; +import java.net.spi.InetAddressResolverProvider; +import java.util.stream.Stream; + +/** + * Test-only resolver, registered in META-INF/services, that counts name lookups made on each thread and passes them to + * the built-in resolver. Names ending in {@code .invalid} are refused without a query, so tests can check the counter. + */ +public final class CountingResolverProvider extends InetAddressResolverProvider { + private static final ThreadLocal LOOKUPS = ThreadLocal.withInitial(() -> new int[1]); + + /** Name lookups made on the calling thread since the last reset. */ + static int lookups() { return LOOKUPS.get()[0]; } + + static void reset() { LOOKUPS.get()[0] = 0; } + + @Override public InetAddressResolver get(Configuration configuration) { + InetAddressResolver builtin = configuration.builtinResolver(); + return new InetAddressResolver() { + @Override public Stream lookupByName(String host, LookupPolicy policy) throws UnknownHostException { + LOOKUPS.get()[0]++; + if (host.endsWith(".invalid")) throw new UnknownHostException(host); + return builtin.lookupByName(host, policy); + } + + @Override public String lookupByAddress(byte[] address) throws UnknownHostException { + return builtin.lookupByAddress(address); + } + }; + } + + @Override public String name() { return "OriginGate test counting resolver"; } +} diff --git a/core/src/test/java/io/github/origingate/core/net/HttpTransportTest.java b/core/src/test/java/io/github/origingate/core/net/HttpTransportTest.java index 7915242..86ed235 100644 --- a/core/src/test/java/io/github/origingate/core/net/HttpTransportTest.java +++ b/core/src/test/java/io/github/origingate/core/net/HttpTransportTest.java @@ -67,6 +67,28 @@ class HttpTransportTest { } } + @Test void postSendsBody() throws Exception { + List seen = new CopyOnWriteArrayList<>(); + HttpServer server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0); + server.createContext("/", exchange -> { + seen.add(exchange.getRequestMethod() + " " + exchange.getRequestHeaders().getFirst("Content-Length") + " " + + exchange.getRequestHeaders().getFirst("Content-Type") + " " + + new String(exchange.getRequestBody().readAllBytes(), StandardCharsets.UTF_8)); + exchange.sendResponseHeaders(204, -1); + exchange.close(); + }); + server.start(); + try (HttpTransport http = HttpTransport.newHttpClient()) { + HttpRequest request = HttpRequest.newBuilder(URI.create("http://127.0.0.1:" + server.getAddress().getPort() + "/")) + .timeout(Duration.ofSeconds(2)).header("Content-Type", "application/json") + .POST("{\"a\":\"é\"}".getBytes(StandardCharsets.UTF_8)).build(); + assertEquals(204, http.send(request, HttpResponse.BodyHandlers.discarding()).statusCode()); + assertEquals(List.of("POST 10 application/json {\"a\":\"é\"}"), seen); + } finally { + server.stop(0); + } + } + @Test void closeDoesNotWaitForABlockedRead() throws Exception { try (SlowServer server = new SlowServer(0, 3000)) { HttpTransport http = HttpTransport.newHttpClient(); diff --git a/core/src/test/java/io/github/origingate/core/report/DiscordWebhookTest.java b/core/src/test/java/io/github/origingate/core/report/DiscordWebhookTest.java new file mode 100644 index 0000000..fa8fa87 --- /dev/null +++ b/core/src/test/java/io/github/origingate/core/report/DiscordWebhookTest.java @@ -0,0 +1,265 @@ +package io.github.origingate.core.report; + +import com.google.gson.JsonObject; +import com.google.gson.JsonParser; +import com.sun.net.httpserver.HttpServer; +import io.github.origingate.core.TestSupport; +import io.github.origingate.core.lookup.IpInfo; +import io.github.origingate.core.lookup.LookupService; +import io.github.origingate.core.net.HttpTransport; +import io.github.origingate.core.rules.Decision; +import io.github.origingate.core.rules.Rule; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.net.InetSocketAddress; +import java.net.URI; +import java.nio.charset.StandardCharsets; +import java.time.Instant; +import java.util.List; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.concurrent.atomic.AtomicInteger; + +import static org.junit.jupiter.api.Assertions.*; + +class DiscordWebhookTest { + private static final String PATH = "/api/webhooks/123456/secret-token"; + private HttpServer server; + private HttpTransport http; + private final List bodies = new CopyOnWriteArrayList<>(); + private final List contentTypes = new CopyOnWriteArrayList<>(); + private final List statuses = new CopyOnWriteArrayList<>(); + private final AtomicInteger calls = new AtomicInteger(); + private final TestSupport.RecordingLog log = new TestSupport.RecordingLog(); + private DiscordWebhook webhook; + + @BeforeEach void start() throws Exception { + server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0); + server.createContext(PATH, exchange -> { + bodies.add(new String(exchange.getRequestBody().readAllBytes(), StandardCharsets.UTF_8)); + contentTypes.add(exchange.getRequestHeaders().getFirst("Content-Type")); + int index = calls.getAndIncrement(); + int status = index < statuses.size() ? statuses.get(index) : 204; + exchange.sendResponseHeaders(status, -1); + exchange.close(); + }); + server.start(); + http = HttpTransport.newHttpClient(); + } + + @AfterEach void stop() { + if (webhook != null) webhook.close(); + http.close(); + server.stop(0); + } + + private DiscordWebhook webhook(boolean showIp) { + webhook = new DiscordWebhook(URI.create("http://127.0.0.1:" + server.getAddress().getPort() + PATH), showIp, http, log, "OriginGate/test"); + return webhook; + } + + private static Decision decision(Decision.Outcome outcome, Rule rule, String note, IpInfo info, boolean dryRun) { + LookupService.Result lookup = info == null ? null : new LookupService.Result(info, LookupService.Source.PROVIDER, null); + return new Decision(outcome, rule, note, lookup, dryRun); + } + + private static IpInfo answer(String organisation) { + return new IpInfo("203.0.113.7", "Example VPN", organisation, null, null, null, "Netherlands", "NL", null, true, false, null, Instant.EPOCH); + } + + private static Decision kick(String note) { + return decision(Decision.Outcome.DENY, Rule.VPN, note, answer("Example Org"), false); + } + + private JsonObject post(int index) { + return JsonParser.parseString(bodies.get(index)).getAsJsonObject(); + } + + private String content(int index) { + return post(index).get("content").getAsString(); + } + + @Test void postsKickBypassAndAlert() { + DiscordWebhook hook = webhook(false); + hook.decision(TestSupport.player("Kai", "203.0.113.7"), kick("flagged as VPN")); + hook.flush(); + hook.decision(TestSupport.player("Kai", "203.0.113.7"), decision(Decision.Outcome.BYPASS, Rule.VPN, "flagged as VPN", answer("Example Org"), false)); + hook.flush(); + hook.alert(false, "provider proxycheck is paused"); + hook.flush(); + hook.alert(true, "provider proxycheck is back"); + hook.flush(); + assertEquals(4, bodies.size()); + assertEquals("Kicked **Kai** by the vpn rule: flagged as VPN (Example VPN / Example Org, Netherlands)", content(0)); + assertEquals("Let in **Kai** with a vpn bypass: flagged as VPN (Example VPN / Example Org, Netherlands)", content(1)); + assertEquals("Alert: provider proxycheck is paused", content(2)); + assertEquals("Recovered: provider proxycheck is back", content(3)); + assertEquals("OriginGate", post(0).get("username").getAsString()); + assertEquals("application/json", contentTypes.get(0)); + } + + @Test void floodBecomesSummary() { + DiscordWebhook hook = webhook(false); + for (int i = 0; i < 25; i++) hook.decision(TestSupport.player("Kai", "203.0.113.7"), kick("flagged as VPN")); + hook.flush(); + assertEquals(1, bodies.size()); + String[] lines = content(0).split("\n"); + assertEquals(11, lines.length); + for (int i = 0; i < 10; i++) assertTrue(lines[i].startsWith("Kicked "), lines[i]); + assertEquals("And 15 more.", lines[10]); + hook.flush(); + assertEquals(1, bodies.size()); + } + + @Test void dryRunAndAllowAreNotPosted() { + DiscordWebhook hook = webhook(false); + hook.decision(TestSupport.player("Kai", "203.0.113.7"), decision(Decision.Outcome.DENY, Rule.VPN, "flagged as VPN", answer("Example Org"), true)); + hook.decision(TestSupport.player("Kai", "203.0.113.7"), decision(Decision.Outcome.ALLOW, null, null, null, false)); + hook.decision(TestSupport.player("Kai", "203.0.113.7"), decision(Decision.Outcome.BYPASS, Rule.VPN, "flagged as VPN", answer("Example Org"), true)); + hook.flush(); + assertEquals(0, bodies.size()); + } + + @Test void addressesInTextAreHiddenUnlessShowIpIsOn() { + String[] notes = {"address is on the deny list (203.0.113.7)", "No provider answered the VPN check for 203.0.113.7", + "no data for 2001:db8::7.", "range 203.0.113.0/24 and 2001:db8::/32 at 12:30"}; + DiscordWebhook hook = webhook(false); + for (String note : notes) hook.decision(TestSupport.player("Kai", "203.0.113.7"), kick(note)); + hook.decision(TestSupport.player("Kai", "203.0.113.7"), new Decision(Decision.Outcome.BYPASS, Rule.VPN, null, null, false, "from 203.0.113.7")); + hook.alert(false, "proxycheck.io response has no data for 203.0.113.7"); + hook.flush(); + String hidden = content(0); + assertFalse(hidden.contains("203.0.113") || hidden.contains("2001") || hidden.contains("db8"), hidden); + assertTrue(hidden.contains("IP hidden") && hidden.contains("at 12:30"), hidden); + assertTrue(hidden.contains("Alert: proxycheck.io response has no data for IP hidden"), hidden); + hook.close(); + DiscordWebhook shown = webhook(true); + for (String note : notes) shown.decision(TestSupport.player("Kai", "203.0.113.7"), kick(note)); + shown.alert(false, "proxycheck.io response has no data for 203.0.113.7"); + shown.flush(); + String text = content(1); + assertTrue(text.contains("203.0.113.7") && text.contains("2001:db8::7") && !text.contains("IP hidden"), text); + } + + @Test void addressesWithPortsAndColonsAreHidden() { + DiscordWebhook hook = webhook(false); + hook.decision(TestSupport.player("Kai", "203.0.113.7"), kick("No provider answered the VPN check for 203.0.113.7: timeout")); + hook.alert(false, "connect failed for 203.0.113.7:25565 today"); + hook.alert(false, "connect failed for [2001:db8::1]:443 today"); + hook.flush(); + String text = content(0); + assertFalse(text.contains("203.0.113.7") || text.contains("2001:db8::1"), text); + assertTrue(text.contains("for IP hidden: timeout"), text); + assertTrue(text.contains("connect failed for IP hidden:25565 today"), text); + assertTrue(text.contains("connect failed for \\[IP hidden\\]:443 today"), text); + } + + @Test void addressesInLookupAnswersAreHidden() { + DiscordWebhook hook = webhook(false); + hook.decision(TestSupport.player("Kai", "203.0.113.7"), + decision(Decision.Outcome.DENY, Rule.VPN, "flagged as VPN", answer("static.203.0.113.7.example.net"), false)); + hook.flush(); + assertFalse(content(0).contains("203.0.113.7"), content(0)); + } + + @Test void longLinesKeepTheAddressAndCaution() { + DiscordWebhook hook = webhook(true); + hook.decision(TestSupport.player("Kai", "203.0.113.7"), + new Decision(Decision.Outcome.BYPASS, Rule.VPN, "n".repeat(300), null, false, "anyone can use this name")); + hook.flush(); + String content = content(0); + assertTrue(content.length() <= 190, "length " + content.length()); + assertTrue(content.endsWith("n... IP 203.0.113.7. Caution: anyone can use this name."), content); + } + + @Test void bodySuppressesEmbeds() { + DiscordWebhook hook = webhook(false); + hook.alert(false, "see https://example.com/x"); + hook.flush(); + assertEquals(4, post(0).get("flags").getAsInt()); + } + + @Test void showIpAddsAddress() { + DiscordWebhook hook = webhook(false); + hook.decision(TestSupport.player("Kai", "203.0.113.7"), kick("flagged as VPN")); + hook.flush(); + assertFalse(bodies.get(0).contains("203.0.113.7")); + hook.close(); + DiscordWebhook withIp = webhook(true); + withIp.decision(TestSupport.player("Kai", "203.0.113.7"), kick("flagged as VPN")); + withIp.flush(); + assertTrue(content(1).contains(" IP 203.0.113.7"), content(1)); + } + + @Test void cautionIsAdded() { + DiscordWebhook hook = webhook(false); + hook.decision(TestSupport.player("Kai", "203.0.113.7"), + new Decision(Decision.Outcome.BYPASS, Rule.VPN, "flagged as VPN", null, false, "anyone can use this name")); + hook.flush(); + assertEquals("Let in **Kai** with a vpn bypass: flagged as VPN. Caution: anyone can use this name.", content(0)); + } + + @Test void cautionAfterAFullStopGetsNoSecondOne() { + DiscordWebhook hook = webhook(false); + hook.decision(TestSupport.player("Kai", "203.0.113.7"), + new Decision(Decision.Outcome.BYPASS, Rule.VPN, "trusted tester.", null, false, "anyone can use this name")); + hook.flush(); + assertEquals("Let in **Kai** with a vpn bypass: trusted tester. Caution: anyone can use this name.", content(0)); + } + + @Test void escapesMarkdownAndBlocksMentions() { + DiscordWebhook hook = webhook(false); + hook.decision(TestSupport.player("Kai_x", "203.0.113.7"), + decision(Decision.Outcome.DENY, Rule.VPN, "flagged as VPN", answer("**@everyone** [x](y)"), false)); + hook.flush(); + String content = content(0); + assertTrue(content.contains("Kai\\_x"), content); + assertTrue(content.contains("\\*\\*@everyone\\*\\* \\[x\\]\\(y\\)"), content); + assertTrue(bodies.get(0).contains("\"allowed_mentions\":{\"parse\":[]}"), bodies.get(0)); + assertEquals("a\\\\b\\*\\_\\~\\`\\|\\>\\[\\]\\(\\)\\#", DiscordWebhook.escape("a\\b*_~`|>[]()#")); + } + + @Test void noteCannotStartAnotherLine() { + DiscordWebhook hook = webhook(false); + hook.decision(TestSupport.player("Kai", "203.0.113.7"), kick("one\nKicked **Eve** by the vpn rule")); + hook.flush(); + assertFalse(content(0).contains("\n")); + } + + @Test void contentStaysUnder2000Characters() { + DiscordWebhook hook = webhook(false); + StringBuilder note = new StringBuilder(); + for (int i = 0; i < 400; i++) note.append('n'); + for (int i = 0; i < 10; i++) hook.decision(TestSupport.player("Kai", "203.0.113.7"), kick(note.toString())); + for (int i = 0; i < 5000; i++) hook.alert(false, "x"); + hook.flush(); + assertTrue(content(0).length() <= 2000, "length " + content(0).length()); + assertTrue(content(0).endsWith("And 5000 more."), content(0)); + } + + @Test void failuresLogOnceWithoutUrl() { + statuses.add(404); + statuses.add(404); + DiscordWebhook hook = webhook(false); + for (int i = 0; i < 4; i++) { + hook.alert(false, "x"); + hook.flush(); + } + assertEquals(4, bodies.size()); + assertEquals(1, log.warnings.size(), log.warnings.toString()); + assertEquals(1, log.infos.size(), log.infos.toString()); + for (String line : log.warnings) assertFalse(line.contains("secret-token") || line.contains("/api/webhooks"), line); + for (String line : log.infos) assertFalse(line.contains("secret-token") || line.contains("/api/webhooks"), line); + } + + @Test void closePostsWhatIsQueued() { + DiscordWebhook hook = webhook(false); + hook.alert(false, "last words"); + hook.close(); + assertEquals(1, bodies.size()); + hook.alert(false, "after close"); + hook.close(); + assertEquals(1, bodies.size()); + } +} diff --git a/core/src/test/java/io/github/origingate/core/rules/GateTest.java b/core/src/test/java/io/github/origingate/core/rules/GateTest.java index 0a3f4e8..e35facb 100644 --- a/core/src/test/java/io/github/origingate/core/rules/GateTest.java +++ b/core/src/test/java/io/github/origingate/core/rules/GateTest.java @@ -5,6 +5,9 @@ import io.github.origingate.core.TestSupport.FakeProvider; import io.github.origingate.core.TestSupport.FakeStorage; import io.github.origingate.core.config.OriginGateConfig; +import io.github.origingate.core.lists.AccessLists; +import io.github.origingate.core.lists.ListEntry; +import io.github.origingate.core.lists.ListTable; import io.github.origingate.core.lookup.IpInfo; import io.github.origingate.core.lookup.LookupException; import io.github.origingate.core.lookup.LookupService; @@ -17,6 +20,7 @@ import java.nio.file.Path; import java.time.Clock; import java.time.Duration; +import java.time.Instant; import java.util.List; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; @@ -55,6 +59,135 @@ private Gate gate(Object... changes) throws Exception { return new Gate(config, lookups, Log.NONE); } + private Gate gateWithLists(AccessLists lists, boolean namesUnverified, Object... changes) throws Exception { + OriginGateConfig config = TestSupport.config(directory, changes); + Clock clock = Clock.fixed(TestSupport.NOW, java.time.ZoneOffset.UTC); + LookupService lookups = new LookupService(TestSupport.chain(provider), new FakeStorage(), new MemoryCache(100, Duration.ofDays(30), clock), + Duration.ofDays(30), workers, clock, Log.NONE); + return new Gate(config, lookups, Log.NONE, namesUnverified, lists); + } + + private Gate gateWithOnline(OnlineCount online, AccessLists lists, Object... changes) throws Exception { + OriginGateConfig config = TestSupport.config(directory, changes); + Clock clock = Clock.fixed(TestSupport.NOW, java.time.ZoneOffset.UTC); + LookupService lookups = new LookupService(TestSupport.chain(provider), new FakeStorage(), new MemoryCache(100, Duration.ofDays(30), clock), + Duration.ofDays(30), workers, clock, Log.NONE); + return new Gate(config, lookups, Log.NONE, false, lists, online); + } + + private static AccessLists lists(ListEntry... entries) { + Clock clock = Clock.fixed(TestSupport.NOW, java.time.ZoneOffset.UTC); + AccessLists lists = AccessLists.load(ListTable.memory(), false, clock, Runnable::run, Log.NONE); + for (ListEntry entry : entries) lists.add(entry).join(); + return lists; + } + + private static ListEntry entry(ListEntry.Kind kind, String target, Instant expiresAt, String note) { + return new ListEntry(kind, target, expiresAt, note, "console", TestSupport.NOW); + } + + @Test void allowListLetsVpnInWithoutLookup() throws Exception { + Gate gate = gateWithLists(lists(entry(ListEntry.Kind.ALLOW, "kai", null, "friend")), false); + Decision decision = run(gate, player("Kai", VPN_IP)); + assertEquals(Outcome.ALLOW, decision.outcome()); + assertNull(decision.rule()); + assertEquals("player is on the allow list: friend", decision.note()); + assertEquals(0, provider.calls.get()); + Gate byAddress = gateWithLists(lists(entry(ListEntry.Kind.ALLOW, "203.0.113.0/24", null, null)), false); + Decision viaAddress = run(byAddress, player("Alex", VPN_IP)); + assertEquals(Outcome.ALLOW, viaAddress.outcome()); + assertEquals("address is on the allow list (203.0.113.0/24)", viaAddress.note()); + assertEquals(0, provider.calls.get()); + } + + @Test void allowListNameGetsOfflineCaution() throws Exception { + Decision byName = run(gateWithLists(lists(entry(ListEntry.Kind.ALLOW, "kai", null, null)), true), player("Kai", VPN_IP)); + assertEquals(Gate.UNVERIFIED_NAME, byName.caution()); + Decision byAddress = run(gateWithLists(lists(entry(ListEntry.Kind.ALLOW, "203.0.113.7", null, null)), true), player("Kai", VPN_IP)); + assertEquals(Outcome.ALLOW, byAddress.outcome()); + assertNull(byAddress.caution()); + } + + @Test void denyListKicksBeforeLookup() throws Exception { + AccessLists lists = lists(entry(ListEntry.Kind.DENY, "198.51.100.0/24", null, "bots")); + Decision decision = run(gateWithLists(lists, false), player("Kai", PROXY_IP, "origingate.bypass.proxy")); + assertEquals(Outcome.DENY, decision.outcome()); + assertEquals(Rule.DENY_LIST, decision.rule()); + assertEquals("address is on the deny list (198.51.100.0/24): bots", decision.note()); + assertEquals(0, provider.calls.get()); + Decision dry = run(gateWithLists(lists, false, "dry-run", true), player("Kai", PROXY_IP)); + assertEquals(Outcome.DENY, dry.outcome()); + assertFalse(dry.kicks()); + } + + @Test void configBypassBeatsDenyList() throws Exception { + Gate gate = gateWithLists(lists(entry(ListEntry.Kind.DENY, "kai", null, null)), false, "bypass.players", List.of("Kai")); + assertEquals(Outcome.ALLOW, run(gate, player("Kai", VPN_IP)).outcome()); + } + + @Test void expiredDenyEntryIsIgnored() throws Exception { + Gate gate = gateWithLists(lists(entry(ListEntry.Kind.DENY, "kai", TestSupport.NOW.minusSeconds(1), null)), false); + Decision decision = run(gate, player("Kai", HOME_IP)); + assertEquals(Outcome.ALLOW, decision.outcome()); + assertNull(decision.rule()); + } + + @Test void accountsPerIpKicksAtTheLimit() throws Exception { + OnlineCount two = (address, except) -> 2; + Decision full = run(gateWithOnline(two, AccessLists.empty(), "rules.accounts-per-ip.enabled", true, + "rules.accounts-per-ip.max", 2), player("Kai", HOME_IP)); + assertEquals(Outcome.DENY, full.outcome()); + assertEquals(Rule.ACCOUNTS_PER_IP, full.rule()); + assertEquals("2 players are already online from this address", full.note()); + assertEquals(0, provider.calls.get()); + OnlineCount one = (address, except) -> 1; + Decision room = run(gateWithOnline(one, AccessLists.empty(), "rules.accounts-per-ip.enabled", true, + "rules.accounts-per-ip.max", 2), player("Kai", HOME_IP)); + assertEquals(Outcome.ALLOW, room.outcome()); + assertEquals(1, provider.calls.get()); + } + + @Test void accountsPerIpPassesJoiningUuid() throws Exception { + java.util.concurrent.atomic.AtomicReference seen = new java.util.concurrent.atomic.AtomicReference<>(); + java.util.concurrent.atomic.AtomicReference from = new java.util.concurrent.atomic.AtomicReference<>(); + OnlineCount count = (address, except) -> { + from.set(address); + seen.set(except); + return 0; + }; + LoginAttempt attempt = player("Kai", HOME_IP); + run(gateWithOnline(count, AccessLists.empty(), "rules.accounts-per-ip.enabled", true), attempt); + assertEquals(attempt.uuid(), seen.get()); + assertEquals(attempt.address(), from.get()); + } + + @Test void accountsPerIpIsOffByDefault() throws Exception { + assertEquals(Outcome.ALLOW, run(gateWithOnline((address, except) -> 50, AccessLists.empty()), player("Kai", HOME_IP)).outcome()); + } + + @Test void accountsPerIpSkipsPrivateAddresses() throws Exception { + Decision decision = run(gateWithOnline((address, except) -> 50, AccessLists.empty(), + "rules.accounts-per-ip.enabled", true, "lookup.skip-private-addresses", true), player("Kai", "127.0.0.1")); + assertEquals(Outcome.ALLOW, decision.outcome()); + assertEquals("private address, lookup skipped", decision.note()); + } + + @Test void allowListBeatsAccountsPerIp() throws Exception { + AccessLists lists = lists(entry(ListEntry.Kind.ALLOW, HOME_IP, null, null)); + Decision decision = run(gateWithOnline((address, except) -> 50, lists, "rules.accounts-per-ip.enabled", true), + player("Kai", HOME_IP)); + assertEquals(Outcome.ALLOW, decision.outcome()); + assertEquals(0, provider.calls.get()); + } + + @Test void dryRunDoesNotKickAccountsPerIp() throws Exception { + Decision decision = run(gateWithOnline((address, except) -> 5, AccessLists.empty(), + "rules.accounts-per-ip.enabled", true, "dry-run", true), player("Kai", HOME_IP)); + assertEquals(Outcome.DENY, decision.outcome()); + assertEquals(Rule.ACCOUNTS_PER_IP, decision.rule()); + assertFalse(decision.kicks()); + } + private static Decision run(Gate gate, LoginAttempt attempt) throws Exception { return gate.check(attempt).get(15, TimeUnit.SECONDS); } @@ -276,6 +409,67 @@ private FakeProvider withHosting() { assertEquals(Outcome.DENY, decision.outcome(), "a VPN bypass does not cover a denied network"); } + private static final String SCHOOL_IP = "198.51.100.77"; + + private void withSchool() { + provider.answer(new IpInfo(SCHOOL_IP, "Example Net", "Example School District", null, "Example City", "Example Region", + "Canada", "CA", "AS64999", false, true, "Residential", TestSupport.NOW)); + } + + @Test void allowNetworksLetsInFlaggedNetwork() throws Exception { + Gate gate = gate("rules.allow-networks.enabled", true, "rules.allow-networks.asns", List.of("AS64500")); + Decision decision = run(gate, player("Kai", VPN_IP)); + assertEquals(Outcome.ALLOW, decision.outcome()); + assertEquals(Rule.ALLOW_NETWORKS, decision.rule()); + assertEquals("network is on the allow list (AS64500)", decision.note()); + } + + @Test void allowNetworksIgnoresNames() throws Exception { + withSchool(); + Gate gate = gate("rules.allow-networks.enabled", true, "rules.allow-networks.asns", List.of("AS64500")); + Decision decision = run(gate, player("Kai", SCHOOL_IP)); + assertEquals(Outcome.DENY, decision.outcome()); + assertEquals(Rule.PROXY, decision.rule()); + } + + @Test void allowNetworksExemptsHostingToo() throws Exception { + withHosting(); + Gate gate = gate("rules.hosting.enabled", true, "rules.allow-networks.enabled", true, + "rules.allow-networks.asns", List.of("AS64496")); + Decision decision = run(gate, player("Kai", HOSTING_IP)); + assertEquals(Outcome.ALLOW, decision.outcome()); + assertEquals(Rule.ALLOW_NETWORKS, decision.rule()); + } + + @Test void allowNetworksKeepsCountryAndDenyNetworks() throws Exception { + Gate country = gate("rules.allow-networks.enabled", true, "rules.allow-networks.asns", List.of("AS64500"), + "rules.country.enabled", true, "rules.country.countries", List.of("CA")); + Decision byCountry = run(country, player("Kai", VPN_IP)); + assertEquals(Outcome.DENY, byCountry.outcome()); + assertEquals(Rule.COUNTRY, byCountry.rule()); + + Gate denied = gate("rules.allow-networks.enabled", true, "rules.allow-networks.asns", List.of("AS64500"), + "rules.deny-networks.enabled", true, "rules.deny-networks.asns", List.of("AS64500")); + Decision byNetwork = run(denied, player("Kai", VPN_IP)); + assertEquals(Outcome.DENY, byNetwork.outcome()); + assertEquals(Rule.DENY_NETWORKS, byNetwork.rule()); + } + + @Test void cleanAnswerFromAllowedNetworkHasNoRule() throws Exception { + Gate gate = gate("rules.allow-networks.enabled", true, "rules.allow-networks.asns", List.of("AS64500")); + Decision decision = run(gate, player("Kai", HOME_IP)); + assertEquals(Outcome.ALLOW, decision.outcome()); + assertNull(decision.rule()); + } + + @Test void matchSkipsExemptedRules() throws Exception { + OriginGateConfig config = TestSupport.config(directory, "rules.allow-networks.enabled", true, + "rules.allow-networks.asns", List.of("AS64500")); + assertFalse(Gate.match(config.rules(), info(VPN_IP, "Netherlands", "NL", true, true)).isPresent()); + OriginGateConfig plain = TestSupport.config(directory); + assertTrue(Gate.match(plain.rules(), info(VPN_IP, "Netherlands", "NL", true, true)).isPresent()); + } + @Test void disabledRulesAreSkipped() throws Exception { Gate gate = gate("rules.vpn.enabled", false, "rules.proxy.enabled", false); Decision decision = run(gate, player("Alex", VPN_IP)); diff --git a/core/src/test/java/io/github/origingate/core/storage/RemoteStorageTest.java b/core/src/test/java/io/github/origingate/core/storage/RemoteStorageTest.java index d9eb69b..4555db1 100644 --- a/core/src/test/java/io/github/origingate/core/storage/RemoteStorageTest.java +++ b/core/src/test/java/io/github/origingate/core/storage/RemoteStorageTest.java @@ -2,6 +2,7 @@ import io.github.origingate.core.TestSupport; import io.github.origingate.core.config.OriginGateConfig; +import io.github.origingate.core.lists.ListEntry; import io.github.origingate.core.lookup.IpInfo; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Tag; @@ -38,6 +39,7 @@ class RemoteStorageTest { database, env("OG_TEST_DB_USERNAME", "root"), env("OG_TEST_DB_PASSWORD", ""), env("OG_TEST_DB_SSL_MODE", "disable"), 3000, 5000); try (Connection connection = open(); Statement statement = connection.createStatement()) { statement.execute("DROP TABLE IF EXISTS " + SqlIpStorage.TABLE); + statement.execute("DROP TABLE IF EXISTS " + SqlIpStorage.LIST_TABLE); } } @@ -64,6 +66,21 @@ private Connection open() throws SQLException { SqlIpStorage.mysql(config); // A second start keeps the existing table. } + @Test void listTableRoundTrip() throws SQLException { + SqlIpStorage storage = SqlIpStorage.mysql(config); + Instant soon = TestSupport.NOW.plusSeconds(60); + ListEntry allow = new ListEntry(ListEntry.Kind.ALLOW, "kai", soon, "it's Kai", "console", TestSupport.NOW); + ListEntry deny = new ListEntry(ListEntry.Kind.DENY, "198.51.100.0/24", null, null, "Sam", TestSupport.NOW.plusSeconds(5)); + storage.put(allow); + storage.put(deny); + assertEquals(List.of(allow, deny), storage.all()); + assertEquals(0, storage.remove(ListEntry.Kind.DENY, "kai")); + assertEquals(0, storage.deleteExpired(TestSupport.NOW)); + assertEquals(1, storage.deleteExpired(soon)); + assertEquals(1, storage.remove(ListEntry.Kind.DENY, "198.51.100.0/24")); + assertEquals(List.of(), storage.all()); + } + @Test void twoProxiesWritingTheSameIpDoNotFail() throws Exception { SqlIpStorage first = SqlIpStorage.mysql(config); SqlIpStorage second = SqlIpStorage.mysql(config); diff --git a/core/src/test/java/io/github/origingate/core/storage/SqlIpStorageTest.java b/core/src/test/java/io/github/origingate/core/storage/SqlIpStorageTest.java index c6a31b2..b57dbe4 100644 --- a/core/src/test/java/io/github/origingate/core/storage/SqlIpStorageTest.java +++ b/core/src/test/java/io/github/origingate/core/storage/SqlIpStorageTest.java @@ -1,6 +1,7 @@ package io.github.origingate.core.storage; import io.github.origingate.core.TestSupport; +import io.github.origingate.core.lists.ListEntry; import io.github.origingate.core.lookup.IpInfo; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; @@ -41,6 +42,27 @@ private static IpInfo read(SqlIpStorage storage, String ip, Instant notBefore) t assertEquals("O'Brien Networks", read.provider()); } + @Test void listTableRoundTrip() throws SQLException { + SqlIpStorage storage = SqlIpStorage.sqlite(directory.resolve("lists.db")); + Instant soon = TestSupport.NOW.plusSeconds(60); + ListEntry allow = new ListEntry(ListEntry.Kind.ALLOW, "kai", soon, "it's Kai", "console", TestSupport.NOW); + ListEntry deny = new ListEntry(ListEntry.Kind.DENY, "198.51.100.0/24", null, null, "Sam", TestSupport.NOW.plusSeconds(5)); + storage.put(allow); + storage.put(deny); + assertEquals(java.util.List.of(allow, deny), storage.all()); + + ListEntry flipped = new ListEntry(ListEntry.Kind.DENY, "kai", null, null, "console", TestSupport.NOW); + storage.put(flipped); + assertEquals(java.util.List.of(flipped, deny), storage.all()); + + assertEquals(0, storage.remove(ListEntry.Kind.ALLOW, "kai")); + assertEquals(1, storage.remove(ListEntry.Kind.DENY, "kai")); + storage.put(allow); + assertEquals(0, storage.deleteExpired(TestSupport.NOW)); + assertEquals(1, storage.deleteExpired(soon)); + assertEquals(java.util.List.of(deny), storage.all()); + } + @Test void nullsStayNull() throws SQLException { SqlIpStorage storage = SqlIpStorage.sqlite(directory.resolve("test.db")); storage.save(new IpInfo("192.0.2.2", null, null, null, null, null, "Canada", null, null, false, true, null, TestSupport.NOW)); diff --git a/core/src/test/resources/META-INF/services/java.net.spi.InetAddressResolverProvider b/core/src/test/resources/META-INF/services/java.net.spi.InetAddressResolverProvider new file mode 100644 index 0000000..9f2e41c --- /dev/null +++ b/core/src/test/resources/META-INF/services/java.net.spi.InetAddressResolverProvider @@ -0,0 +1 @@ +io.github.origingate.core.net.CountingResolverProvider diff --git a/core/src/test/resources/upgrade/config-1.1.1.yml b/core/src/test/resources/upgrade/config-1.1.1.yml new file mode 100644 index 0000000..006d530 --- /dev/null +++ b/core/src/test/resources/upgrade/config-1.1.1.yml @@ -0,0 +1,158 @@ +# OriginGate settings. Run "origingate reload" after editing. +# Updates keep this file. New settings are not added automatically. + +# Format version of this file. Leave unchanged. +config-version: 1 + +# Run every check and log the result, but never kick anyone. +# Useful for the first days, to see who would be kicked. +dry-run: false + +# What the console shows for each login. Each level includes the ones before it. +# none: nothing (startup, reload, and errors still show) +# kicks: kicked players (and WOULD-DENY in dry-run) +# matches: every login where a rule matched or the lookup failed, including bypasses +# all: every login, one line each +# debug: every login, plus each step of the check +console-log: matches + +lookup: + # Let in players from localhost or your LAN without a lookup. + skip-private-addresses: true + # What to do when the lookup fails or takes longer than wait-millis: allow or deny. + on-lookup-failure: allow + # Longest time a login waits for the lookup, in milliseconds (1000-20000). + wait-millis: 2500 + # Most lookups sent to providers in any 60 seconds (0-100000), so a wave of bots cannot use up a provider's + # daily quota. Logins over it are not looked up. 0 means no limit. + max-lookups-per-minute: 0 + # What to do with a login over that limit: allow or deny. Without this setting, on-lookup-failure decides. + # deny turns away new, unchecked addresses during a flood; addresses looked up within max-age-days are not affected. + # on-budget-exceeded: deny + # Providers asked for the country, in order. When one fails, the next one is asked. + # Any of: proxycheck, iphub, ip-api, ipinfo, maxmind. + country-from: [proxycheck] + # Providers asked whether the IP is a VPN or proxy, in order. Any of: proxycheck, iphub, ip-api. + # A provider already asked for the country is not asked again. + # Leave empty ([]) for no VPN check; then the vpn and proxy rules below must be disabled, and lookups are not saved. + vpn-from: [proxycheck] + proxycheck: + # proxycheck.io v3 API. Change only for testing. + base-url: "https://proxycheck.io/v3/" + # Your proxycheck.io API keys, used in turn. Leave empty to use proxycheck.io without a key (100 lookups per day). + # When a key is rejected or rate-limited, it is skipped for 60 seconds and the next key is tried. + api-keys: [] + # Longest time for one API request, in milliseconds (500-20000). + request-timeout-millis: 3500 + iphub: + # Your IPHub API keys (iphub.info), used in turn. At least one is needed to use IPHub. + api-keys: [] + request-timeout-millis: 3500 + ip-api: + # Your ip-api.com Pro key. Leave empty for the free service, which uses plain HTTP and does not allow commercial use. + api-key: "" + request-timeout-millis: 3500 + ipinfo: + # Your IPinfo token (ipinfo.io). Needed to use IPinfo. The free Lite plan gives the country only, no VPN check. + token: "" + request-timeout-millis: 3500 + maxmind: + # MaxMind GeoLite2 database file, inside the plugin folder. Gives the country only, no VPN check. + file: data/GeoLite2-Country.mmdb + # Which file to download when account-id and license-key are set: GeoLite2-Country or GeoLite2-City. + edition: GeoLite2-Country + # Your free MaxMind account ID and license key, to download the file and keep it updated. + # Leave as 0 and "" to place the file yourself. + account-id: 0 + license-key: "" + +storage: + # sqlite (local file) or mysql (also for MariaDB). Saved lookups are not copied when switching. + type: sqlite + # Lookups older than this many days (1-365) are looked up again. + max-age-days: 30 + # Lookups older than this many days are deleted from storage. 0 keeps them forever. + # Otherwise it must be at least the max-age-days value above, up to 3650. + # Each IP keeps only its latest lookup, so a new lookup replaces the old one. + keep-days: 30 + # Most recent lookups kept in memory (100-1000000). + memory-cache-size: 10000 + sqlite: + # Database file, inside the plugin folder. + file: data/origingate.db + # Used only when type is mysql. The table is created automatically. + mysql: + host: localhost + port: 3306 + database: origingate + username: origingate + # Literal password. Environment-variable references are not expanded. + password: "" + # verify-full checks the certificate and host name. Use disable only on a protected network. + ssl-mode: verify-full + # Timeouts in milliseconds (100-30000). + connect-timeout-millis: 3000 + socket-timeout-millis: 5000 + +# Anyone matching here skips every check below. +bypass: + # Any of these permissions. + permissions: [] + # Player names or UUIDs, for example ["Steve"]. + players: [] + # IP addresses or CIDR ranges, for example 203.0.113.0/24. + addresses: [] + +# Checked in this order. The first rule that matches decides. +# A player with any of a rule's bypass-permissions is let in instead of kicked by that rule. +rules: + # Kicks the IP addresses or ranges you list, without a lookup. + deny-addresses: + enabled: false + # IP addresses or CIDR ranges, for example ["203.0.113.0/24"]. + list: [] + bypass-permissions: [] + # Kicks networks you list by AS number or name, for example a hosting company that VPN services rent from. + # Works with every provider except maxmind, which has no network data. + deny-networks: + enabled: false + # AS numbers, for example [AS64496]. + asns: [] + # Text to look for in the network's provider, organisation, or VPN operator name, ignoring case. + # For example ["Example Hosting"]. At least 3 characters each. + organisations: [] + bypass-permissions: ["origingate.bypass.deny-networks"] + # Kicks IPs that the vpn-from provider flags as a VPN. + vpn: + enabled: true + bypass-permissions: ["origingate.bypass.vpn"] + # Kicks IPs that the vpn-from provider flags as a proxy (only proxycheck.io reports proxies separately). + proxy: + enabled: true + # Proxies from these countries are allowed. Two-letter codes, for example [US, GB]. + allowed-countries: [] + bypass-permissions: ["origingate.bypass.proxy"] + # Kicks IPs on hosting and datacenter networks (rented servers, cloud providers), where VPNs and bots often run + # without being flagged as either. Needs proxycheck or ip-api in vpn-from. IPHub has no separate hosting flag; + # it already counts hosting networks as VPNs. + hosting: + enabled: false + bypass-permissions: ["origingate.bypass.hosting"] + # Kicks players by country. + country: + enabled: false + # allowlist: only these countries get in. denylist: these countries are kicked. + mode: allowlist + # Two-letter country codes, for example [US, CA]. + countries: [] + bypass-permissions: ["origingate.bypass.country"] + +alerts: + # Online staff with any of these permissions see kicks and bypasses in chat, and one message when a lookup + # provider stops answering or the lookup budget is used up, and one when that is over. + permissions: ["origingate.alerts"] + +# Write every login where a rule matched or the lookup failed to daily files in the logs folder. +log-file: true +# Log files older than this many days (0-3650) are deleted. 0 keeps them forever. +log-file-keep-days: 30 diff --git a/core/src/test/resources/upgrade/messages-1.1.1.yml b/core/src/test/resources/upgrade/messages-1.1.1.yml new file mode 100644 index 0000000..6593061 --- /dev/null +++ b/core/src/test/resources/upgrade/messages-1.1.1.yml @@ -0,0 +1,83 @@ +# OriginGate messages in MiniMessage format: https://docs.advntr.dev/minimessage/format.html +# Run "origingate reload" after editing. +# +# Placeholders: +#