From ade61152178b10d07f07d21280bd444d0dd60470 Mon Sep 17 00:00:00 2001 From: rayhandestian Date: Sat, 7 Nov 2026 13:09:16 +0700 Subject: [PATCH 01/32] chore(release): start 1.2.0 --- gradle.properties | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gradle.properties b/gradle.properties index a3af5c6..3fdd8f7 100644 --- a/gradle.properties +++ b/gradle.properties @@ -1,2 +1,2 @@ # The plugin version. The build and the plugin read it from here. -version=1.1.1 +version=1.2.0 From 8e602640d8a844404fecad8fe884962428c11019 Mon Sep 17 00:00:00 2001 From: rayhandestian Date: Sat, 7 Nov 2026 13:09:16 +0700 Subject: [PATCH 02/32] feat(rules): add the allow-networks rule --- CHANGELOG.md | 10 ++++ .../origingate/core/config/ConfigLoader.java | 26 ++++++---- .../origingate/core/config/Messages.java | 10 ++-- .../core/config/OriginGateConfig.java | 12 +++-- .../io/github/origingate/core/rules/Gate.java | 43 +++++++++++---- .../io/github/origingate/core/rules/Rule.java | 4 ++ core/src/main/resources/config.yml | 9 ++++ .../core/config/ConfigLoaderTest.java | 16 +++++- .../origingate/core/rules/GateTest.java | 52 +++++++++++++++++++ docs/configuration.md | 13 ++++- docs/contributing/testing.md | 2 +- docs/how-it-works.md | 2 +- 12 files changed, 168 insertions(+), 31 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 04cefbb..3dc8c78 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,15 @@ # Changelog +## 1.2.0 (unreleased) + +### 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. To use the new features, copy the new settings from the [default config](https://github.com/kaizen-network/OriginGate/blob/main/core/src/main/resources/config.yml). + +### Added + +- `allow-networks` rule: lets in networks you list by AS number or by text in the provider, organisation, or VPN operator name, 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. + ## 1.1.1 (2026-11-07) ### Fixed 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..1fb2cd3 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 @@ -73,10 +73,15 @@ 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)); @@ -237,7 +242,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", "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 +253,8 @@ 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), + 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), @@ -264,12 +270,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", "organisations"); List asns = new ArrayList<>(); for (String value : section.list("asns", MAX_LIST)) { String asn = value.toUpperCase(Locale.ROOT); @@ -287,7 +294,8 @@ private static NetworkRule denyNetworks(YamlSection rules) throws ConfigExceptio 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..23fe548 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 @@ -434,15 +434,17 @@ public Bypass(List permissions, Set players, List public static final class Rules { private final AddressRule denyAddresses; 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, NetworkRule denyNetworks, NetworkRule allowNetworks, BasicRule vpn, ProxyRule proxy, + BasicRule hosting, CountryRule country) { this.denyAddresses = denyAddresses; this.denyNetworks = denyNetworks; + this.allowNetworks = allowNetworks; this.vpn = vpn; this.proxy = proxy; this.hosting = hosting; @@ -451,6 +453,7 @@ public Rules(AddressRule denyAddresses, NetworkRule denyNetworks, BasicRule vpn, public AddressRule denyAddresses() { return denyAddresses; } 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; } @@ -468,13 +471,14 @@ public List> bypassPermissions() { Rules that = (Rules) other; return java.util.Objects.equals(denyAddresses, that.denyAddresses) && 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, denyNetworks, allowNetworks, vpn, proxy, hosting, country); } + @Override public String toString() { return "Rules[" + "denyAddresses=" + denyAddresses + ", " + "denyNetworks=" + denyNetworks + ", " + "allowNetworks=" + allowNetworks + ", " + "vpn=" + vpn + ", " + "proxy=" + proxy + ", " + "hosting=" + hosting + ", " + "country=" + country + "]"; } } public static final class AddressRule { 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..c701257 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 @@ -25,7 +25,8 @@ /** * 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. + * 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. */ @@ -142,7 +143,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 +154,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 +169,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/Rule.java b/core/src/main/java/io/github/origingate/core/rules/Rule.java index fabcc5a..1ff5eb8 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 @@ -4,6 +4,7 @@ public enum Rule { DENY_ADDRESSES("deny-addresses"), DENY_NETWORKS("deny-networks"), + ALLOW_NETWORKS("allow-networks"), VPN("vpn"), PROXY("proxy"), HOSTING("hosting"), @@ -19,4 +20,7 @@ public enum Rule { /** 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; } + + /** 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/resources/config.yml b/core/src/main/resources/config.yml index 006d530..d5cd2df 100644 --- a/core/src/main/resources/config.yml +++ b/core/src/main/resources/config.yml @@ -122,6 +122,15 @@ 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 or name 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. + # Works with every provider except maxmind, which has no network data. + allow-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. At least 3 characters each. + organisations: [] # Kicks IPs that the vpn-from provider flags as a VPN. vpn: enabled: true 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..2c2bfa2 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,20 @@ 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 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()); + Messages.load(directory); + } + @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 +279,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/rules/GateTest.java b/core/src/test/java/io/github/origingate/core/rules/GateTest.java index 0a3f4e8..f38e387 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 @@ -276,6 +276,58 @@ 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", "AS64511", 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 allowNetworksByOrganisationText() throws Exception { + withSchool(); + Gate gate = gate("rules.allow-networks.enabled", true, "rules.allow-networks.organisations", List.of("Example School")); + Decision decision = run(gate, player("Kai", SCHOOL_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/docs/configuration.md b/docs/configuration.md index a654dbf..1283c7e 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -8,7 +8,7 @@ order: 4 `config.yml` is in `plugins/origingate/`. Run `origingate reload` after editing. A file with a mistake is refused, the old settings stay active, and the reply names the setting, for example `lookup.wait-millis must be a whole number from 1000 to 20000`. Unknown settings are refused too, so typos are caught. -Updates keep your file. New settings are not added automatically; compare with the [default config](https://github.com/kaizen-network/OriginGate/blob/main/core/src/main/resources/config.yml) after an update. Settings added in 1.1.0 (`max-lookups-per-minute`, `on-budget-exceeded`, `rules.deny-networks`, and `rules.hosting`) are optional: a config without them works as it did in 1.0.0. +Updates keep your file. New settings are not added automatically; compare with the [default config](https://github.com/kaizen-network/OriginGate/blob/main/core/src/main/resources/config.yml) after an update. Settings added in 1.1.0 (`max-lookups-per-minute`, `on-budget-exceeded`, `rules.deny-networks`, and `rules.hosting`) and 1.2.0 (`rules.allow-networks`) are optional: a config without them works as it did in 1.0.0. ## Settings @@ -43,6 +43,7 @@ Updates keep your file. New settings are not added automatically; compare with t | `bypass.addresses` | `[]` | IPs or CIDR ranges | | `rules.deny-addresses` | off | `list` of IPs or CIDR ranges, `bypass-permissions` | | `rules.deny-networks` | off | `asns` (AS numbers such as `AS64496`), `organisations` (text to look for in the network's provider, organisation, or VPN operator name, ignoring case, at least 3 characters), `bypass-permissions: [origingate.bypass.deny-networks]`. Works with every provider except `maxmind` | +| `rules.allow-networks` | off | `asns` and `organisations`, like `deny-networks`, but no bypass permissions. Lets in a listed network when `vpn`, `proxy`, or `hosting` would kick it; `deny-networks` and `country` still apply. Works with every provider except `maxmind` | | `rules.vpn` | on | `bypass-permissions: [origingate.bypass.vpn]` | | `rules.proxy` | on | `allowed-countries` (codes), `bypass-permissions: [origingate.bypass.proxy]` | | `rules.hosting` | off | `bypass-permissions: [origingate.bypass.hosting]`. Needs `proxycheck` or `ip-api` in `vpn-from`. See [providers](providers.md#hosting-networks) | @@ -101,6 +102,16 @@ rules: bypass-permissions: ["origingate.bypass.hosting"] ``` +To let in a network that a provider wrongly flags, such as a school or a mobile carrier, list it under `allow-networks`. It only skips the `vpn`, `proxy`, and `hosting` rules, and the log shows `rule=allow-networks` when it did. + +```yaml +rules: + allow-networks: + enabled: true + asns: [AS64500] + organisations: ["Example School"] +``` + Hosting and datacenter networks are where VPN services and bots rent their servers, so the hosting rule catches many that no provider flags as a VPN. It also catches players who play through a cloud desktop or a hosted VPN of their own; give them `origingate.bypass.hosting`. Try it with `dry-run: true` first. ### Flood protection diff --git a/docs/contributing/testing.md b/docs/contributing/testing.md index 65700d6..cb9bbd5 100644 --- a/docs/contributing/testing.md +++ b/docs/contributing/testing.md @@ -6,7 +6,7 @@ - Config loading, bounds, unknown keys, paths, country codes, and redaction of passwords and keys - The unchanged 1.0.0 `config.yml` and `messages.yml` (in `core/src/test/resources/upgrade/`) loading and reading the same as the current defaults apart from the new settings -- Rule order and first match, every bypass path (global permission, player name, UUID, address, per-rule permission, several permissions), deny-addresses before lookup, private-address skip, deny-networks by ASN and organisation text before the vpn rule, and the hosting rule +- Rule order and first match, every bypass path (global permission, player name, UUID, address, per-rule permission, several permissions), deny-addresses before lookup, private-address skip, deny-networks by ASN and organisation text before the vpn rule, the hosting rule, and allow-networks skipping only vpn, proxy, and hosting - Country matching by code, including `XK` - Lookup order (memory, storage, provider), one request per IP, expiry, the answer arriving before the save, the 60-second storage pause, the 5-minute pause after a result without country, a refresh never joining a normal lookup, full queue - Lookup failure and timeout in both `on-lookup-failure` modes, dry-run, console log levels diff --git a/docs/how-it-works.md b/docs/how-it-works.md index 117071b..9115430 100644 --- a/docs/how-it-works.md +++ b/docs/how-it-works.md @@ -20,7 +20,7 @@ On Velocity, the check runs after permission plugins such as LuckPerms have load 2. `deny-addresses`, when enabled. 3. Private address skip (`lookup.skip-private-addresses`). 4. Lookup, waiting at most `lookup.wait-millis`. -5. `deny-networks`, `vpn`, `proxy`, `hosting`, `country`, when enabled. +5. `deny-networks`, `allow-networks` (skips `vpn`, `proxy`, and `hosting` for a network on its list), `vpn`, `proxy`, `hosting`, `country`, when enabled. The first rule that matches decides: kick, or let in through that rule's bypass permission. Later rules are not checked. For example, a player with the VPN bypass who uses a VPN from a country outside the allowlist is let in, because the vpn rule matched first. From ec0eaf425d37063c3d2e52000a008cf30fa09304 Mon Sep 17 00:00:00 2001 From: rayhandestian Date: Sat, 7 Nov 2026 13:12:34 +0700 Subject: [PATCH 03/32] fix(rules): match allow-networks by AS number only --- CHANGELOG.md | 2 +- .../origingate/core/config/ConfigLoader.java | 5 +++-- core/src/main/resources/config.yml | 8 +++----- .../origingate/core/config/ConfigLoaderTest.java | 5 +++++ .../io/github/origingate/core/rules/GateTest.java | 15 ++++++++++++--- docs/configuration.md | 5 +++-- 6 files changed, 27 insertions(+), 13 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 3dc8c78..69bb03f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,7 +8,7 @@ Replace the JAR and restart. Your `config.yml` and `messages.yml` keep working u ### Added -- `allow-networks` rule: lets in networks you list by AS number or by text in the provider, organisation, or VPN operator name, 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. +- `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. ## 1.1.1 (2026-11-07) 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 1fb2cd3..17caed2 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 @@ -276,7 +276,7 @@ private static NetworkRule networks(YamlSection rules, String name, boolean hasB 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", "organisations"); + else section.allowOnly("enabled", "asns"); List asns = new ArrayList<>(); for (String value : section.list("asns", MAX_LIST)) { String asn = value.toUpperCase(Locale.ROOT); @@ -287,7 +287,8 @@ private static NetworkRule networks(YamlSection rules, String name, boolean hasB 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); } diff --git a/core/src/main/resources/config.yml b/core/src/main/resources/config.yml index d5cd2df..5c03616 100644 --- a/core/src/main/resources/config.yml +++ b/core/src/main/resources/config.yml @@ -122,15 +122,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 or name 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. - # Works with every provider except maxmind, which has no network data. + # 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: [] - # Text to look for in the network's provider, organisation, or VPN operator name, ignoring case. At least 3 characters each. - organisations: [] # Kicks IPs that the vpn-from provider flags as a VPN. vpn: enabled: true 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 2c2bfa2..7b2c523 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 @@ -115,6 +115,11 @@ private String failure(Object... changes) { .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")); 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 f38e387..cfb591d 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 @@ -280,7 +280,7 @@ private FakeProvider withHosting() { private void withSchool() { provider.answer(new IpInfo(SCHOOL_IP, "Example Net", "Example School District", null, "Example City", "Example Region", - "Canada", "CA", "AS64511", false, true, "Residential", TestSupport.NOW)); + "Canada", "CA", "AS64999", false, true, "Residential", TestSupport.NOW)); } @Test void allowNetworksLetsInFlaggedNetwork() throws Exception { @@ -291,10 +291,19 @@ private void withSchool() { assertEquals("network is on the allow list (AS64500)", decision.note()); } - @Test void allowNetworksByOrganisationText() throws Exception { + @Test void allowNetworksIgnoresNames() throws Exception { withSchool(); - Gate gate = gate("rules.allow-networks.enabled", true, "rules.allow-networks.organisations", List.of("Example School")); + 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()); } diff --git a/docs/configuration.md b/docs/configuration.md index 1283c7e..4b32014 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -43,7 +43,7 @@ Updates keep your file. New settings are not added automatically; compare with t | `bypass.addresses` | `[]` | IPs or CIDR ranges | | `rules.deny-addresses` | off | `list` of IPs or CIDR ranges, `bypass-permissions` | | `rules.deny-networks` | off | `asns` (AS numbers such as `AS64496`), `organisations` (text to look for in the network's provider, organisation, or VPN operator name, ignoring case, at least 3 characters), `bypass-permissions: [origingate.bypass.deny-networks]`. Works with every provider except `maxmind` | -| `rules.allow-networks` | off | `asns` and `organisations`, like `deny-networks`, but no bypass permissions. Lets in a listed network when `vpn`, `proxy`, or `hosting` would kick it; `deny-networks` and `country` still apply. Works with every provider except `maxmind` | +| `rules.allow-networks` | off | `asns` only (AS numbers, no name matching, no bypass permissions). Lets in a listed network when `vpn`, `proxy`, or `hosting` would kick it; `deny-networks` and `country` still apply. Works with every provider except `maxmind` | | `rules.vpn` | on | `bypass-permissions: [origingate.bypass.vpn]` | | `rules.proxy` | on | `allowed-countries` (codes), `bypass-permissions: [origingate.bypass.proxy]` | | `rules.hosting` | off | `bypass-permissions: [origingate.bypass.hosting]`. Needs `proxycheck` or `ip-api` in `vpn-from`. See [providers](providers.md#hosting-networks) | @@ -109,9 +109,10 @@ rules: allow-networks: enabled: true asns: [AS64500] - organisations: ["Example School"] ``` +Use `origingate check ` to see an address's AS number. Names are not matched, because a name match could let in any VPN with that text in its name. + Hosting and datacenter networks are where VPN services and bots rent their servers, so the hosting rule catches many that no provider flags as a VPN. It also catches players who play through a cloud desktop or a hosted VPN of their own; give them `origingate.bypass.hosting`. Try it with `dry-run: true` first. ### Flood protection From a1fd412563cdd25fa72daa7c1e2f55623351b835 Mon Sep 17 00:00:00 2001 From: rayhandestian Date: Sat, 7 Nov 2026 13:18:04 +0700 Subject: [PATCH 04/32] feat(lists): store allow and deny entries with expiry --- CHANGELOG.md | 1 + .../origingate/core/lists/AccessLists.java | 191 ++++++++++++++++++ .../origingate/core/lists/ListEntry.java | 131 ++++++++++++ .../origingate/core/lists/ListTable.java | 48 +++++ .../origingate/core/storage/SqlIpStorage.java | 61 +++++- .../core/lists/AccessListsTest.java | 157 ++++++++++++++ .../origingate/core/lists/ListEntryTest.java | 66 ++++++ .../core/storage/RemoteStorageTest.java | 17 ++ .../core/storage/SqlIpStorageTest.java | 22 ++ docs/contributing/architecture.md | 1 + docs/storage-and-privacy.md | 11 + 11 files changed, 705 insertions(+), 1 deletion(-) create mode 100644 core/src/main/java/io/github/origingate/core/lists/AccessLists.java create mode 100644 core/src/main/java/io/github/origingate/core/lists/ListEntry.java create mode 100644 core/src/main/java/io/github/origingate/core/lists/ListTable.java create mode 100644 core/src/test/java/io/github/origingate/core/lists/AccessListsTest.java create mode 100644 core/src/test/java/io/github/origingate/core/lists/ListEntryTest.java diff --git a/CHANGELOG.md b/CHANGELOG.md index 69bb03f..6f81719 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,7 @@ Replace the JAR and restart. Your `config.yml` and `messages.yml` keep working u ### 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. ## 1.1.1 (2026-11-07) 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..c55ea97 --- /dev/null +++ b/core/src/main/java/io/github/origingate/core/lists/AccessLists.java @@ -0,0 +1,191 @@ +package io.github.origingate.core.lists; + +import io.github.origingate.core.Log; +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.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}, 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) { + AccessLists lists = new AccessLists(table, persistent, clock, executor, log); + lists.readNow(); + return lists; + } + + /** 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); + } + + public CompletableFuture add(ListEntry entry) { + return submit(() -> { + table.put(entry); + readOrThrow(); + return null; + }); + } + + /** Completes with true when an entry was removed. */ + public CompletableFuture remove(ListEntry.Kind kind, String target) { + return submit(() -> { + int removed = table.remove(kind, target); + readOrThrow(); + 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 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 ex) { + readAt = clock.instant(); + if (!failing) log.warn("The allow and deny lists could not be read, so they may be out of date: " + ex.getMessage(), 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 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..3969485 --- /dev/null +++ b/core/src/main/java/io/github/origingate/core/lists/ListEntry.java @@ -0,0 +1,131 @@ +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 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 (with {@code /prefix} only when shorter than the whole address), + * else a UUID, 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('/'); + String host = slash < 0 ? value : value.substring(0, slash); + InetAddress address = Addresses.parse(host).orElse(null); + if (address != null) { + try { + AddressRange.parse(value); + } catch (IllegalArgumentException ex) { + throw invalid(input); + } + String text = Addresses.text(address); + if (slash >= 0) { + int prefix = Integer.parseInt(value.substring(slash + 1)); + if (prefix < address.getAddress().length * 8) text += "/" + prefix; + } + return text; + } + 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/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/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..dce5ca1 --- /dev/null +++ b/core/src/test/java/io/github/origingate/core/lists/AccessListsTest.java @@ -0,0 +1,157 @@ +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()); + } + + @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()); + } +} 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..970f95c --- /dev/null +++ b/core/src/test/java/io/github/origingate/core/lists/ListEntryTest.java @@ -0,0 +1,66 @@ +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")); + 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/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/docs/contributing/architecture.md b/docs/contributing/architecture.md index 872890d..cb85012 100644 --- a/docs/contributing/architecture.md +++ b/docs/contributing/architecture.md @@ -41,3 +41,4 @@ ConsentGate holds `PlayerChooseInitialServerEvent`, which fires after `LoginEven - On reload, logins already in progress finish on the old runtime, which is then closed in the background. - IP parsing is literal-only; no DNS lookups. - Every query uses prepared statements. +- `AccessLists` keeps the allow and deny entries in memory (`ListTable` is the storage side, `SqlIpStorage` the SQL one). `match` never blocks: when the copy is older than 30 seconds it starts one background re-read, and a failed read keeps the old copy and tries again after the next 30 seconds. Adds and removes write, then re-read at once. Memory-only storage uses `ListTable.memory()` and is never re-read. diff --git a/docs/storage-and-privacy.md b/docs/storage-and-privacy.md index 3111a3d..34a891a 100644 --- a/docs/storage-and-privacy.md +++ b/docs/storage-and-privacy.md @@ -22,6 +22,17 @@ OriginGate creates its own table, `origingate_ip_cache`, on start: Saves replace the previous row for the same IP in one step, in both SQLite and MySQL, so several proxies can share one table. Long values are shortened to fit. +The allow and deny lists use a second table, `origingate_list`, in the same database. It is created together with the first one: + +| Column | Type | Notes | +| --- | --- | --- | +| `target` | `VARCHAR(64)` primary key | A lowercase player name, a UUID, an IP address, or a CIDR range. One row per target, so adding it to one list replaces it on the other | +| `kind` | `VARCHAR(5)` | `allow` or `deny` | +| `expires_at` | `BIGINT` | Unix seconds, `NULL` when the entry never expires | +| `note` | `VARCHAR(255)` | `NULL` when there is none | +| `added_by` | `VARCHAR(64)` | Who added the entry | +| `added_at` | `BIGINT` | Unix seconds | + ## SQLite The default. The file is `plugins/origingate/data/origingate.db`. Nothing to set up. SQLite runs on the systems listed under [compatibility](compatibility.md#sqlite); elsewhere, lookups are kept in memory only until you switch to MySQL or MariaDB. The same happens when the file cannot be opened (damaged, locked by another program, or a folder that cannot be written): connections are still checked, an error is logged, and `origingate reload` tries the file again. From 8c51fec293402436c749865e73f978895c4a6742 Mon Sep 17 00:00:00 2001 From: rayhandestian Date: Sat, 7 Nov 2026 13:20:45 +0700 Subject: [PATCH 05/32] fix(lists): handle every storage failure when reading or writing lists --- .../origingate/core/lists/AccessLists.java | 11 +-- .../core/lists/AccessListsTest.java | 68 +++++++++++++++++++ 2 files changed, 74 insertions(+), 5 deletions(-) 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 index c55ea97..cd66dc7 100644 --- a/core/src/main/java/io/github/origingate/core/lists/AccessLists.java +++ b/core/src/main/java/io/github/origingate/core/lists/AccessLists.java @@ -12,6 +12,7 @@ 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; @@ -85,7 +86,7 @@ public Optional match(String username, UUID uuid, InetAddress address public CompletableFuture add(ListEntry entry) { return submit(() -> { table.put(entry); - readOrThrow(); + readNow(); return null; }); } @@ -94,7 +95,7 @@ public CompletableFuture add(ListEntry entry) { public CompletableFuture remove(ListEntry.Kind kind, String target) { return submit(() -> { int removed = table.remove(kind, target); - readOrThrow(); + readNow(); return removed > 0; }); } @@ -144,12 +145,12 @@ private void refreshIfStale() { } } - /** Reads the table. A failure is logged once until a read works again, and the next try waits for the next refresh. */ + /** 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 ex) { + } 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: " + ex.getMessage(), null); failing = true; @@ -177,7 +178,7 @@ private CompletableFuture submit(SqlTask task) { executor.execute(() -> { try { future.complete(task.run()); - } catch (SQLException | RuntimeException ex) { + } catch (SQLException | RuntimeException | ServiceConfigurationError | LinkageError ex) { future.completeExceptionally(ex); } }); 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 index dce5ca1..0e755d7 100644 --- a/core/src/test/java/io/github/origingate/core/lists/AccessListsTest.java +++ b/core/src/test/java/io/github/origingate/core/lists/AccessListsTest.java @@ -135,6 +135,74 @@ private static AccessLists load(ListTable table, TestSupport.MutableClock clock) 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(); From 6c9c7ab5d0d10f9e82c62abb58d1b46e9b0c0e4e Mon Sep 17 00:00:00 2001 From: rayhandestian Date: Sat, 7 Nov 2026 13:25:16 +0700 Subject: [PATCH 06/32] feat(rules): check the allow and deny lists before any lookup --- CHANGELOG.md | 1 + .../origingate/core/OriginGateRuntime.java | 32 ++++++--- .../origingate/core/RuntimeController.java | 5 +- .../io/github/origingate/core/rules/Gate.java | 21 +++++- .../io/github/origingate/core/rules/Rule.java | 3 +- core/src/main/resources/messages.yml | 7 ++ .../origingate/core/RuntimeCommandsTest.java | 27 +++++++- .../core/config/ConfigLoaderTest.java | 3 +- .../origingate/core/rules/GateTest.java | 69 +++++++++++++++++++ docs/how-it-works.md | 12 ++-- docs/messages.md | 6 +- 11 files changed, 162 insertions(+), 24 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 6f81719..432566f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,7 @@ Replace the JAR and restart. Your `config.yml` and `messages.yml` keep working u - `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. ## 1.1.1 (2026-11-07) 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..e294075 100644 --- a/core/src/main/java/io/github/origingate/core/OriginGateRuntime.java +++ b/core/src/main/java/io/github/origingate/core/OriginGateRuntime.java @@ -4,6 +4,9 @@ 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; @@ -47,6 +50,7 @@ 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; private final Clock clock; private final LookupStats stats; @@ -59,7 +63,7 @@ public final class OriginGateRuntime implements AutoCloseable { 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, Clock clock, LookupStats stats, AtomicBoolean current, String storageName, String storageProblem) { this.config = config; @@ -69,6 +73,7 @@ private OriginGateRuntime(OriginGateConfig config, Messages messages, IpStorage this.providers = providers; this.workers = workers; this.gate = gate; + this.lists = lists; this.decisionFile = decisionFile; this.clock = clock; this.stats = stats; @@ -153,9 +158,11 @@ 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; + AccessLists lists = AccessLists.load(persistent ? (ListTable) storage : ListTable.memory(), persistent, clock, workers, log); 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); + return new OriginGateRuntime(config, messages, storage, http, providers, workers, + new Gate(config, lookups, log, namesUnverified, lists), lists, decisionFile, clock, stats, current, storageName, storageProblem); } private static java.util.concurrent.ThreadFactory threads() { @@ -170,33 +177,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 +237,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 +254,7 @@ 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("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) 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..127719d 100644 --- a/core/src/main/java/io/github/origingate/core/RuntimeController.java +++ b/core/src/main/java/io/github/origingate/core/RuntimeController.java @@ -112,8 +112,9 @@ public void cleanup() { if (active == null) return; try { OriginGateRuntime.Cleanup cleanup = active.deleteExpired(); - if (cleanup.rows() > 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); 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 c701257..606e0ca 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,7 +26,7 @@ import java.util.concurrent.TimeoutException; /** - * Decides whether a connection may join. Order: global bypass, deny-addresses, private-address skip, + * Decides whether a connection may join. Order: global bypass, allow list, deny list, deny-addresses, private-address skip, * 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. */ @@ -37,6 +39,7 @@ public final class Gate { private final Log log; private final Set permissionNames; private final String bypassCaution; + private final AccessLists lists; public Gate(OriginGateConfig config, LookupService lookups, Log log) { this(config, lookups, log, false); @@ -44,6 +47,11 @@ 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.lists = lists; this.config = config; this.lookups = lookups; this.log = log; @@ -113,6 +121,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")); 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 1ff5eb8..fa2065a 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,6 +2,7 @@ /** Rules in the order they are checked, plus the lookup-failure outcome. */ public enum Rule { + DENY_LIST("deny-list"), DENY_ADDRESSES("deny-addresses"), DENY_NETWORKS("deny-networks"), ALLOW_NETWORKS("allow-networks"), @@ -19,7 +20,7 @@ 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 == 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/resources/messages.yml b/core/src/main/resources/messages.yml index 6593061..8999718 100644 --- a/core/src/main/resources/messages.yml +++ b/core/src/main/resources/messages.yml @@ -13,6 +13,13 @@ 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: vpn: |- 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..2c1135f 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; @@ -227,9 +228,31 @@ 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 commandsExplainWhenNotRunning() throws Exception { 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 7b2c523..fddb00f 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 @@ -125,7 +125,8 @@ private String failure(Object... changes) { TestSupport.copyResource("/upgrade/messages-1.0.0.yml", directory.resolve("messages.yml")); OriginGateConfig legacy = ConfigLoader.load(directory); assertFalse(legacy.rules().allowNetworks().enabled()); - Messages.load(directory); + Messages messages = Messages.load(directory); + assertTrue(messages.kick(io.github.origingate.core.rules.Rule.DENY_LIST).startsWith("You are not allowed on this server.")); } @Test void olderConfigWithoutProviderSettingsUsesProxycheck() throws Exception { 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 cfb591d..803cd40 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,71 @@ 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 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()); + } + private static Decision run(Gate gate, LoginAttempt attempt) throws Exception { return gate.check(attempt).get(15, TimeUnit.SECONDS); } diff --git a/docs/how-it-works.md b/docs/how-it-works.md index 9115430..40a568d 100644 --- a/docs/how-it-works.md +++ b/docs/how-it-works.md @@ -17,14 +17,16 @@ On Velocity, the check runs after permission plugins such as LuckPerms have load ## Order of checks 1. Global bypass: `bypass.players` (name or UUID), `bypass.addresses`, `bypass.permissions`. -2. `deny-addresses`, when enabled. -3. Private address skip (`lookup.skip-private-addresses`). -4. Lookup, waiting at most `lookup.wait-millis`. -5. `deny-networks`, `allow-networks` (skips `vpn`, `proxy`, and `hosting` for a network on its list), `vpn`, `proxy`, `hosting`, `country`, when enabled. +2. Allow list entry (`origingate allow`): lets the player in with no lookup. A name entry gets the same offline-mode caution as `bypass.players`. +3. Deny list entry (`origingate deny`): the `deny-list` rule. No bypass permission applies. +4. `deny-addresses`, when enabled. +5. Private address skip (`lookup.skip-private-addresses`). +6. Lookup, waiting at most `lookup.wait-millis`. +7. `deny-networks`, `allow-networks` (skips `vpn`, `proxy`, and `hosting` for a network on its list), `vpn`, `proxy`, `hosting`, `country`, when enabled. The first rule that matches decides: kick, or let in through that rule's bypass permission. Later rules are not checked. For example, a player with the VPN bypass who uses a VPN from a country outside the allowlist is let in, because the vpn rule matched first. -A `bypass.addresses` entry wins over a `deny-addresses` entry. +A `bypass.addresses` entry wins over a `deny-addresses` entry, and over the lists. Within the lists, an entry for the player's name or UUID comes before an entry for their address. When two address entries match, the allow entry wins. Expired entries are ignored at once and deleted by the hourly cleanup. Logins read the lists from memory only, so they never wait on the database. ## Lookups diff --git a/docs/messages.md b/docs/messages.md index 7cb7804..b062cd2 100644 --- a/docs/messages.md +++ b/docs/messages.md @@ -12,20 +12,20 @@ Bukkit/Spigot/Paper and BungeeCord receive messages as legacy text, so hover and | Key | When | | --- | --- | -| `kick.deny-addresses`, `kick.deny-networks`, `kick.vpn`, `kick.proxy`, `kick.hosting`, `kick.country` | Kick screen for that rule | +| `kick.deny-list`, `kick.deny-addresses`, `kick.deny-networks`, `kick.vpn`, `kick.proxy`, `kick.hosting`, `kick.country` | Kick screen for that rule | | `kick.lookup-failure` | Kick screen when `on-lookup-failure: deny`, or `on-budget-exceeded: deny` for a login over the lookup budget | | `bypass-notice` | Chat message after joining the first server through a rule bypass. Empty turns it off | | `alerts.denied`, `alerts.bypassed` | Chat alert to staff. Empty turns it off | | `alerts.lookup-problem`, `alerts.lookup-recovered` | Chat alert to staff when lookups start failing and when they work again. The text is in ``; the other placeholders do not apply. Empty turns it off | -Messages added in 1.1.0 (`kick.deny-networks`, `kick.hosting`, `alerts.lookup-problem`, and `alerts.lookup-recovered`) may be missing from an older `messages.yml`. Then the bundled text is used. +Messages added in 1.1.0 (`kick.deny-networks`, `kick.hosting`, `alerts.lookup-problem`, and `alerts.lookup-recovered`) and 1.2.0 (`kick.deny-list`) may be missing from an older `messages.yml`. Then the bundled text is used. ## Placeholders | Placeholder | Value | | --- | --- | | ``, ``, `` | The connecting player | -| `` | `deny-addresses`, `deny-networks`, `vpn`, `proxy`, `hosting`, `country`, or `lookup-failure` | +| `` | `deny-list`, `deny-addresses`, `deny-networks`, `vpn`, `proxy`, `hosting`, `country`, or `lookup-failure` | | `