Runway 1.0.0
This commit is contained in:
commit
dcf819146b
1372 files changed
+188168
No files matched your search
+96
@@ -0,0 +1,96 @@
|
||||
package mx.quest.protection;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Path;
|
||||
import java.util.Arrays;
|
||||
import mx.quest.runway.crypto.SecretCipher;
|
||||
import mx.quest.runway.storage.StorageLayout;
|
||||
import mx.quest.runway.storage.StorageProperties;
|
||||
import mx.quest.runway.storage.YamlStore;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
|
||||
/**
|
||||
* The read-model the app login-protection PANEL ({@code templates/admin-app.html}) binds to. It must surface the
|
||||
* live app-scope settings for pre-fill, and — the security-critical contract — expose the captcha secret ONLY as a
|
||||
* boolean "configured?" flag, never the value, so the panel has no binding through which the secret could reach the
|
||||
* page.
|
||||
*/
|
||||
class AppProtectionPanelTest {
|
||||
|
||||
private static AppProtectionPanel panel(Path root, ProtectionSettings settings) throws IOException {
|
||||
StorageProperties props = new StorageProperties();
|
||||
props.setExternal(root);
|
||||
ProtectionConfigStore store = new ProtectionConfigStore(
|
||||
new ProtectionProperties(), StorageLayout.from(props), new YamlStore(), passthrough());
|
||||
store.saveApp(settings);
|
||||
return new AppProtectionPanel(store);
|
||||
}
|
||||
|
||||
@Test
|
||||
void itSurfacesTheLiveSettingsForThePanel(@TempDir Path root) throws IOException {
|
||||
AppProtectionPanel panel = panel(root, new ProtectionSettings(true, 7, 250, 800,
|
||||
new ProtectionSettings.Captcha(true, "recaptcha-v3", "public-site-key", "", 0.4)));
|
||||
|
||||
assertTrue(panel.honeypotEnabled());
|
||||
assertEquals(7, panel.maxAttempts());
|
||||
assertEquals(250, panel.windowSeconds());
|
||||
assertEquals(800, panel.lockoutSeconds());
|
||||
assertTrue(panel.captchaEnabled());
|
||||
assertEquals("recaptcha-v3", panel.provider());
|
||||
assertEquals("public-site-key", panel.siteKey());
|
||||
assertEquals(0.4, panel.scoreThreshold());
|
||||
assertTrue(panel.providers().contains("recaptcha-v2"), "the provider list is offered to the select");
|
||||
assertTrue(panel.secretStorable(), "a cipher is available");
|
||||
assertFalse(panel.secretConfigured(), "no secret set yet");
|
||||
}
|
||||
|
||||
@Test
|
||||
void itExposesTheCaptchaSecretOnlyAsABoolean(@TempDir Path root) throws IOException {
|
||||
AppProtectionPanel panel = panel(root, new ProtectionSettings(true, 5, 300, 900,
|
||||
new ProtectionSettings.Captcha(true, "recaptcha-v2", "public-site-key", "TOP-SECRET-VALUE", 0.5)));
|
||||
|
||||
assertTrue(panel.secretConfigured(), "a stored secret is reported as a boolean");
|
||||
assertEquals("public-site-key", panel.siteKey(), "the PUBLIC site key is surfaced (it is not secret)");
|
||||
// Structural masking guard: NO zero-arg String getter on the panel returns the secret value, so the fragment
|
||||
// has nothing to bind it to. Guards against a future regression that adds such an accessor.
|
||||
boolean leaks = Arrays.stream(AppProtectionPanel.class.getMethods())
|
||||
.filter(m -> m.getParameterCount() == 0 && m.getReturnType() == String.class)
|
||||
.anyMatch(m -> {
|
||||
try {
|
||||
return "TOP-SECRET-VALUE".equals(m.invoke(panel));
|
||||
} catch (ReflectiveOperationException e) {
|
||||
return false;
|
||||
}
|
||||
});
|
||||
assertFalse(leaks, "no accessor on the panel returns the captcha secret value");
|
||||
}
|
||||
|
||||
private static SecretCipher passthrough() {
|
||||
return new SecretCipher() {
|
||||
@Override
|
||||
public boolean isAvailable() {
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String encrypt(String plaintext) {
|
||||
return plaintext;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String decrypt(String value) {
|
||||
return value;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isEncrypted(String value) {
|
||||
return false;
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
+187
@@ -0,0 +1,187 @@
|
||||
package mx.quest.protection;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.boot.context.properties.bind.Binder;
|
||||
import org.springframework.boot.context.properties.source.MapConfigurationPropertySource;
|
||||
|
||||
/**
|
||||
* The auto-block thresholds are declared in {@code plugin.yml} <b>and</b> actually bind.
|
||||
*
|
||||
* <h2>Why both halves matter</h2>
|
||||
* Found on a live deployment: the four auto-escalation values existed and bound, but were <b>not declared</b> in the
|
||||
* plugin's settings schema. That is a worse state than simply missing, because it fails <i>later</i> and
|
||||
* <i>quietly</i> — an operator could hand-edit {@code block-seconds} into
|
||||
* {@code external/plugin-settings/protection.yml} and a restart would honour it, but the settings form writes
|
||||
* the <i>complete declared key set</i> on save, so the next unrelated save of that page silently dropped the
|
||||
* key and the block duration reverted to 900 s with no error and no log line.
|
||||
*
|
||||
* <p>So declaring the keys is only half the fix. A declared key whose path does not match the bound property is
|
||||
* equally silent: the form would accept a value, write it, and nothing would read it. This test pins the
|
||||
* <b>path</b> by binding a value and reading it back through {@link ProtectionProperties}.
|
||||
*
|
||||
* <p>It also pins the declared defaults against the Java defaults, so the form can never advertise one number
|
||||
* while the running system uses another.
|
||||
*/
|
||||
class AutoBlockSettingsSchemaTest {
|
||||
|
||||
private static final String PREFIX = "runway.plugin.protection";
|
||||
|
||||
private static String descriptor() throws IOException {
|
||||
return Files.readString(Path.of("plugin.yml"));
|
||||
}
|
||||
|
||||
private static ProtectionProperties bind(Map<String, Object> properties) {
|
||||
return new Binder(new MapConfigurationPropertySource(properties))
|
||||
.bind(PREFIX, ProtectionProperties.class)
|
||||
.orElseGet(ProtectionProperties::new);
|
||||
}
|
||||
|
||||
/**
|
||||
* The operator-visible question this whole change exists to answer: "how long am I blocked for, and can I
|
||||
* change it?" A declared key that does not reach the running value would leave that answer wrong while
|
||||
* looking right in the console.
|
||||
*/
|
||||
@Test
|
||||
void theDeclaredAutoBlockKeysBindToTheRunningValues() {
|
||||
ProtectionProperties bound = bind(Map.of(
|
||||
PREFIX + ".rate-limit.auto-block.enabled", "false",
|
||||
PREFIX + ".rate-limit.auto-block.breach-threshold", "17",
|
||||
PREFIX + ".rate-limit.auto-block.window-seconds", "23",
|
||||
PREFIX + ".rate-limit.auto-block.block-seconds", "42"));
|
||||
|
||||
ProtectionProperties.AutoBlock autoBlock = bound.getRateLimit().getAutoBlock();
|
||||
assertEquals(false, autoBlock.isEnabled(), "the enable switch must reach the limiter");
|
||||
assertEquals(17, autoBlock.getBreachThreshold());
|
||||
assertEquals(23L, autoBlock.getWindowSeconds());
|
||||
assertEquals(42L, autoBlock.getBlockSeconds(), "the DURATION is the value an operator most needs to set");
|
||||
}
|
||||
|
||||
/** Every key the form offers must exist in the descriptor, or it is never rendered at all. */
|
||||
@Test
|
||||
void allFourAutoBlockKeysAreDeclaredInTheDescriptor() throws IOException {
|
||||
String yml = descriptor();
|
||||
for (String key : new String[] {
|
||||
"rate-limit.auto-block.enabled",
|
||||
"rate-limit.auto-block.breach-threshold",
|
||||
"rate-limit.auto-block.window-seconds",
|
||||
"rate-limit.auto-block.block-seconds"}) {
|
||||
assertTrue(declaresKey(yml, key), "settings schema must declare: " + key);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The declared defaults must equal the Java defaults. If they drift, the console shows one number while the
|
||||
* running system uses another — and because the form writes the complete key set on save, merely opening
|
||||
* and saving the page would silently change behaviour to whatever the descriptor claimed.
|
||||
*/
|
||||
@Test
|
||||
void theDeclaredDefaultsMatchTheRunningDefaults() throws IOException {
|
||||
String yml = descriptor();
|
||||
ProtectionProperties.AutoBlock defaults = new ProtectionProperties().getRateLimit().getAutoBlock();
|
||||
|
||||
assertEquals(true, defaults.isEnabled());
|
||||
assertTrue(yml.contains("key: rate-limit.auto-block.enabled, type: boolean, default: true"),
|
||||
"descriptor default must match the Java default (true)");
|
||||
assertEquals(60, defaults.getBreachThreshold());
|
||||
assertTrue(yml.contains("default: 60, range: \"1..100000\""), "threshold default must match (60)");
|
||||
assertEquals(60L, defaults.getWindowSeconds());
|
||||
assertEquals(900L, defaults.getBlockSeconds());
|
||||
assertTrue(yml.contains("default: 900, range: \"1..604800\""), "duration default must match (900)");
|
||||
}
|
||||
|
||||
// ---- the exemption list ----------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* The allowlist is declared AND binds — the same two halves, on the key whose whole job is preventing a
|
||||
* self-lockout.
|
||||
*
|
||||
* <p>This one was missed when the auto-block keys above were fixed, and the omission was found the hard
|
||||
* way: a same-host SEO audit locked the admin IP out for 15 minutes and returned
|
||||
* 13 FAIL / 25 WARN, every one a {@code 429} rather than a defect, from a clean deployment — close to a
|
||||
* false regression report against the release.
|
||||
*
|
||||
* <p>It had always bound and reached {@code RateLimitEdgeGuard} — it was simply undeclared, which is the
|
||||
* worse state for exactly the reason this class was created: the settings form writes the complete
|
||||
* declared key set on save, so an operator who found the key in the source and set it would have lost it
|
||||
* on the next unrelated save of that page, and been locked out again with nothing to point at.
|
||||
*/
|
||||
@Test
|
||||
void theAllowlistIsDeclaredAndBinds() throws IOException {
|
||||
assertTrue(declaresKey(descriptor(), "allowlist"),
|
||||
"an undeclared exemption key is silently wiped by the next save of the settings form");
|
||||
|
||||
ProtectionProperties bound = bind(Map.of(
|
||||
PREFIX + ".allowlist[0]", "203.0.113.0/24",
|
||||
PREFIX + ".allowlist[1]", "198.51.100.7"));
|
||||
|
||||
assertEquals(List.of("203.0.113.0/24", "198.51.100.7"), bound.getAllowlist(),
|
||||
"the declared key must reach the value the guard actually consults");
|
||||
}
|
||||
|
||||
/** Absent means empty, not null — an empty list is "exempt nobody", never a startup failure. */
|
||||
@Test
|
||||
void anAbsentAllowlistIsEmptyRatherThanNull() {
|
||||
assertEquals(List.of(), new ProtectionProperties().getAllowlist());
|
||||
assertEquals(List.of(), bind(Map.of()).getAllowlist());
|
||||
}
|
||||
|
||||
/**
|
||||
* The declared list actually exempts, end to end through the guard.
|
||||
*
|
||||
* <p>Asserted against the verdict rather than the property, because a value that binds and is never
|
||||
* consulted looks identical in configuration to one that works.
|
||||
*/
|
||||
@Test
|
||||
void anAllowlistedAddressIsNeitherThrottledNorBlocked() {
|
||||
mx.quest.runway.web.CidrSet allow =
|
||||
mx.quest.runway.web.CidrSet.of(List.of("203.0.113.0/24"));
|
||||
java.nio.file.Path tmp;
|
||||
try {
|
||||
tmp = java.nio.file.Files.createTempDirectory("allowlist-test");
|
||||
} catch (IOException e) {
|
||||
throw new java.io.UncheckedIOException(e);
|
||||
}
|
||||
IpBlocklist blocklist = new IpBlocklist(tmp.resolve("b.yml"), new mx.quest.runway.storage.YamlStore(),
|
||||
allow, () -> 1_000L);
|
||||
// Even a bucket of one token, already spent, must not touch an allowlisted caller.
|
||||
RateLimitEdgeGuard guard =
|
||||
new RateLimitEdgeGuard(allow, blocklist, new TokenBucketRateLimiter(1, 0.0, 10, () -> 0L));
|
||||
|
||||
for (int i = 0; i < 50; i++) {
|
||||
assertTrue(guard.check(new mx.quest.runway.protect.EdgeRequest("203.0.113.9", "GET", "/")).allowed(),
|
||||
"an allowlisted address must never be throttled, however many requests it makes");
|
||||
}
|
||||
assertFalse(blocklist.isBlocked("203.0.113.9"), "…and must never be auto-blocked either");
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether the descriptor <b>declares</b> {@code key} — as an actual schema entry, not as a mention.
|
||||
*
|
||||
* <p>Written because the obvious {@code yml.contains("key: allowlist")} is <b>vacuous</b>: commenting the
|
||||
* declaration out leaves {@code # - { key: allowlist, …}} in the file, the substring still matches, and
|
||||
* the test passes while the key is undeclared. Proven by doing exactly that — the assertion did not
|
||||
* notice. This descriptor is heavily commented (the comments explain each key and therefore NAME it), so
|
||||
* substring matching here was always going to confirm the prose rather than the schema.
|
||||
*/
|
||||
private static boolean declaresKey(String yml, String key) {
|
||||
for (String line : yml.split("\n")) {
|
||||
String t = line.trim();
|
||||
if (t.startsWith("#")) {
|
||||
continue; // prose that names a key is not a declaration
|
||||
}
|
||||
if (t.startsWith("- {") && t.replace(" ", "").contains("key:" + key.replace(" ", "") + ",")) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
+140
@@ -0,0 +1,140 @@
|
||||
package mx.quest.protection;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
|
||||
import java.nio.file.Path;
|
||||
import mx.quest.runway.crypto.SecretCipher;
|
||||
import mx.quest.runway.security.LoginAttemptGate;
|
||||
import mx.quest.runway.security.LoginProtectionFilter;
|
||||
import mx.quest.runway.security.ProtectionScope;
|
||||
import mx.quest.runway.storage.StorageLayout;
|
||||
import mx.quest.runway.storage.StorageProperties;
|
||||
import mx.quest.runway.storage.YamlStore;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
import org.springframework.mock.web.MockFilterChain;
|
||||
import org.springframework.mock.web.MockHttpServletRequest;
|
||||
import org.springframework.mock.web.MockHttpServletResponse;
|
||||
|
||||
/**
|
||||
* End-to-end at the filter band: the kernel's {@link LoginProtectionFilter} wired with the plugin's real
|
||||
* {@link LoginFormPolicyGuard} (captcha verification stubbed). An active-captcha login POST with no/invalid token
|
||||
* is redirected to {@code /app/login?captcha} <b>and records a failed attempt</b> (so it counts toward the IP
|
||||
* lockout); a valid token passes through to the chain. Proves the wiring the operator actually gets — the guard's
|
||||
* captcha rejection surfaces through the filter's redirect + failure count.
|
||||
*/
|
||||
class CaptchaLoginProtectionFilterTest {
|
||||
|
||||
private static SecretCipher passthroughCipher() {
|
||||
return new SecretCipher() {
|
||||
@Override public boolean isAvailable() { return true; }
|
||||
@Override public String encrypt(String plaintext) { return "ENC(" + plaintext + ")"; }
|
||||
@Override public String decrypt(String value) { return value; }
|
||||
@Override public boolean isEncrypted(String value) { return value != null && value.startsWith("ENC("); }
|
||||
};
|
||||
}
|
||||
|
||||
/** Trusted-device service with the feature OFF, so the guard's captcha path runs unchanged (no cookie here). */
|
||||
private static TrustedDeviceService td() {
|
||||
ProtectionProperties props = new ProtectionProperties();
|
||||
props.getRememberDevice().setEnabled(false);
|
||||
return new TrustedDeviceService(props, null, passthroughCipher());
|
||||
}
|
||||
|
||||
private static StorageLayout layout(Path root) {
|
||||
StorageProperties props = new StorageProperties();
|
||||
props.setExternal(root.resolve("external"));
|
||||
props.setSites(root.resolve("external").resolve("sites"));
|
||||
return StorageLayout.from(props);
|
||||
}
|
||||
|
||||
/** An app-scope store with captcha enabled (both keys present → active) and honeypot off (isolate captcha). */
|
||||
private static ProtectionConfigStore activeCaptchaStore(Path root) {
|
||||
ProtectionProperties props = new ProtectionProperties();
|
||||
props.getLogin().setHoneypotEnabled(false);
|
||||
ProtectionProperties.Captcha c = props.getLogin().getCaptcha();
|
||||
c.setEnabled(true);
|
||||
c.setProvider("recaptcha-v2");
|
||||
c.setSiteKey("PUBLIC");
|
||||
c.setSecretKey("SECRET");
|
||||
return new ProtectionConfigStore(props, layout(root), new YamlStore(), passthroughCipher());
|
||||
}
|
||||
|
||||
/** A gate that never locks and counts recorded failures into {@code failures[0]}. */
|
||||
private static LoginAttemptGate countingGate(int[] failures) {
|
||||
return new LoginAttemptGate() {
|
||||
@Override public boolean isLocked(String clientIp) { return false; }
|
||||
@Override public void recordFailure(String clientIp) { failures[0]++; }
|
||||
@Override public void recordSuccess(String clientIp) { }
|
||||
};
|
||||
}
|
||||
|
||||
private static CaptchaVerifier stubVerifier(boolean result) {
|
||||
return new CaptchaVerifier((url, body) -> { throw new AssertionError("no real exchange"); }) {
|
||||
@Override public boolean verify(ProtectionSettings.Captcha config, String token, String remoteIp) {
|
||||
return result;
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
private static MockHttpServletRequest loginPost() {
|
||||
MockHttpServletRequest request = new MockHttpServletRequest("POST", "/app/login");
|
||||
request.setRequestURI("/app/login");
|
||||
request.setRemoteAddr("203.0.113.11");
|
||||
return request;
|
||||
}
|
||||
|
||||
@Test
|
||||
void anActiveCaptchaLoginWithNoTokenIsRejectedAndCounted(@TempDir Path root) throws Exception {
|
||||
int[] failures = {0};
|
||||
LoginFormPolicyGuard guard = new LoginFormPolicyGuard(activeCaptchaStore(root), stubVerifier(false), td());
|
||||
LoginProtectionFilter filter = new LoginProtectionFilter(
|
||||
"/app/login", countingGate(failures), guard, ProtectionScope.Realm.APPLICATION, null);
|
||||
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
MockFilterChain chain = new MockFilterChain();
|
||||
filter.doFilter(loginPost(), response, chain); // no captcha token param present
|
||||
|
||||
assertNull(chain.getRequest(), "auth must NOT be reached when the captcha check rejects");
|
||||
assertEquals("/app/login?captcha", response.getRedirectedUrl(), "captcha rejection uses the ?captcha flag");
|
||||
assertEquals(1, failures[0], "a captcha rejection records a failure so it counts toward the IP lockout");
|
||||
}
|
||||
|
||||
@Test
|
||||
void anActiveCaptchaLoginWithAnInvalidTokenIsRejectedAndCounted(@TempDir Path root) throws Exception {
|
||||
int[] failures = {0};
|
||||
LoginFormPolicyGuard guard = new LoginFormPolicyGuard(activeCaptchaStore(root), stubVerifier(false), td());
|
||||
LoginProtectionFilter filter = new LoginProtectionFilter(
|
||||
"/app/login", countingGate(failures), guard, ProtectionScope.Realm.APPLICATION, null);
|
||||
|
||||
MockHttpServletRequest request = loginPost();
|
||||
request.addParameter("g-recaptcha-response", "bad-token");
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
MockFilterChain chain = new MockFilterChain();
|
||||
filter.doFilter(request, response, chain);
|
||||
|
||||
assertNull(chain.getRequest(), "an invalid captcha token is rejected before auth");
|
||||
assertEquals("/app/login?captcha", response.getRedirectedUrl());
|
||||
assertEquals(1, failures[0]);
|
||||
}
|
||||
|
||||
@Test
|
||||
void anActiveCaptchaLoginWithAValidTokenReachesTheChain(@TempDir Path root) throws Exception {
|
||||
int[] failures = {0};
|
||||
LoginFormPolicyGuard guard = new LoginFormPolicyGuard(activeCaptchaStore(root), stubVerifier(true), td());
|
||||
LoginProtectionFilter filter = new LoginProtectionFilter(
|
||||
"/app/login", countingGate(failures), guard, ProtectionScope.Realm.APPLICATION, null);
|
||||
|
||||
MockHttpServletRequest request = loginPost();
|
||||
request.addParameter("g-recaptcha-response", "good-token");
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
MockFilterChain chain = new MockFilterChain();
|
||||
filter.doFilter(request, response, chain);
|
||||
|
||||
assertNotNull(chain.getRequest(), "a verifier-approved token lets the login proceed to auth");
|
||||
assertNull(response.getRedirectedUrl());
|
||||
assertEquals(0, failures[0], "a passing captcha records no failure");
|
||||
}
|
||||
}
|
||||
+290
@@ -0,0 +1,290 @@
|
||||
package mx.quest.protection;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
import jakarta.servlet.http.Cookie;
|
||||
import java.nio.file.Path;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import mx.quest.runway.crypto.AesGcmSecretCipher;
|
||||
import mx.quest.runway.crypto.SecretCipher;
|
||||
import mx.quest.runway.platform.PlatformSettingsStore;
|
||||
import mx.quest.runway.security.ProtectionScope;
|
||||
import mx.quest.runway.security.RunwaySecurityProperties;
|
||||
import mx.quest.runway.site.Site;
|
||||
import mx.quest.runway.site.SiteResolver;
|
||||
import mx.quest.runway.site.SiteStatus;
|
||||
import mx.quest.runway.site.SiteStore;
|
||||
import mx.quest.runway.storage.StorageLayout;
|
||||
import mx.quest.runway.storage.StorageProperties;
|
||||
import mx.quest.runway.storage.YamlStore;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
import org.springframework.mock.web.MockHttpServletRequest;
|
||||
import org.springframework.mock.web.MockHttpServletResponse;
|
||||
import org.springframework.web.servlet.ModelAndView;
|
||||
|
||||
/**
|
||||
* The login-view contributor sets the generic captcha model flags (the PUBLIC site key + provider flags + script
|
||||
* url) when a scope's captcha is active, and only {@code captchaActive=false} when it is not. It must never leak
|
||||
* the captcha secret into the model.
|
||||
*/
|
||||
class CaptchaLoginViewContributorTest {
|
||||
|
||||
private static SecretCipher passthroughCipher() {
|
||||
return new SecretCipher() {
|
||||
@Override public boolean isAvailable() { return true; }
|
||||
@Override public String encrypt(String plaintext) { return "ENC(" + plaintext + ")"; }
|
||||
@Override public String decrypt(String value) { return value; }
|
||||
@Override public boolean isEncrypted(String value) { return value != null && value.startsWith("ENC("); }
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Trusted-device service with the feature OFF, so {@code isTrusted} is false and {@code rememberDeviceOffered}
|
||||
* false — the captcha slot flags render exactly as before. (The trust-based skip is covered by
|
||||
* {@link TrustedDeviceServiceTest}; the contributor's offer/skip wiring by dedicated cases below.)
|
||||
*/
|
||||
private static TrustedDeviceService td() {
|
||||
ProtectionProperties props = new ProtectionProperties();
|
||||
props.getRememberDevice().setEnabled(false);
|
||||
return new TrustedDeviceService(props, null, passthroughCipher());
|
||||
}
|
||||
|
||||
private static StorageLayout layout(Path root) {
|
||||
StorageProperties props = new StorageProperties();
|
||||
props.setExternal(root.resolve("external"));
|
||||
props.setSites(root.resolve("external").resolve("sites"));
|
||||
return StorageLayout.from(props);
|
||||
}
|
||||
|
||||
private static ProtectionConfigStore appStore(Path root, ProtectionProperties.Captcha appCaptcha) {
|
||||
ProtectionProperties props = new ProtectionProperties();
|
||||
if (appCaptcha != null) {
|
||||
props.getLogin().setCaptcha(appCaptcha);
|
||||
}
|
||||
return new ProtectionConfigStore(props, layout(root), new YamlStore(), passthroughCipher());
|
||||
}
|
||||
|
||||
/**
|
||||
* A real {@link SiteResolver} over the temp external tree. No site is bound by default, so
|
||||
* {@link SiteResolver#current()} is empty (app-realm behaviour); a test that needs a bound site calls
|
||||
* {@link SiteResolver#bind(Site)} on it. Real stores are cheap here (no site files exist, so lookups are empty).
|
||||
*/
|
||||
private static SiteResolver resolver(Path root) {
|
||||
StorageLayout layout = layout(root);
|
||||
YamlStore yaml = new YamlStore();
|
||||
return new SiteResolver(new SiteStore(layout, yaml), new PlatformSettingsStore(layout, yaml));
|
||||
}
|
||||
|
||||
private static Site site(String id) {
|
||||
return new Site(id, id + " Ltd", List.of(id + ".example"), Locale.ENGLISH, List.of(),
|
||||
"https://" + id + ".example", SiteStatus.ACTIVE);
|
||||
}
|
||||
|
||||
private static MockHttpServletRequest get(String uri) {
|
||||
MockHttpServletRequest request = new MockHttpServletRequest("GET", uri);
|
||||
request.setRequestURI(uri);
|
||||
return request;
|
||||
}
|
||||
|
||||
private static ProtectionProperties.Captcha appCaptcha(boolean enabled, String provider, String site, String secret) {
|
||||
ProtectionProperties.Captcha c = new ProtectionProperties.Captcha();
|
||||
c.setEnabled(enabled);
|
||||
c.setProvider(provider);
|
||||
c.setSiteKey(site);
|
||||
c.setSecretKey(secret);
|
||||
return c;
|
||||
}
|
||||
|
||||
/** A real AES-GCM cipher so an enabled trusted-device service can mint + verify a genuine cookie. */
|
||||
private static SecretCipher realCipher() {
|
||||
RunwaySecurityProperties security = new RunwaySecurityProperties();
|
||||
security.setSecretKey("contributor-test-master-key-0123456789");
|
||||
return new AesGcmSecretCipher(security);
|
||||
}
|
||||
|
||||
private static TrustedDeviceService enabledTd(ProtectionConfigStore store, SecretCipher cipher) {
|
||||
return new TrustedDeviceService(new ProtectionProperties(), store, cipher); // remember-device on, 30 days
|
||||
}
|
||||
|
||||
// ---- "remember this device" offer + trusted-device skip ---------------------------------------
|
||||
|
||||
@Test
|
||||
void theRememberOfferAppearsOnLoginWhenACaptchaIsShown(@TempDir Path root) throws Exception {
|
||||
SecretCipher cipher = realCipher();
|
||||
ProtectionConfigStore store = appStore(root, appCaptcha(true, "recaptcha-v2", "K", "S"));
|
||||
CaptchaLoginViewContributor contributor =
|
||||
new CaptchaLoginViewContributor(store, resolver(root), enabledTd(store, cipher));
|
||||
|
||||
ModelAndView mav = new ModelAndView("operator/login-app");
|
||||
contributor.postHandle(get("/app/login"), new MockHttpServletResponse(), new Object(), mav);
|
||||
|
||||
assertEquals(Boolean.TRUE, mav.getModel().get("captchaActive"), "no cookie yet ⇒ captcha shown");
|
||||
assertEquals(Boolean.TRUE, mav.getModel().get("rememberDeviceOffered"), "…so the remember-device box is offered");
|
||||
assertEquals(30, mav.getModel().get("rememberDeviceDays"), "the configured trust window reaches the view");
|
||||
}
|
||||
|
||||
@Test
|
||||
void theRememberOfferIsNotShownOnTheForgotPasswordForm(@TempDir Path root) throws Exception {
|
||||
SecretCipher cipher = realCipher();
|
||||
ProtectionConfigStore store = appStore(root, appCaptcha(true, "recaptcha-v2", "K", "S"));
|
||||
CaptchaLoginViewContributor contributor =
|
||||
new CaptchaLoginViewContributor(store, resolver(root), enabledTd(store, cipher));
|
||||
|
||||
ModelAndView mav = new ModelAndView("operator/recovery-request");
|
||||
contributor.postHandle(get("/app/forgot-password"), new MockHttpServletResponse(), new Object(), mav);
|
||||
|
||||
assertEquals(Boolean.TRUE, mav.getModel().get("captchaActive"), "the recovery form still shows a captcha");
|
||||
assertEquals(Boolean.FALSE, mav.getModel().get("rememberDeviceOffered"),
|
||||
"but 'remember this device' only makes sense on the login form");
|
||||
}
|
||||
|
||||
@Test
|
||||
void aTrustedDeviceHidesTheCaptchaAndTheOffer(@TempDir Path root) throws Exception {
|
||||
SecretCipher cipher = realCipher();
|
||||
ProtectionConfigStore store = appStore(root, appCaptcha(true, "recaptcha-v2", "K", "S"));
|
||||
TrustedDeviceService svc = enabledTd(store, cipher);
|
||||
|
||||
// Mint a real cookie via the issue path (opt-in login POST with an active captcha).
|
||||
MockHttpServletRequest post = new MockHttpServletRequest("POST", "/app/login");
|
||||
post.addParameter(TrustedDeviceService.REMEMBER_PARAM, "1");
|
||||
MockHttpServletResponse minted = new MockHttpServletResponse();
|
||||
svc.rememberIfRequested(post, minted, ProtectionScope.application());
|
||||
String header = minted.getHeader(org.springframework.http.HttpHeaders.SET_COOKIE);
|
||||
String nameValue = header.substring(0, header.indexOf(';'));
|
||||
int eq = nameValue.indexOf('=');
|
||||
|
||||
MockHttpServletRequest getReq = get("/app/login");
|
||||
getReq.setCookies(new Cookie(nameValue.substring(0, eq), nameValue.substring(eq + 1)));
|
||||
CaptchaLoginViewContributor contributor = new CaptchaLoginViewContributor(store, resolver(root), svc);
|
||||
|
||||
ModelAndView mav = new ModelAndView("operator/login-app");
|
||||
contributor.postHandle(getReq, new MockHttpServletResponse(), new Object(), mav);
|
||||
|
||||
assertEquals(Boolean.FALSE, mav.getModel().get("captchaActive"), "a trusted device sees no captcha widget");
|
||||
assertEquals(Boolean.FALSE, mav.getModel().get("rememberDeviceOffered"), "…and no remember-device offer");
|
||||
}
|
||||
|
||||
@Test
|
||||
void anActiveCaptchaSetsPublicFlagsAndNeverTheSecret(@TempDir Path root) throws Exception {
|
||||
ProtectionConfigStore store = appStore(root, appCaptcha(true, "recaptcha-v2", "PUBLIC-SITE-KEY", "SECRET-XYZ"));
|
||||
CaptchaLoginViewContributor contributor = new CaptchaLoginViewContributor(store, resolver(root), td());
|
||||
|
||||
ModelAndView mav = new ModelAndView("operator/login-app");
|
||||
contributor.postHandle(get("/app/login"), new MockHttpServletResponse(), new Object(), mav);
|
||||
Map<String, Object> model = mav.getModel();
|
||||
|
||||
assertEquals(Boolean.TRUE, model.get("captchaActive"));
|
||||
assertEquals("recaptcha-v2", model.get("captchaProvider"));
|
||||
assertEquals(Boolean.TRUE, model.get("captchaRecaptchaV2"));
|
||||
assertEquals(Boolean.FALSE, model.get("captchaRecaptchaV3"));
|
||||
assertEquals("PUBLIC-SITE-KEY", model.get("captchaSiteKey"), "the PUBLIC site key reaches the view");
|
||||
assertEquals("g-recaptcha", model.get("captchaWidgetClass"));
|
||||
assertEquals("g-recaptcha-response", model.get("captchaTokenField"));
|
||||
assertTrue(((String) model.get("captchaScriptUrl")).startsWith("https://www.google.com/recaptcha/"));
|
||||
|
||||
// The secret must never appear anywhere in the model — not as a value, not spliced into a url.
|
||||
for (Object v : model.values()) {
|
||||
if (v instanceof String s) {
|
||||
assertFalse(s.contains("SECRET-XYZ"), "the captcha secret must never reach the view");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void theRecoveryRequestFormAlsoGetsTheScopeCaptcha(@TempDir Path root) throws Exception {
|
||||
// The forgot-password REQUEST form renders the same app-scope challenge as /app/login, so a configured
|
||||
// CAPTCHA also guards the reset-email request.
|
||||
ProtectionConfigStore store = appStore(root, appCaptcha(true, "recaptcha-v2", "PUBLIC-SITE-KEY", "SECRET-XYZ"));
|
||||
CaptchaLoginViewContributor contributor = new CaptchaLoginViewContributor(store, resolver(root), td());
|
||||
|
||||
ModelAndView mav = new ModelAndView("operator/recovery-forgot");
|
||||
contributor.postHandle(get("/app/forgot-password"), new MockHttpServletResponse(), new Object(), mav);
|
||||
|
||||
assertEquals(Boolean.TRUE, mav.getModel().get("captchaActive"), "the forgot form gets the app-scope captcha");
|
||||
assertEquals("PUBLIC-SITE-KEY", mav.getModel().get("captchaSiteKey"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void recaptchaV3SetsTheRenderScriptAndNoVisibleWidgetClass(@TempDir Path root) throws Exception {
|
||||
ProtectionConfigStore store = appStore(root, appCaptcha(true, "recaptcha-v3", "V3KEY", "SECRET"));
|
||||
CaptchaLoginViewContributor contributor = new CaptchaLoginViewContributor(store, resolver(root), td());
|
||||
|
||||
ModelAndView mav = new ModelAndView("operator/login-app");
|
||||
contributor.postHandle(get("/app/login"), new MockHttpServletResponse(), new Object(), mav);
|
||||
Map<String, Object> model = mav.getModel();
|
||||
|
||||
assertEquals(Boolean.TRUE, model.get("captchaRecaptchaV3"));
|
||||
assertEquals("", model.get("captchaWidgetClass"), "v3 is invisible — no widget class");
|
||||
assertEquals("g-recaptcha-response", model.get("captchaTokenField"));
|
||||
assertTrue(((String) model.get("captchaScriptUrl")).contains("render=V3KEY"),
|
||||
"v3 splices the public site key into ?render=");
|
||||
}
|
||||
|
||||
@Test
|
||||
void anInactiveCaptchaSetsOnlyTheFalseFlag(@TempDir Path root) throws Exception {
|
||||
ProtectionConfigStore store = appStore(root, appCaptcha(false, "recaptcha-v2", "", "")); // disabled
|
||||
CaptchaLoginViewContributor contributor = new CaptchaLoginViewContributor(store, resolver(root), td());
|
||||
|
||||
ModelAndView mav = new ModelAndView("operator/login-app");
|
||||
contributor.postHandle(get("/app/login"), new MockHttpServletResponse(), new Object(), mav);
|
||||
Map<String, Object> model = mav.getModel();
|
||||
|
||||
assertEquals(Boolean.FALSE, model.get("captchaActive"));
|
||||
assertNull(model.get("captchaSiteKey"), "no key, no widget when inactive");
|
||||
assertNull(model.get("captchaProvider"));
|
||||
assertNull(model.get("captchaScriptUrl"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aNonLoginPathIsUntouched(@TempDir Path root) throws Exception {
|
||||
ProtectionConfigStore store = appStore(root, appCaptcha(true, "recaptcha-v2", "K", "S"));
|
||||
CaptchaLoginViewContributor contributor = new CaptchaLoginViewContributor(store, resolver(root), td());
|
||||
|
||||
ModelAndView mav = new ModelAndView("operator/dashboard");
|
||||
contributor.postHandle(get("/__app/dashboard"), new MockHttpServletResponse(), new Object(), mav);
|
||||
assertTrue(mav.getModel().isEmpty(), "a non-login view gets no captcha attributes");
|
||||
}
|
||||
|
||||
@Test
|
||||
void aNullModelAndViewIsIgnored(@TempDir Path root) throws Exception {
|
||||
ProtectionConfigStore store = appStore(root, appCaptcha(true, "recaptcha-v2", "K", "S"));
|
||||
CaptchaLoginViewContributor contributor = new CaptchaLoginViewContributor(store, resolver(root), td());
|
||||
// A redirect with no view — must not throw.
|
||||
contributor.postHandle(get("/app/login"), new MockHttpServletResponse(), new Object(), null);
|
||||
}
|
||||
|
||||
@Test
|
||||
void theTenantLoginResolvesTheBoundSitesPerSiteCaptcha(@TempDir Path root) throws Exception {
|
||||
// The app scope has NO captcha; the bound site does — proving the /login path reads the per-site config,
|
||||
// not the app's, via SiteResolver.current().
|
||||
ProtectionConfigStore store = appStore(root, appCaptcha(false, "recaptcha-v2", "", ""));
|
||||
store.savePerSite("acme", new ProtectionSettings(true, 5, 300, 900,
|
||||
new ProtectionSettings.Captcha(true, "recaptcha-v3", "SITE-ACME", "SECRET-ACME", 0.5)));
|
||||
|
||||
SiteResolver resolver = resolver(root);
|
||||
resolver.bind(site("acme"));
|
||||
try {
|
||||
CaptchaLoginViewContributor contributor = new CaptchaLoginViewContributor(store, resolver, td());
|
||||
ModelAndView mav = new ModelAndView("operator/login-tenant");
|
||||
contributor.postHandle(get("/login"), new MockHttpServletResponse(), new Object(), mav);
|
||||
Map<String, Object> model = mav.getModel();
|
||||
|
||||
assertEquals(Boolean.TRUE, model.get("captchaActive"), "the bound site's captcha governs the tenant login");
|
||||
assertEquals("recaptcha-v3", model.get("captchaProvider"));
|
||||
assertEquals("SITE-ACME", model.get("captchaSiteKey"));
|
||||
for (Object v : model.values()) {
|
||||
if (v instanceof String s) {
|
||||
assertFalse(s.contains("SECRET-ACME"), "the per-site captcha secret must never reach the view");
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
resolver.clear();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,214 @@
|
||||
package mx.quest.protection;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
/**
|
||||
* The captcha verifier's request-building and response-parsing through the injected
|
||||
* {@link CaptchaVerifier.Exchange} seam — no real network. Since 0.4.0 the only provider is Google reCAPTCHA
|
||||
* (v2 + v3); this covers the reCAPTCHA endpoint + form body, the {@code success} parse, the v3 score gate, the
|
||||
* legacy-value migration to v2, the provider-shaped widget helpers, the blank-token short-circuit, and the
|
||||
* fail-open stance on a transport error / non-2xx status.
|
||||
*/
|
||||
class CaptchaVerifierTest {
|
||||
|
||||
/** A recording exchange: captures the URL + body and returns a canned response (or throws). */
|
||||
private static final class RecordingExchange implements CaptchaVerifier.Exchange {
|
||||
final AtomicReference<String> url = new AtomicReference<>();
|
||||
final AtomicReference<String> body = new AtomicReference<>();
|
||||
private final CaptchaVerifier.Exchange.Response response;
|
||||
private final IOException toThrow;
|
||||
|
||||
RecordingExchange(CaptchaVerifier.Exchange.Response response) {
|
||||
this.response = response;
|
||||
this.toThrow = null;
|
||||
}
|
||||
|
||||
RecordingExchange(IOException toThrow) {
|
||||
this.response = null;
|
||||
this.toThrow = toThrow;
|
||||
}
|
||||
|
||||
@Override
|
||||
public CaptchaVerifier.Exchange.Response post(String u, String b) throws IOException {
|
||||
url.set(u);
|
||||
body.set(b);
|
||||
if (toThrow != null) {
|
||||
throw toThrow;
|
||||
}
|
||||
return response;
|
||||
}
|
||||
}
|
||||
|
||||
private static CaptchaVerifier.Exchange.Response ok(String json) {
|
||||
return new CaptchaVerifier.Exchange.Response(200, json);
|
||||
}
|
||||
|
||||
private static ProtectionSettings.Captcha captcha(String provider, double threshold) {
|
||||
return new ProtectionSettings.Captcha(true, provider, "SITEKEY", "sk-secret", threshold);
|
||||
}
|
||||
|
||||
// ---- token param + widget helpers -------------------------------------
|
||||
|
||||
@Test
|
||||
void tokenParamIsAlwaysTheRecaptchaField() {
|
||||
// Both modes (and any legacy/blank value that migrates to v2) post under the same field name.
|
||||
assertEquals("g-recaptcha-response", CaptchaVerifier.tokenParam("recaptcha-v2"));
|
||||
assertEquals("g-recaptcha-response", CaptchaVerifier.tokenParam("recaptcha-v3"));
|
||||
assertEquals("g-recaptcha-response", CaptchaVerifier.tokenParam(null));
|
||||
assertEquals("g-recaptcha-response", CaptchaVerifier.tokenParam("turnstile"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void widgetHelpersDistinguishVisibleV2FromInvisibleV3() {
|
||||
assertFalse(CaptchaVerifier.isInvisible("recaptcha-v2"));
|
||||
assertTrue(CaptchaVerifier.isInvisible("recaptcha-v3"));
|
||||
// A legacy / blank value normalizes to the visible v2.
|
||||
assertFalse(CaptchaVerifier.isInvisible("turnstile"));
|
||||
assertFalse(CaptchaVerifier.isInvisible(null));
|
||||
|
||||
assertEquals("g-recaptcha", CaptchaVerifier.widgetClass("recaptcha-v2"));
|
||||
assertEquals("", CaptchaVerifier.widgetClass("recaptcha-v3"), "v3 is invisible — no widget div");
|
||||
|
||||
assertEquals("https://www.google.com/recaptcha/api.js", CaptchaVerifier.scriptUrl("recaptcha-v2", "KEY"));
|
||||
assertEquals("https://www.google.com/recaptcha/api.js?render=KEY",
|
||||
CaptchaVerifier.scriptUrl("recaptcha-v3", "KEY"), "v3 splices the site key into ?render=");
|
||||
}
|
||||
|
||||
// ---- endpoint + body --------------------------------------------------
|
||||
|
||||
@Test
|
||||
void verifyPostsSecretResponseAndRemoteIpToTheRecaptchaEndpoint() {
|
||||
RecordingExchange ex = new RecordingExchange(ok("{\"success\":true}"));
|
||||
boolean result = new CaptchaVerifier(ex).verify(captcha("recaptcha-v2", 0.5), "tok123", "203.0.113.1");
|
||||
assertTrue(result);
|
||||
assertEquals(CaptchaVerifier.RECAPTCHA_URL, ex.url.get());
|
||||
assertTrue(ex.body.get().contains("secret=sk-secret"), "the secret is form-encoded into the body");
|
||||
assertTrue(ex.body.get().contains("response=tok123"), "the token is the response param");
|
||||
assertTrue(ex.body.get().contains("remoteip=203.0.113.1"), "the remote ip hint is included when present");
|
||||
}
|
||||
|
||||
@Test
|
||||
void recaptchaV2AndV3HitTheRecaptchaEndpoint() {
|
||||
RecordingExchange v2 = new RecordingExchange(ok("{\"success\":true}"));
|
||||
assertTrue(new CaptchaVerifier(v2).verify(captcha("recaptcha-v2", 0.5), "t", "203.0.113.1"));
|
||||
assertEquals(CaptchaVerifier.RECAPTCHA_URL, v2.url.get());
|
||||
|
||||
RecordingExchange v3 = new RecordingExchange(ok("{\"success\":true,\"score\":0.9}"));
|
||||
assertTrue(new CaptchaVerifier(v3).verify(captcha("recaptcha-v3", 0.5), "t", "203.0.113.1"));
|
||||
assertEquals(CaptchaVerifier.RECAPTCHA_URL, v3.url.get());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aLegacyProviderValueMigratesToRecaptchaV2AndStillVerifies() {
|
||||
// A site left over from a dropped provider (Turnstile / hCaptcha) verifies against reCAPTCHA as v2 —
|
||||
// it keeps working after upgrade (the operator must supply a reCAPTCHA key for the challenge to pass).
|
||||
RecordingExchange ex = new RecordingExchange(ok("{\"success\":true}"));
|
||||
assertTrue(new CaptchaVerifier(ex).verify(captcha("turnstile", 0.5), "tok", "203.0.113.1"));
|
||||
assertEquals(CaptchaVerifier.RECAPTCHA_URL, ex.url.get(), "a legacy value hits the reCAPTCHA endpoint");
|
||||
}
|
||||
|
||||
@Test
|
||||
void remoteIpIsOmittedWhenBlank() {
|
||||
RecordingExchange ex = new RecordingExchange(ok("{\"success\":true}"));
|
||||
new CaptchaVerifier(ex).verify(captcha("recaptcha-v2", 0.5), "tok", null);
|
||||
assertFalse(ex.body.get().contains("remoteip="), "no remoteip param when the ip is null");
|
||||
}
|
||||
|
||||
// ---- success / rejection parse ----------------------------------------
|
||||
|
||||
@Test
|
||||
void aSuccessFalseResponseIsRejected() {
|
||||
RecordingExchange ex = new RecordingExchange(ok("{\"success\":false,\"error-codes\":[\"invalid-input-response\"]}"));
|
||||
assertFalse(new CaptchaVerifier(ex).verify(captcha("recaptcha-v2", 0.5), "tok", "203.0.113.1"),
|
||||
"the provider actively rejected the token");
|
||||
}
|
||||
|
||||
// ---- blank token short-circuit ----------------------------------------
|
||||
|
||||
@Test
|
||||
void aBlankTokenFailsWithoutCallingTheProvider() {
|
||||
AtomicReference<Boolean> called = new AtomicReference<>(false);
|
||||
CaptchaVerifier.Exchange ex = (url, body) -> { called.set(true); return ok("{\"success\":true}"); };
|
||||
CaptchaVerifier verifier = new CaptchaVerifier(ex);
|
||||
assertFalse(verifier.verify(captcha("recaptcha-v2", 0.5), "", "203.0.113.1"), "empty token → not verified");
|
||||
assertFalse(verifier.verify(captcha("recaptcha-v2", 0.5), null, "203.0.113.1"), "null token → not verified");
|
||||
assertFalse(verifier.verify(captcha("recaptcha-v2", 0.5), " ", "203.0.113.1"), "blank token → not verified");
|
||||
assertFalse(called.get(), "a missing token never reaches the provider");
|
||||
}
|
||||
|
||||
// ---- reCAPTCHA v3 score gate ------------------------------------------
|
||||
|
||||
@Test
|
||||
void recaptchaV3RejectsAScoreBelowTheThreshold() {
|
||||
RecordingExchange ex = new RecordingExchange(ok("{\"success\":true,\"score\":0.3}"));
|
||||
assertFalse(new CaptchaVerifier(ex).verify(captcha("recaptcha-v3", 0.5), "tok", "203.0.113.1"),
|
||||
"v3 score 0.3 < threshold 0.5 → rejected");
|
||||
}
|
||||
|
||||
@Test
|
||||
void recaptchaV3AcceptsAScoreAtOrAboveTheThreshold() {
|
||||
RecordingExchange atThreshold = new RecordingExchange(ok("{\"success\":true,\"score\":0.5}"));
|
||||
assertTrue(new CaptchaVerifier(atThreshold).verify(captcha("recaptcha-v3", 0.5), "tok", "203.0.113.1"),
|
||||
"v3 score == threshold → accepted");
|
||||
|
||||
RecordingExchange above = new RecordingExchange(ok("{\"success\":true,\"score\":0.8}"));
|
||||
assertTrue(new CaptchaVerifier(above).verify(captcha("recaptcha-v3", 0.5), "tok", "203.0.113.1"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void theScoreGateOnlyAppliesToV3NotV2() {
|
||||
// v2 has no score; a success:true (no score field) passes even though the config carries a threshold.
|
||||
RecordingExchange ex = new RecordingExchange(ok("{\"success\":true}"));
|
||||
assertTrue(new CaptchaVerifier(ex).verify(captcha("recaptcha-v2", 0.9), "tok", "203.0.113.1"),
|
||||
"v2 ignores the score threshold");
|
||||
}
|
||||
|
||||
// ---- fail-open on transport error / non-2xx ---------------------------
|
||||
|
||||
@Test
|
||||
void aTransportErrorFailsOpen() {
|
||||
RecordingExchange ex = new RecordingExchange(new IOException("connection reset"));
|
||||
assertTrue(new CaptchaVerifier(ex).verify(captcha("recaptcha-v2", 0.5), "tok", "203.0.113.1"),
|
||||
"a provider outage must never lock everyone out — fail open");
|
||||
}
|
||||
|
||||
@Test
|
||||
void aNon2xxStatusFailsOpen() {
|
||||
RecordingExchange ex = new RecordingExchange(new CaptchaVerifier.Exchange.Response(503, "gateway down"));
|
||||
assertTrue(new CaptchaVerifier(ex).verify(captcha("recaptcha-v3", 0.5), "tok", "203.0.113.1"),
|
||||
"a 5xx from the provider fails open");
|
||||
}
|
||||
|
||||
@Test
|
||||
void aNullResponseFailsOpen() {
|
||||
CaptchaVerifier.Exchange ex = (url, body) -> null;
|
||||
assertTrue(new CaptchaVerifier(ex).verify(captcha("recaptcha-v2", 0.5), "tok", "203.0.113.1"),
|
||||
"a null response is treated as an outage — fail open");
|
||||
}
|
||||
|
||||
// ---- score reader edge cases ------------------------------------------
|
||||
|
||||
@Test
|
||||
void anUnparseableBodyOnA200IsTreatedAsNotVerified() {
|
||||
// A present (2xx) but nonsense body has no success:true → rejected (the transport fail-open is only for
|
||||
// an unreachable provider, decided before parsing).
|
||||
RecordingExchange ex = new RecordingExchange(ok("not json at all"));
|
||||
assertFalse(new CaptchaVerifier(ex).verify(captcha("recaptcha-v2", 0.5), "tok", "203.0.113.1"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void siteVerifyResponseReadsSuccessAndScore() {
|
||||
assertTrue(SiteVerifyResponse.success("{\"success\": true, \"score\": 0.7}"));
|
||||
assertFalse(SiteVerifyResponse.success("{\"success\": false}"));
|
||||
assertFalse(SiteVerifyResponse.success(""), "blank body → not success");
|
||||
assertFalse(SiteVerifyResponse.success(null), "null body → not success");
|
||||
assertEquals(0.7, SiteVerifyResponse.score("{\"success\":true,\"score\":0.7}"), 1e-9);
|
||||
assertEquals(0.0, SiteVerifyResponse.score("{\"success\":true}"), 1e-9, "absent score → 0.0 floor");
|
||||
}
|
||||
}
|
||||
+103
@@ -0,0 +1,103 @@
|
||||
package mx.quest.protection;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
import mx.quest.runway.console.AssetVersion;
|
||||
import mx.quest.runway.security.ProtectionScope;
|
||||
import mx.quest.runway.spi.model.CaptchaWidget;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
/**
|
||||
* The reusable site-form CAPTCHA seam: an inactive site yields an inactive widget and always-accept verify; an
|
||||
* active Turnstile site yields the visible widget markup + provider script; reCAPTCHA v3 yields the invisible
|
||||
* hidden-field + execute script; and verify delegates to {@link CaptchaVerifier} only when a challenge is active.
|
||||
*/
|
||||
class CaptchaWidgetServiceTest {
|
||||
|
||||
private static ProtectionSettings withCaptcha(ProtectionSettings.Captcha captcha) {
|
||||
return new ProtectionSettings(true, 10, 900, 900, captcha);
|
||||
}
|
||||
|
||||
private static ProtectionConfigStore storeReturning(ProtectionSettings.Captcha captcha) {
|
||||
ProtectionConfigStore store = mock(ProtectionConfigStore.class);
|
||||
when(store.resolve(any(ProtectionScope.class))).thenReturn(withCaptcha(captcha));
|
||||
return store;
|
||||
}
|
||||
|
||||
@Test
|
||||
void anInactiveSiteYieldsAnInactiveWidgetAndAlwaysAcceptsVerify() {
|
||||
CaptchaWidgetService svc = new CaptchaWidgetService(
|
||||
storeReturning(ProtectionSettings.Captcha.disabled()), mock(CaptchaVerifier.class));
|
||||
|
||||
CaptchaWidget widget = svc.widgetForSite("acme");
|
||||
assertFalse(widget.active(), "no configured challenge ⇒ inactive");
|
||||
assertTrue(widget.html().isEmpty(), "no markup when inactive");
|
||||
assertTrue(svc.verify("acme", null, null), "verify accepts unconditionally when inactive");
|
||||
}
|
||||
|
||||
@Test
|
||||
void anActiveRecaptchaV2SiteRendersTheVisibleWidget() {
|
||||
ProtectionSettings.Captcha v2 =
|
||||
new ProtectionSettings.Captcha(true, "recaptcha-v2", "PUBLIC-KEY", "SECRET", 0.5);
|
||||
CaptchaWidgetService svc = new CaptchaWidgetService(storeReturning(v2), mock(CaptchaVerifier.class));
|
||||
|
||||
CaptchaWidget widget = svc.widgetForSite("acme");
|
||||
assertTrue(widget.active());
|
||||
assertEquals("g-recaptcha-response", widget.tokenField());
|
||||
assertTrue(widget.html().contains("g-recaptcha"), "the provider widget class is present");
|
||||
assertTrue(widget.html().contains("data-sitekey=\"PUBLIC-KEY\""), "the PUBLIC site key is embedded");
|
||||
assertTrue(widget.html().contains("www.google.com/recaptcha/api.js"), "the provider script is loaded");
|
||||
assertFalse(widget.html().contains("SECRET"), "the secret key is NEVER embedded in the widget");
|
||||
}
|
||||
|
||||
@Test
|
||||
void anActiveRecaptchaV3SiteRendersTheInvisibleField() {
|
||||
ProtectionSettings.Captcha v3 =
|
||||
new ProtectionSettings.Captcha(true, "recaptcha-v3", "V3-KEY", "SECRET", 0.7);
|
||||
CaptchaWidgetService svc = new CaptchaWidgetService(storeReturning(v3), mock(CaptchaVerifier.class));
|
||||
|
||||
CaptchaWidget widget = svc.widgetForSite("acme");
|
||||
assertTrue(widget.active());
|
||||
assertEquals("g-recaptcha-response", widget.tokenField());
|
||||
assertTrue(widget.html().contains("rw-captcha-v3"), "the invisible v3 hidden field is present");
|
||||
// The submit-time execute logic is now the shared, externalized client (no inline <script> — CSP script-src
|
||||
// dropped 'unsafe-inline'); the widget references it by src alongside the provider script.
|
||||
assertTrue(widget.html().contains("/__assets/captcha-v3.js"), "the v3 client is referenced by src");
|
||||
assertFalse(widget.html().contains("<script>"), "no inline <script> — it would violate the tightened CSP");
|
||||
assertTrue(widget.html().contains("render=V3-KEY"), "the v3 provider script carries ?render=<siteKey>");
|
||||
}
|
||||
|
||||
@Test
|
||||
void theV3ClientReferenceCarriesTheKernelAssetToken() {
|
||||
ProtectionSettings.Captcha v3 =
|
||||
new ProtectionSettings.Captcha(true, "recaptcha-v3", "V3-KEY", "SECRET", 0.7);
|
||||
// Wired with the kernel's token (as ProtectionConfig does), the client URL changes with every release, so a
|
||||
// day-cached old client can never outlive an upgrade.
|
||||
String versioned = new CaptchaWidgetService(storeReturning(v3), mock(CaptchaVerifier.class),
|
||||
AssetVersion.fixed("1760000000000")).widgetForSite("acme").html();
|
||||
assertTrue(versioned.contains("src=\"/__assets/captcha-v3.js?v=1760000000000\""), versioned);
|
||||
// The legacy two-argument constructor stays unversioned (served no-cache by the kernel: correct, slower).
|
||||
String legacy = new CaptchaWidgetService(storeReturning(v3), mock(CaptchaVerifier.class))
|
||||
.widgetForSite("acme").html();
|
||||
assertTrue(legacy.contains("src=\"/__assets/captcha-v3.js\""), legacy);
|
||||
}
|
||||
|
||||
@Test
|
||||
void verifyDelegatesToTheVerifierWhenActive() {
|
||||
ProtectionSettings.Captcha v2 =
|
||||
new ProtectionSettings.Captcha(true, "recaptcha-v2", "PUBLIC-KEY", "SECRET", 0.5);
|
||||
CaptchaVerifier verifier = mock(CaptchaVerifier.class);
|
||||
when(verifier.verify(any(), eq("good-token"), any())).thenReturn(true);
|
||||
when(verifier.verify(any(), eq("bad-token"), any())).thenReturn(false);
|
||||
CaptchaWidgetService svc = new CaptchaWidgetService(storeReturning(v2), verifier);
|
||||
|
||||
assertTrue(svc.verify("acme", "good-token", "1.2.3.4"));
|
||||
assertFalse(svc.verify("acme", "bad-token", "1.2.3.4"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,213 @@
|
||||
package mx.quest.protection;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import org.jsoup.Jsoup;
|
||||
import org.jsoup.nodes.Document;
|
||||
import org.jsoup.nodes.Element;
|
||||
|
||||
/**
|
||||
* A verbatim copy of the kernel's {@code mx.quest.runway.console.OperatorA11yAudit} (runway-app's TEST sources are
|
||||
* not on this module's classpath): the protection screens render inside the kernel's operator console, so they
|
||||
* are held to exactly the same rules. Keep the two in step — change the kernel's first, then copy it here.
|
||||
*
|
||||
* <p>The structural accessibility rules every rendered operator page must satisfy. It is deliberately a
|
||||
* small, offline, deterministic checker — not a full WCAG engine: it encodes the defects the accessibility audit found so
|
||||
* they cannot come back, and nothing that needs a browser (contrast, focus order at runtime, live regions).
|
||||
*
|
||||
* <p>The rules, each reported as one human-readable violation line naming the offending element:
|
||||
* <ol>
|
||||
* <li>{@code <html lang>} is present and non-empty (screen readers pick their pronunciation from it).</li>
|
||||
* <li>Every user-facing form control — {@code input} (except {@code hidden}/{@code submit}/{@code button}/
|
||||
* {@code reset}/{@code image}), {@code select}, {@code textarea} — has an accessible name: a
|
||||
* {@code <label for>} pointing at its id, a wrapping {@code <label>}, a non-empty {@code aria-label}, or an
|
||||
* {@code aria-labelledby} whose every id exists. A {@code title} alone does not count.</li>
|
||||
* <li>Every {@code <button>} and {@code <a>} has an accessible name: visible text, an {@code <img alt>} inside
|
||||
* it, a non-empty {@code aria-label}, or a resolvable {@code aria-labelledby}. Icon-only controls named only
|
||||
* by {@code title} fail.</li>
|
||||
* <li>Every {@code <iframe>} has a {@code title} (its accessible name).</li>
|
||||
* <li>Every {@code <table>} has at least one {@code <th>}, and every {@code <th>} declares {@code scope}.</li>
|
||||
* <li>Every {@code <label for>} points at an element that exists.</li>
|
||||
* <li>Element ids are unique in the rendered page.</li>
|
||||
* <li>Every {@code aria-labelledby} names ids that exist; every Bootstrap {@code .modal} is named by an
|
||||
* {@code aria-labelledby} and carries {@code tabindex="-1"} (Bootstrap's Escape-to-close needs it).</li>
|
||||
* <li>The page has exactly one {@code <main>} landmark.</li>
|
||||
* <li>On a console page (one carrying the realm topbar): a skip link to {@code <main>} is the first link in
|
||||
* the body, and the topbar's menus sit in a {@code <nav>} with an accessible name.</li>
|
||||
* </ol>
|
||||
* Elements inside an {@code aria-hidden="true"} subtree (the login honeypot) are exempt: they are removed from
|
||||
* the accessibility tree on purpose.
|
||||
*/
|
||||
final class ConsoleA11yAudit {
|
||||
|
||||
private static final Set<String> UNNAMED_INPUT_TYPES = Set.of("hidden", "submit", "button", "reset", "image");
|
||||
|
||||
private ConsoleA11yAudit() {
|
||||
}
|
||||
|
||||
/** Every violation found in the whole page {@code html}, prefixed with {@code where} (empty when clean). */
|
||||
static List<String> audit(String where, String html) {
|
||||
return audit(where, html, true);
|
||||
}
|
||||
|
||||
/**
|
||||
* Every violation found in {@code html}. With {@code wholePage} false the markup is a FRAGMENT (a plugin panel
|
||||
* rendered on its own): the page-level rules ({@code lang}, one {@code <main>}, the skip link) are skipped
|
||||
* because the host page supplies them; every element-level rule still applies.
|
||||
*/
|
||||
static List<String> audit(String where, String html, boolean wholePage) {
|
||||
Document doc = Jsoup.parse(html);
|
||||
List<String> out = new ArrayList<>();
|
||||
|
||||
String lang = doc.selectFirst("html") == null ? "" : doc.selectFirst("html").attr("lang").trim();
|
||||
if (wholePage && lang.isEmpty()) {
|
||||
out.add(where + ": <html> has no lang");
|
||||
}
|
||||
|
||||
Map<String, Integer> idCounts = new HashMap<>();
|
||||
for (Element e : doc.select("[id]")) {
|
||||
idCounts.merge(e.id(), 1, Integer::sum);
|
||||
}
|
||||
idCounts.forEach((id, n) -> {
|
||||
if (n > 1) {
|
||||
out.add(where + ": id \"" + id + "\" appears " + n + " times");
|
||||
}
|
||||
});
|
||||
|
||||
for (Element control : doc.select("input, select, textarea")) {
|
||||
if (hidden(control)) {
|
||||
continue;
|
||||
}
|
||||
if (control.tagName().equals("input")
|
||||
&& UNNAMED_INPUT_TYPES.contains(control.attr("type").toLowerCase(Locale.ROOT))) {
|
||||
continue;
|
||||
}
|
||||
if (!controlHasName(doc, control)) {
|
||||
out.add(where + ": unlabelled " + describe(control));
|
||||
}
|
||||
}
|
||||
|
||||
for (Element clickable : doc.select("button, a")) {
|
||||
if (hidden(clickable)) {
|
||||
continue;
|
||||
}
|
||||
if (!hasText(clickable) && !ariaNamed(doc, clickable)) {
|
||||
out.add(where + ": " + clickable.tagName() + " without an accessible name " + describe(clickable));
|
||||
}
|
||||
}
|
||||
|
||||
for (Element frame : doc.select("iframe")) {
|
||||
if (frame.attr("title").isBlank() && !ariaNamed(doc, frame)) {
|
||||
out.add(where + ": iframe without a title " + describe(frame));
|
||||
}
|
||||
}
|
||||
|
||||
for (Element table : doc.select("table")) {
|
||||
if (table.select("th").isEmpty()) {
|
||||
out.add(where + ": table without <th> " + describe(table));
|
||||
}
|
||||
}
|
||||
for (Element th : doc.select("th")) {
|
||||
if (th.attr("scope").isBlank()) {
|
||||
out.add(where + ": <th> without scope " + describe(th));
|
||||
}
|
||||
}
|
||||
|
||||
for (Element label : doc.select("label[for]")) {
|
||||
if (doc.getElementById(label.attr("for")) == null) {
|
||||
out.add(where + ": <label for=\"" + label.attr("for") + "\"> points at no element");
|
||||
}
|
||||
}
|
||||
|
||||
for (Element e : doc.select("[aria-labelledby]")) {
|
||||
if (!ariaNamed(doc, e) && e.attr("aria-label").isBlank()) {
|
||||
out.add(where + ": aria-labelledby=\"" + e.attr("aria-labelledby") + "\" names a missing id "
|
||||
+ describe(e));
|
||||
}
|
||||
}
|
||||
for (Element modal : doc.select(".modal")) {
|
||||
if (modal.attr("aria-labelledby").isBlank() || !ariaNamed(doc, modal)) {
|
||||
out.add(where + ": modal without a resolvable aria-labelledby " + describe(modal));
|
||||
}
|
||||
if (!"-1".equals(modal.attr("tabindex"))) {
|
||||
out.add(where + ": modal without tabindex=\"-1\" (Escape cannot close it) " + describe(modal));
|
||||
}
|
||||
}
|
||||
|
||||
if (!wholePage) {
|
||||
return out;
|
||||
}
|
||||
int mains = doc.select("main").size();
|
||||
if (mains != 1) {
|
||||
out.add(where + ": " + mains + " <main> landmarks (exactly one expected)");
|
||||
}
|
||||
|
||||
if (!doc.select(".rw-topbar").isEmpty()) {
|
||||
Element first = doc.body() == null ? null : doc.body().selectFirst("a[href]");
|
||||
Element main = doc.selectFirst("main");
|
||||
boolean skip = first != null && first.hasClass("rw-skip-link") && main != null && !main.id().isEmpty()
|
||||
&& first.attr("href").equals("#" + main.id());
|
||||
if (!skip) {
|
||||
out.add(where + ": the first link in the body is not a skip link to <main>");
|
||||
}
|
||||
Element menu = doc.selectFirst(".rw-topbar #navbar-menu");
|
||||
if (menu == null || menu.closest("nav") == null || !ariaNamed(doc, menu.closest("nav"))) {
|
||||
out.add(where + ": the topbar menu is not inside a named <nav>");
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
private static boolean hidden(Element e) {
|
||||
for (Element cur = e; cur != null; cur = cur.parent()) {
|
||||
if ("true".equals(cur.attr("aria-hidden"))) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private static boolean controlHasName(Document doc, Element control) {
|
||||
if (ariaNamed(doc, control)) {
|
||||
return true;
|
||||
}
|
||||
if (control.closest("label") != null) {
|
||||
return true;
|
||||
}
|
||||
String id = control.id();
|
||||
return !id.isEmpty() && !doc.select("label[for]").stream().filter(l -> l.attr("for").equals(id))
|
||||
.toList().isEmpty();
|
||||
}
|
||||
|
||||
private static boolean ariaNamed(Document doc, Element e) {
|
||||
if (!e.attr("aria-label").isBlank()) {
|
||||
return true;
|
||||
}
|
||||
String by = e.attr("aria-labelledby").trim();
|
||||
if (by.isEmpty()) {
|
||||
return false;
|
||||
}
|
||||
for (String id : by.split("\\s+")) {
|
||||
if (doc.getElementById(id) == null) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
private static boolean hasText(Element e) {
|
||||
if (!e.text().isBlank()) {
|
||||
return true;
|
||||
}
|
||||
return e.select("img[alt]").stream().anyMatch(img -> !img.attr("alt").isBlank());
|
||||
}
|
||||
|
||||
private static String describe(Element e) {
|
||||
String outer = e.outerHtml().replaceAll("\\s+", " ");
|
||||
return outer.length() > 160 ? outer.substring(0, 160) + "…" : outer;
|
||||
}
|
||||
}
|
||||
+57
@@ -0,0 +1,57 @@
|
||||
package mx.quest.protection;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import mx.quest.runway.plugin.PluginDescriptor;
|
||||
import mx.quest.runway.plugin.PluginVersion;
|
||||
import mx.quest.runway.spi.RunwaySpi;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
/**
|
||||
* The shipped descriptor declares the SPI floor the plugin's code actually needs.
|
||||
*
|
||||
* <h2>Why</h2>
|
||||
* The installer (on every upgrade since 1.0.0-rc1; before that with {@code --update-essential-plugins}) replaces the
|
||||
* protection jar in the version-independent
|
||||
* {@code external/plugins/protection/}, so after an upgrade the jar outlives the kernel it came with: a rollback
|
||||
* is a symlink flip that puts an older kernel in front of the newer jar. From 1.5.0 the plugin links
|
||||
* {@code spi.service.RequestContext} (SPI 0.5.0) and {@code spi.service.ConsoleScreen} (SPI 0.6.0). A kernel
|
||||
* without them registered the plugin and then failed to start with {@code NoClassDefFoundError: …RequestContext}
|
||||
* — the essential plugin, so nothing came up, and nothing named the plugin. The {@code requiresSpi} floor makes
|
||||
* every kernel since 0.5.0-beta10 refuse it with a reason instead.
|
||||
*/
|
||||
class DescriptorSpiFloorTest {
|
||||
|
||||
/** The highest SPI level whose types the plugin's code links today. Raise it with the code. */
|
||||
private static final PluginVersion NEEDED = PluginVersion.parse("0.6.0");
|
||||
|
||||
private static PluginDescriptor descriptor() throws IOException {
|
||||
try (InputStream in = Files.newInputStream(Path.of("plugin.yml"))) {
|
||||
PluginDescriptor descriptor = PluginDescriptor.read(in);
|
||||
descriptor.validate();
|
||||
return descriptor;
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void theDescriptorDeclaresAFloorCoveringTheSpiTypesTheCodeLinks() throws IOException {
|
||||
PluginVersion floor = descriptor().spiFloor();
|
||||
assertNotNull(floor, "plugin.yml must declare requiresSpi — without it an older kernel registers the jar "
|
||||
+ "and then dies on a NoClassDefFoundError");
|
||||
assertTrue(floor.compareTo(NEEDED) >= 0, "requiresSpi " + floor + " is below " + NEEDED
|
||||
+ ", the level of the newest SPI type the plugin links");
|
||||
}
|
||||
|
||||
@Test
|
||||
void theFloorIsSatisfiedByTheSpiThePluginIsBuiltAndShippedWith() throws IOException {
|
||||
PluginVersion floor = descriptor().spiFloor();
|
||||
PluginVersion built = PluginVersion.parse(RunwaySpi.VERSION);
|
||||
assertTrue(floor.compareTo(built) <= 0, "requiresSpi " + floor + " is above this kernel's SPI " + built
|
||||
+ ": the essential plugin would be refused by the kernel it ships with (fail-closed 503)");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,193 @@
|
||||
package mx.quest.protection;
|
||||
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.when;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
|
||||
|
||||
import java.nio.file.Path;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import mx.quest.runway.authz.AuthorizationService;
|
||||
import mx.quest.runway.authz.AuthzExpressions;
|
||||
import mx.quest.runway.authz.Permission;
|
||||
import mx.quest.runway.authz.PermissionCatalog;
|
||||
import mx.quest.runway.security.RunwayUserDetails;
|
||||
import mx.quest.runway.security.User;
|
||||
import mx.quest.runway.site.Site;
|
||||
import mx.quest.runway.site.SiteResolver;
|
||||
import mx.quest.runway.spi.model.Realm;
|
||||
import mx.quest.runway.storage.YamlStore;
|
||||
import mx.quest.runway.web.CidrSet;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
|
||||
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
|
||||
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
|
||||
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
import org.springframework.security.web.SecurityFilterChain;
|
||||
import org.springframework.test.context.junit.jupiter.web.SpringJUnitWebConfig;
|
||||
import org.springframework.test.web.servlet.MockMvc;
|
||||
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
|
||||
import org.springframework.web.context.WebApplicationContext;
|
||||
|
||||
/**
|
||||
* The DoS screen is gated on the plugin's own {@code protection|settings} control point (app realm): a principal
|
||||
* who fails the check is denied on GET and on both POSTs; one who passes reaches the controller (a {@code 3xx}
|
||||
* redirect). Proves the gate is wired and that block/unblock are reachable when authorized.
|
||||
*/
|
||||
@SpringJUnitWebConfig(DosScreenGatingTest.Config.class)
|
||||
class DosScreenGatingTest {
|
||||
|
||||
private static final Permission APP_SETTINGS = new Permission("protection|settings", Realm.APPLICATION);
|
||||
|
||||
@Autowired
|
||||
private WebApplicationContext context;
|
||||
@Autowired
|
||||
private AuthorizationService authorization;
|
||||
|
||||
private MockMvc mvc;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
mvc = MockMvcBuilders.webAppContextSetup(context).build();
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void clearContext() {
|
||||
SecurityContextHolder.clearContext();
|
||||
}
|
||||
|
||||
private static void signIn() {
|
||||
User user = new User("op1", "op", "", "Op", "", true, false, Realm.APPLICATION, Set.of(), List.of());
|
||||
RunwayUserDetails details = new RunwayUserDetails(user);
|
||||
SecurityContextHolder.getContext().setAuthentication(
|
||||
new UsernamePasswordAuthenticationToken(details, "n/a", details.getAuthorities()));
|
||||
}
|
||||
|
||||
private static void assertDenied(org.junit.jupiter.api.function.Executable action) {
|
||||
Throwable thrown = org.junit.jupiter.api.Assertions.assertThrows(Throwable.class, action);
|
||||
for (Throwable t = thrown; t != null; t = t.getCause()) {
|
||||
if (t instanceof org.springframework.security.authorization.AuthorizationDeniedException) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
org.junit.jupiter.api.Assertions.fail("expected an AuthorizationDeniedException, got: " + thrown);
|
||||
}
|
||||
|
||||
@Test
|
||||
void theScreenForbidsAPrincipalWithoutTheControlPoint() {
|
||||
signIn();
|
||||
when(authorization.mayAccess(any(), eq(APP_SETTINGS), any())).thenReturn(false);
|
||||
assertDenied(() -> mvc.perform(get("/__app/dos")));
|
||||
assertDenied(() -> mvc.perform(post("/__app/dos/block").param("ip", "203.0.113.7")));
|
||||
assertDenied(() -> mvc.perform(post("/__app/dos/unblock").param("ip", "203.0.113.7")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aManualBlockAndUnblockRoundTripWhenAuthorized() throws Exception {
|
||||
signIn();
|
||||
when(authorization.mayAccess(any(), eq(APP_SETTINGS), any())).thenReturn(true);
|
||||
|
||||
IpBlocklist blocklist = context.getBean(IpBlocklist.class);
|
||||
|
||||
mvc.perform(post("/__app/dos/block").param("ip", "203.0.113.7").param("seconds", "900")
|
||||
.param("reason", "abuse").with(r -> { r.setRemoteAddr("10.9.9.9"); return r; }))
|
||||
.andExpect(status().is3xxRedirection());
|
||||
org.junit.jupiter.api.Assertions.assertTrue(blocklist.isBlocked("203.0.113.7"),
|
||||
"the authorized block reached the controller and blocked the IP");
|
||||
|
||||
mvc.perform(post("/__app/dos/unblock").param("ip", "203.0.113.7"))
|
||||
.andExpect(status().is3xxRedirection());
|
||||
org.junit.jupiter.api.Assertions.assertFalse(blocklist.isBlocked("203.0.113.7"),
|
||||
"the authorized unblock removed the IP");
|
||||
}
|
||||
|
||||
@Test
|
||||
void blockingYourOwnGatedIpIsRefused() throws Exception {
|
||||
signIn();
|
||||
when(authorization.mayAccess(any(), eq(APP_SETTINGS), any())).thenReturn(true);
|
||||
IpBlocklist blocklist = context.getBean(IpBlocklist.class);
|
||||
|
||||
mvc.perform(post("/__app/dos/block").param("ip", "10.9.9.9")
|
||||
.with(r -> { r.setRemoteAddr("10.9.9.9"); return r; }))
|
||||
.andExpect(status().is3xxRedirection());
|
||||
org.junit.jupiter.api.Assertions.assertFalse(blocklist.isBlocked("10.9.9.9"),
|
||||
"the controller refuses to block the operator's own address");
|
||||
}
|
||||
|
||||
/** A minimal web context: method security on, permit-all chain, the authz expression, the DoS controller. */
|
||||
@Configuration
|
||||
@org.springframework.web.servlet.config.annotation.EnableWebMvc
|
||||
@EnableWebSecurity
|
||||
@EnableMethodSecurity
|
||||
static class Config {
|
||||
|
||||
@Bean
|
||||
SecurityFilterChain chain(HttpSecurity http) throws Exception {
|
||||
http.csrf(c -> c.disable()).authorizeHttpRequests(a -> a.anyRequest().permitAll());
|
||||
return http.build();
|
||||
}
|
||||
|
||||
@Bean
|
||||
AuthorizationService authorizationService() {
|
||||
return mock(AuthorizationService.class);
|
||||
}
|
||||
|
||||
@Bean
|
||||
PermissionCatalog permissionCatalog() {
|
||||
PermissionCatalog catalog = mock(PermissionCatalog.class);
|
||||
when(catalog.find("protection|settings")).thenReturn(Optional.of(APP_SETTINGS));
|
||||
return catalog;
|
||||
}
|
||||
|
||||
@Bean
|
||||
SiteResolver siteResolver() {
|
||||
Site site = mock(Site.class);
|
||||
when(site.id()).thenReturn("acme");
|
||||
SiteResolver resolver = mock(SiteResolver.class);
|
||||
when(resolver.current()).thenReturn(Optional.of(site));
|
||||
return resolver;
|
||||
}
|
||||
|
||||
@Bean("authz")
|
||||
AuthzExpressions authz(AuthorizationService authz, PermissionCatalog catalog, SiteResolver siteResolver) {
|
||||
return new AuthzExpressions(authz, catalog, siteResolver);
|
||||
}
|
||||
|
||||
@Bean
|
||||
IpBlocklist blocklist() {
|
||||
Path file = Path.of(System.getProperty("java.io.tmpdir"),
|
||||
"runway-dos-gating-" + System.nanoTime() + ".yml");
|
||||
return new IpBlocklist(file, new YamlStore(), CidrSet.of(List.of()),
|
||||
() -> System.currentTimeMillis() / 1000L);
|
||||
}
|
||||
|
||||
@Bean
|
||||
TokenBucketRateLimiter limiter(IpBlocklist blocklist) {
|
||||
return new TokenBucketRateLimiter(120, 2.0, 1_000, () -> 0L, blocklist,
|
||||
new TokenBucketRateLimiter.AutoBlock(false, 60, 60, 900), () -> 0L);
|
||||
}
|
||||
|
||||
@Bean
|
||||
DosController dosController(TokenBucketRateLimiter limiter, IpBlocklist blocklist,
|
||||
@org.springframework.beans.factory.annotation.Qualifier("operatorAwareMessageSource")
|
||||
org.springframework.context.MessageSource messages) {
|
||||
return new DosController(limiter, blocklist, messages);
|
||||
}
|
||||
|
||||
@Bean("operatorAwareMessageSource")
|
||||
org.springframework.context.MessageSource messages() {
|
||||
return new org.springframework.context.support.StaticMessageSource();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,233 @@
|
||||
package mx.quest.protection;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Set;
|
||||
import mx.quest.runway.authz.AuthorizationService;
|
||||
import mx.quest.runway.authz.PermissionCatalog;
|
||||
import mx.quest.runway.console.MenuRegistry;
|
||||
import mx.quest.runway.console.OperatorProperties;
|
||||
import mx.quest.runway.console.OperatorShellModel;
|
||||
import mx.quest.runway.console.PluginTemplateResolver;
|
||||
import mx.quest.runway.plugin.LoadedPlugin;
|
||||
import mx.quest.runway.plugin.PluginDescriptor;
|
||||
import mx.quest.runway.plugin.RunningPlugins;
|
||||
import mx.quest.runway.site.SiteResolver;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.Mockito;
|
||||
import org.springframework.context.support.ReloadableResourceBundleMessageSource;
|
||||
import org.springframework.context.support.StaticApplicationContext;
|
||||
import org.springframework.core.convert.support.DefaultConversionService;
|
||||
import org.springframework.mock.web.MockHttpServletRequest;
|
||||
import org.springframework.mock.web.MockHttpServletResponse;
|
||||
import org.springframework.mock.web.MockServletContext;
|
||||
import org.springframework.ui.Model;
|
||||
import org.springframework.validation.support.BindingAwareModelMap;
|
||||
import org.springframework.web.context.request.RequestContextHolder;
|
||||
import org.springframework.web.context.request.ServletRequestAttributes;
|
||||
import org.thymeleaf.context.IContext;
|
||||
import org.thymeleaf.context.WebContext;
|
||||
import org.thymeleaf.spring6.SpringTemplateEngine;
|
||||
import org.thymeleaf.spring6.expression.ThymeleafEvaluationContext;
|
||||
import org.thymeleaf.templatemode.TemplateMode;
|
||||
import org.thymeleaf.templateresolver.ClassLoaderTemplateResolver;
|
||||
import org.thymeleaf.web.IWebExchange;
|
||||
import org.thymeleaf.web.servlet.JakartaServletWebApplication;
|
||||
|
||||
/**
|
||||
* The DoS screen renders inside the kernel {@code op-layout} shell with the app topbar (the reusable 1c seam),
|
||||
* with the plugin's own i18n resolving its {@code #{dos.*}} labels, the manual-block form present, and repeated
|
||||
* blocklist + offender rows populated. It never renders a secret (there is none on this screen).
|
||||
*/
|
||||
class DosScreenRenderTest {
|
||||
|
||||
/** The plugin project root (where templates/ + i18n/ live) — the CWD when the module's tests run. */
|
||||
private static final Path PLUGIN_ROOT = Path.of(System.getProperty("user.dir"));
|
||||
|
||||
@AfterEach
|
||||
void clearRequest() {
|
||||
RequestContextHolder.resetRequestAttributes();
|
||||
}
|
||||
|
||||
private static PluginDescriptor descriptor() throws IOException {
|
||||
try (InputStream in = Files.newInputStream(PLUGIN_ROOT.resolve("plugin.yml"))) {
|
||||
return PluginDescriptor.read(in);
|
||||
}
|
||||
}
|
||||
|
||||
private static SpringTemplateEngine engine(RunningPlugins running) {
|
||||
ClassLoaderTemplateResolver operator = new ClassLoaderTemplateResolver();
|
||||
operator.setPrefix("templates/");
|
||||
operator.setSuffix(".html");
|
||||
operator.setResolvablePatterns(Set.of("operator/*"));
|
||||
operator.setTemplateMode(TemplateMode.HTML);
|
||||
operator.setUseDecoupledLogic(true);
|
||||
operator.setCacheable(false);
|
||||
operator.setOrder(2);
|
||||
|
||||
PluginTemplateResolver plugin = new PluginTemplateResolver(running);
|
||||
plugin.setCacheable(false);
|
||||
|
||||
ReloadableResourceBundleMessageSource messages = new ReloadableResourceBundleMessageSource();
|
||||
messages.setBasenames("classpath:i18n/operator-messages",
|
||||
"file:" + PLUGIN_ROOT.resolve("i18n").resolve("messages"));
|
||||
messages.setDefaultEncoding("UTF-8");
|
||||
messages.setUseCodeAsDefaultMessage(true);
|
||||
// As in production (OperatorMessageSource): no fallback to the HOST's locale. Without this the English
|
||||
// render resolved Spanish on a workstation whose LANG is es_MX — a test that passed or failed by machine.
|
||||
messages.setFallbackToSystemLocale(false);
|
||||
|
||||
SpringTemplateEngine engine = new SpringTemplateEngine();
|
||||
engine.addTemplateResolver(operator);
|
||||
engine.addTemplateResolver(plugin);
|
||||
engine.setTemplateEngineMessageSource(messages);
|
||||
return engine;
|
||||
}
|
||||
|
||||
private static RunningPlugins runningWithProtection() throws IOException {
|
||||
LoadedPlugin loaded = new LoadedPlugin(descriptor(), PLUGIN_ROOT);
|
||||
RunningPlugins running = Mockito.mock(RunningPlugins.class);
|
||||
Mockito.when(running.installed()).thenReturn(List.of(loaded));
|
||||
return running;
|
||||
}
|
||||
|
||||
private static OperatorShellModel shellModel(RunningPlugins running, SiteResolver siteResolver) {
|
||||
AuthorizationService authz = Mockito.mock(AuthorizationService.class);
|
||||
PermissionCatalog catalog = Mockito.mock(PermissionCatalog.class);
|
||||
MenuRegistry menu = new MenuRegistry(running, authz, catalog);
|
||||
mx.quest.runway.crypto.SecretCipher cipher = Mockito.mock(mx.quest.runway.crypto.SecretCipher.class);
|
||||
Mockito.when(cipher.isAvailable()).thenReturn(true);
|
||||
mx.quest.runway.mail.PlatformMailer mailer = Mockito.mock(mx.quest.runway.mail.PlatformMailer.class);
|
||||
Mockito.when(mailer.isConfigured()).thenReturn(true);
|
||||
@SuppressWarnings("unchecked")
|
||||
org.springframework.beans.factory.ObjectProvider<org.springframework.boot.info.BuildProperties> buildProps =
|
||||
Mockito.mock(org.springframework.beans.factory.ObjectProvider.class);
|
||||
return new OperatorShellModel(menu, siteResolver, new OperatorProperties(), cipher, mailer, buildProps);
|
||||
}
|
||||
|
||||
private String render(List<DosController.OffenderRow> offenders, List<DosController.BlockRow> blocks)
|
||||
throws IOException {
|
||||
return render(offenders, blocks, List.of());
|
||||
}
|
||||
|
||||
private String render(List<DosController.OffenderRow> offenders, List<DosController.BlockRow> blocks,
|
||||
List<DosController.EndedRow> ended) throws IOException {
|
||||
RunningPlugins running = runningWithProtection();
|
||||
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/__app/dos");
|
||||
request.setRequestURI("/__app/dos");
|
||||
RequestContextHolder.setRequestAttributes(new ServletRequestAttributes(request));
|
||||
|
||||
SiteResolver siteResolver = Mockito.mock(SiteResolver.class);
|
||||
Model model = new BindingAwareModelMap();
|
||||
shellModel(running, siteResolver).populate(model, request, null);
|
||||
model.addAttribute("offenders", offenders);
|
||||
model.addAttribute("blocks", blocks);
|
||||
model.addAttribute("ended", ended);
|
||||
model.addAttribute("contentTemplate", "__plugin__/protection/app-dos");
|
||||
model.addAttribute("pageTitleKey", "dos.screen.title");
|
||||
|
||||
IContext ctx = webContext(request, model);
|
||||
return engine(running).process("operator/op-layout", ctx);
|
||||
}
|
||||
|
||||
private static IContext webContext(MockHttpServletRequest request, Model model) {
|
||||
MockServletContext servletContext = new MockServletContext();
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
JakartaServletWebApplication application = JakartaServletWebApplication.buildApplication(servletContext);
|
||||
IWebExchange exchange = application.buildExchange(request, response);
|
||||
WebContext ctx = new WebContext(exchange, Locale.ENGLISH);
|
||||
model.asMap().forEach(ctx::setVariable);
|
||||
StaticApplicationContext appContext = new StaticApplicationContext();
|
||||
appContext.refresh();
|
||||
ctx.setVariable(ThymeleafEvaluationContext.THYMELEAF_EVALUATION_CONTEXT_CONTEXT_VARIABLE_NAME,
|
||||
new ThymeleafEvaluationContext(appContext, DefaultConversionService.getSharedInstance()));
|
||||
return ctx;
|
||||
}
|
||||
|
||||
@Test
|
||||
void theScreenRendersInsideOpLayoutWithTheAppChromeAndTheBlockForm() throws IOException {
|
||||
String html = render(List.of(), List.of());
|
||||
|
||||
assertTrue(html.contains("rw-topbar-app"), "the DoS screen renders inside op-layout with the app topbar");
|
||||
assertFalse(html.contains("rw-topbar-admin"));
|
||||
assertTrue(html.contains("action=\"/__app/dos/block\""), "the manual-block form is present");
|
||||
assertTrue(html.contains("DoS activity"), "plugin i18n label resolved (dos.screen.heading)");
|
||||
assertFalse(html.contains("dos.screen.heading"), "the raw plugin i18n key must not leak");
|
||||
// Empty-state messages show when the lists are empty.
|
||||
assertTrue(html.contains("No addresses are currently blocked."));
|
||||
}
|
||||
|
||||
/**
|
||||
* The DoS screen passes the console's structural accessibility audit with TWO rows in every table, so a
|
||||
* repeated row id (the template's selector anchor) or an unnamed control would show up here.
|
||||
*/
|
||||
@Test
|
||||
void theScreenPassesTheConsoleAccessibilityAuditWithRepeatedRows() throws IOException {
|
||||
String html = render(
|
||||
List.of(new DosController.OffenderRow("198.51.100.9", 500, 42, true),
|
||||
new DosController.OffenderRow("198.51.100.10", 300, 7, false)),
|
||||
List.of(new DosController.BlockRow("203.0.113.7", "abuse", "manual", "2026-07-08 12:00", true),
|
||||
new DosController.BlockRow("203.0.113.8", "abuse", "auto", "2026-07-08 12:05", true)),
|
||||
List.of(new DosController.EndedRow("198.51.100.4", "auto", "auto", "2026-08-20 15:04"),
|
||||
new DosController.EndedRow("198.51.100.5", "auto", "auto", "2026-08-20 15:09")));
|
||||
java.util.List<String> problems = ConsoleA11yAudit.audit("/__app/dos", html);
|
||||
assertTrue(problems.isEmpty(), String.join("\n", problems));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aBlockedEntryAndAnOffenderRowRender() throws IOException {
|
||||
DosController.BlockRow block = new DosController.BlockRow(
|
||||
"203.0.113.7", "abuse", "manual", "2026-07-08 12:00", true);
|
||||
DosController.OffenderRow offender = new DosController.OffenderRow("198.51.100.9", 500, 42, true);
|
||||
|
||||
String html = render(List.of(offender), List.of(block));
|
||||
|
||||
assertTrue(html.contains("203.0.113.7"), "the blocked IP renders");
|
||||
assertTrue(html.contains("abuse"), "the block reason renders");
|
||||
assertTrue(html.contains("198.51.100.9"), "the offender IP renders");
|
||||
assertTrue(html.contains("42"), "the offender throttled count renders");
|
||||
// The per-row unblock form targets the unblock endpoint and carries the IP.
|
||||
assertTrue(html.contains("action=\"/__app/dos/unblock\""), "the per-row unblock form is present");
|
||||
}
|
||||
|
||||
/**
|
||||
* A block that has ended renders in its own table.
|
||||
*
|
||||
* <p>An auto-block lasts fifteen minutes by default, so an operator asking "was the guard doing anything
|
||||
* when the site was slow at three?" previously arrived to an empty blocklist with no way to tell. This is
|
||||
* the screen half of that fix, and it is asserted through a real render because a decoupled-logic
|
||||
* selector that matches nothing fails <b>silently</b> — the row would come out structurally correct and
|
||||
* completely blank.
|
||||
*/
|
||||
@Test
|
||||
void anEndedBlockRendersWithItsReasonAndTime() throws IOException {
|
||||
DosController.EndedRow ended = new DosController.EndedRow(
|
||||
"198.51.100.4", "auto: 60 breaches in 60s", "auto", "2026-08-20 15:04");
|
||||
|
||||
String html = render(List.of(), List.of(), List.of(ended));
|
||||
|
||||
assertTrue(html.contains("198.51.100.4"), "the address renders");
|
||||
assertTrue(html.contains("auto: 60 breaches in 60s"), "the reason is the part that answers the question");
|
||||
assertTrue(html.contains("2026-08-20 15:04"), "and when it ended");
|
||||
assertFalse(html.contains("No blocks have ended yet."), "the empty state must give way to the row");
|
||||
assertFalse(html.contains("dos.ended."), "no raw i18n key leaks: " + html.contains("dos.ended."));
|
||||
}
|
||||
|
||||
/** With nothing to show, the empty state explains that the list is in memory and clears on restart. */
|
||||
@Test
|
||||
void theEndedBlocksEmptyStateExplainsItself() throws IOException {
|
||||
String html = render(List.of(), List.of());
|
||||
|
||||
assertTrue(html.contains("No blocks have ended yet."));
|
||||
assertTrue(html.contains("empties on restart"),
|
||||
"an operator must not read an empty list as 'nothing was ever blocked'");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,279 @@
|
||||
package mx.quest.protection;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.atomic.AtomicLong;
|
||||
import mx.quest.runway.storage.YamlStore;
|
||||
import mx.quest.runway.web.CidrSet;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
|
||||
/**
|
||||
* The mutable blocklist's contract: manual blocks persist and round-trip across a fresh instance over the same
|
||||
* file; auto blocks are in-memory only (never written); loopback and the configured allowlist are unblockable;
|
||||
* expired entries prune lazily. All with an injectable clock so expiry is deterministic.
|
||||
*/
|
||||
class IpBlocklistTest {
|
||||
|
||||
@TempDir
|
||||
Path dir;
|
||||
|
||||
private final AtomicLong clock = new AtomicLong(1_000L); // epoch seconds
|
||||
|
||||
private IpBlocklist blocklist(CidrSet allowlist) {
|
||||
return new IpBlocklist(dir.resolve("blocklist.yml"), new YamlStore(), allowlist, clock::get);
|
||||
}
|
||||
|
||||
private IpBlocklist blocklist() {
|
||||
return blocklist(CidrSet.of(List.of()));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aManualBlockIsReportedBlockedAndUnblockRemovesIt() {
|
||||
IpBlocklist b = blocklist();
|
||||
assertTrue(b.block("203.0.113.7", 900, "abuse", true));
|
||||
assertTrue(b.isBlocked("203.0.113.7"));
|
||||
assertEquals(1, b.list().size());
|
||||
|
||||
b.unblock("203.0.113.7");
|
||||
assertFalse(b.isBlocked("203.0.113.7"));
|
||||
assertTrue(b.list().isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aManualBlockPersistsAndSurvivesAFreshInstanceOverTheSameFile() {
|
||||
IpBlocklist first = blocklist();
|
||||
first.block("198.51.100.4", 3_600, "manual ban", true);
|
||||
assertTrue(Files.isRegularFile(dir.resolve("blocklist.yml")), "manual block wrote the file");
|
||||
|
||||
// A fresh instance over the same file (same not-yet-advanced clock) re-reads the persisted manual block.
|
||||
IpBlocklist reloaded = blocklist();
|
||||
assertTrue(reloaded.isBlocked("198.51.100.4"), "the persisted manual block survived a restart");
|
||||
assertEquals("manual ban", reloaded.list().get(0).reason());
|
||||
assertTrue(reloaded.list().get(0).manual());
|
||||
}
|
||||
|
||||
@Test
|
||||
void unblockingAManualEntryRewritesTheFileSoItDoesNotComeBack() {
|
||||
IpBlocklist first = blocklist();
|
||||
first.block("198.51.100.4", 3_600, "x", true);
|
||||
first.unblock("198.51.100.4");
|
||||
|
||||
IpBlocklist reloaded = blocklist();
|
||||
assertFalse(reloaded.isBlocked("198.51.100.4"), "unblock rewrote the file — the entry does not resurrect");
|
||||
}
|
||||
|
||||
@Test
|
||||
void anAutoBlockIsInMemoryOnlyAndIsNeverWrittenToTheFile() throws IOException {
|
||||
IpBlocklist b = blocklist();
|
||||
assertTrue(b.block("192.0.2.9", 900, "auto: rate-limit", false));
|
||||
assertTrue(b.isBlocked("192.0.2.9"), "the auto block is live in memory");
|
||||
|
||||
Path file = dir.resolve("blocklist.yml");
|
||||
if (Files.isRegularFile(file)) {
|
||||
String yaml = Files.readString(file);
|
||||
assertFalse(yaml.contains("192.0.2.9"), "an auto block must NEVER be persisted");
|
||||
}
|
||||
// And a fresh instance does not see it (it was never on disk).
|
||||
assertFalse(blocklist().isBlocked("192.0.2.9"), "an auto block does not survive a restart");
|
||||
}
|
||||
|
||||
@Test
|
||||
void loopbackIsAlwaysAllowlistedAndNeverBlockable() {
|
||||
IpBlocklist b = blocklist();
|
||||
assertTrue(b.isAllowlisted("127.0.0.1"));
|
||||
assertTrue(b.isAllowlisted("::1"));
|
||||
assertFalse(b.block("127.0.0.1", 900, "nope", true), "loopback is refused (unblockable)");
|
||||
assertFalse(b.isBlocked("127.0.0.1"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aConfiguredAllowlistedIpIsNeverBlockable() {
|
||||
IpBlocklist b = blocklist(CidrSet.of(List.of("10.0.0.0/8")));
|
||||
assertTrue(b.isAllowlisted("10.1.2.3"));
|
||||
assertFalse(b.block("10.1.2.3", 900, "nope", true), "an allowlisted IP is refused (manual)");
|
||||
assertFalse(b.block("10.1.2.3", 900, "auto", false), "an allowlisted IP is refused (auto too)");
|
||||
assertFalse(b.isBlocked("10.1.2.3"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void anExpiredEntryPrunesLazilyOnTheNextCheck() {
|
||||
IpBlocklist b = blocklist();
|
||||
b.block("203.0.113.50", 60, "temp", true); // until = 1000 + 60 = 1060
|
||||
assertTrue(b.isBlocked("203.0.113.50"));
|
||||
|
||||
clock.set(1_100L); // past the expiry
|
||||
assertFalse(b.isBlocked("203.0.113.50"), "an expired block is pruned on the next check");
|
||||
assertTrue(b.list().isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void anIndefiniteBlockNeverExpires() {
|
||||
IpBlocklist b = blocklist();
|
||||
b.block("203.0.113.99", 0, "forever", true); // 0 seconds = indefinite
|
||||
clock.set(Long.MAX_VALUE / 2);
|
||||
assertTrue(b.isBlocked("203.0.113.99"), "an indefinite block never lapses");
|
||||
assertTrue(b.list().get(0).indefinite());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aCidrBlockMatchesEveryAddressInTheRange() {
|
||||
IpBlocklist b = blocklist();
|
||||
b.block("203.0.113.0/24", 900, "range ban", true);
|
||||
assertTrue(b.isBlocked("203.0.113.1"));
|
||||
assertTrue(b.isBlocked("203.0.113.254"));
|
||||
assertFalse(b.isBlocked("203.0.114.1"), "an address outside the range is not blocked");
|
||||
}
|
||||
|
||||
@Test
|
||||
void aMalformedFileFailsSoftToAnEmptyBlocklist() throws IOException {
|
||||
Files.writeString(dir.resolve("blocklist.yml"), "this: is: not: a: valid: blocklist: [[[");
|
||||
IpBlocklist b = blocklist(); // must not throw at construction
|
||||
assertTrue(b.list().isEmpty(), "a corrupt file degrades to an empty blocklist (fail-soft)");
|
||||
// And it still works after the bad load.
|
||||
assertTrue(b.block("192.0.2.1", 900, "ok", true));
|
||||
assertTrue(b.isBlocked("192.0.2.1"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void anAlreadyExpiredPersistedEntryIsDroppedOnLoad() {
|
||||
IpBlocklist first = blocklist();
|
||||
first.block("192.0.2.7", 60, "temp", true); // until 1060
|
||||
clock.set(2_000L); // both instances now see it as expired
|
||||
IpBlocklist reloaded = blocklist();
|
||||
assertFalse(reloaded.isBlocked("192.0.2.7"), "an expired persisted entry is dropped on load");
|
||||
}
|
||||
|
||||
/**
|
||||
* A bare {@code 403} is not diagnosable: an operator ban and a system auto-escalation look identical on the
|
||||
* wire but call for opposite responses — investigate the client, versus check whether your own thresholds
|
||||
* are too tight. {@code blockKind} is what lets the rejection log and the metric tell them apart.
|
||||
*/
|
||||
@Test
|
||||
void blockKindDistinguishesManualFromAutoFromCidr() {
|
||||
IpBlocklist blocklist = blocklist();
|
||||
blocklist.block("203.0.113.10", 60, "operator ban", true);
|
||||
blocklist.block("203.0.113.11", 60, "escalated", false);
|
||||
blocklist.block("198.51.100.0/24", 60, "range", true);
|
||||
|
||||
assertEquals("blocklist-manual", blocklist.blockKind("203.0.113.10"));
|
||||
assertEquals("blocklist-auto", blocklist.blockKind("203.0.113.11"));
|
||||
assertEquals("blocklist-cidr", blocklist.blockKind("198.51.100.7"));
|
||||
assertNull(blocklist.blockKind("203.0.113.99"), "an unblocked address has no kind");
|
||||
}
|
||||
|
||||
/**
|
||||
* {@code isBlocked} delegates to {@code blockKind}, so the two can never drift — the fail-open contract, the
|
||||
* allowlist precedence and the lazy prune all live in one implementation. Asserted across every shape,
|
||||
* because a second copy of this logic is exactly how a security check and its diagnostic disagree.
|
||||
*/
|
||||
@Test
|
||||
void isBlockedAndBlockKindAlwaysAgree() {
|
||||
IpBlocklist blocklist = blocklist();
|
||||
blocklist.block("203.0.113.20", 60, "manual", true);
|
||||
blocklist.block("203.0.113.21", 60, "auto", false);
|
||||
blocklist.block("198.51.100.0/24", 60, "range", true);
|
||||
|
||||
for (String ip : new String[] {"203.0.113.20", "203.0.113.21", "198.51.100.5", "203.0.113.99",
|
||||
"127.0.0.1", "", " "}) {
|
||||
assertEquals(blocklist.isBlocked(ip), blocklist.blockKind(ip) != null,
|
||||
"isBlocked and blockKind disagree for: " + ip);
|
||||
}
|
||||
assertNull(blocklist.blockKind(null));
|
||||
}
|
||||
|
||||
/** An allowlisted address is never blocked, so it must report no kind either — not "blocked but allowed". */
|
||||
@Test
|
||||
void anAllowlistedAddressReportsNoBlockKind() {
|
||||
IpBlocklist blocklist = blocklist();
|
||||
blocklist.block("127.0.0.1", 60, "attempt", true);
|
||||
|
||||
assertNull(blocklist.blockKind("127.0.0.1"));
|
||||
assertEquals(false, blocklist.isBlocked("127.0.0.1"));
|
||||
}
|
||||
|
||||
// ---- a block that ends must leave a trace ---------------------------------------------------
|
||||
|
||||
/**
|
||||
* An expired block appears in the history.
|
||||
*
|
||||
* <p>The default auto-block lasts fifteen minutes, so an operator asking "was the guard doing anything
|
||||
* when the site was slow at three?" arrives to an empty blocklist and cannot tell whether it acted at all
|
||||
* — the evidence deleted itself at exactly the rate that makes it hardest to catch.
|
||||
*
|
||||
* <p>Expiry is lazy, so the trace is written when something looks; {@code list()} is what looks.
|
||||
*/
|
||||
@Test
|
||||
void anExpiredBlockIsRememberedWithItsReason(@TempDir Path dir) {
|
||||
long[] now = {1_000L};
|
||||
IpBlocklist blocklist = new IpBlocklist(dir.resolve("b.yml"), new YamlStore(), CidrSet.of(List.of()),
|
||||
() -> now[0]);
|
||||
blocklist.block("198.51.100.4", 900, "auto: 60 breaches in 60s", false);
|
||||
|
||||
now[0] = 2_000L;
|
||||
blocklist.list(); // the lazy prune
|
||||
|
||||
List<IpBlocklist.Lapsed> ended = blocklist.recentlyEnded();
|
||||
assertEquals(1, ended.size());
|
||||
assertEquals("198.51.100.4", ended.get(0).ip());
|
||||
assertEquals("auto: 60 breaches in 60s", ended.get(0).reason(),
|
||||
"the reason is the whole point — the rejection counter already says a rejection happened");
|
||||
assertFalse(ended.get(0).manual());
|
||||
assertEquals(2_000L, ended.get(0).endedAt());
|
||||
}
|
||||
|
||||
/** An operator lifting a block is also an ending, and it is worth showing who did what. */
|
||||
@Test
|
||||
void anOperatorUnblockIsRecordedAsManual(@TempDir Path dir) {
|
||||
IpBlocklist blocklist = new IpBlocklist(dir.resolve("b.yml"), new YamlStore(), CidrSet.of(List.of()),
|
||||
() -> 1_000L);
|
||||
blocklist.block("203.0.113.7", 900, "banned by hand", true);
|
||||
|
||||
blocklist.unblock("203.0.113.7");
|
||||
|
||||
assertEquals(1, blocklist.recentlyEnded().size());
|
||||
assertTrue(blocklist.recentlyEnded().get(0).manual());
|
||||
}
|
||||
|
||||
/** A live block is not in the history — the two lists must never show the same address at once. */
|
||||
@Test
|
||||
void aBlockStillInForceIsNotInTheHistory(@TempDir Path dir) {
|
||||
IpBlocklist blocklist = new IpBlocklist(dir.resolve("b.yml"), new YamlStore(), CidrSet.of(List.of()),
|
||||
() -> 1_000L);
|
||||
blocklist.block("198.51.100.5", 900, "auto", false);
|
||||
|
||||
blocklist.list();
|
||||
|
||||
assertTrue(blocklist.recentlyEnded().isEmpty());
|
||||
}
|
||||
|
||||
/**
|
||||
* The history is bounded, newest first.
|
||||
*
|
||||
* <p>It runs during a flood, which is when an unbounded structure is most dangerous — and the addresses
|
||||
* in it are attacker-supplied. A diagnostic that answers "what happened recently" does not need, and must
|
||||
* not have, unbounded memory.
|
||||
*/
|
||||
@Test
|
||||
void theHistoryIsBoundedAndNewestFirst(@TempDir Path dir) {
|
||||
long[] now = {1_000L};
|
||||
IpBlocklist blocklist = new IpBlocklist(dir.resolve("b.yml"), new YamlStore(), CidrSet.of(List.of()),
|
||||
() -> now[0]);
|
||||
for (int i = 0; i < 150; i++) {
|
||||
blocklist.block("198.51.100." + (i % 250), 10, "auto " + i, false);
|
||||
now[0] += 20;
|
||||
blocklist.list(); // each one lapses before the next is applied
|
||||
}
|
||||
|
||||
List<IpBlocklist.Lapsed> ended = blocklist.recentlyEnded();
|
||||
assertEquals(100, ended.size(), "bounded");
|
||||
assertTrue(ended.get(0).endedAt() > ended.get(ended.size() - 1).endedAt(), "newest first");
|
||||
}
|
||||
}
|
||||
+254
@@ -0,0 +1,254 @@
|
||||
package mx.quest.protection;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
import jakarta.servlet.http.Cookie;
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Path;
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
import mx.quest.runway.crypto.AesGcmSecretCipher;
|
||||
import mx.quest.runway.crypto.SecretCipher;
|
||||
import mx.quest.runway.security.LoginFormGuard;
|
||||
import mx.quest.runway.security.LoginFormVerdict;
|
||||
import mx.quest.runway.security.ProtectionScope;
|
||||
import mx.quest.runway.security.RunwaySecurityProperties;
|
||||
import mx.quest.runway.storage.StorageLayout;
|
||||
import mx.quest.runway.storage.StorageProperties;
|
||||
import mx.quest.runway.storage.YamlStore;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.mock.web.MockHttpServletRequest;
|
||||
import org.springframework.mock.web.MockHttpServletResponse;
|
||||
|
||||
/**
|
||||
* The plugin's {@code @Primary} login form guard: it rejects a filled honeypot, and when a scope's captcha is
|
||||
* active it verifies the provider token (rejecting a missing/invalid one) while passing when captcha is inactive.
|
||||
* The captcha verifier is stubbed so the guard's policy — not the network — is under test.
|
||||
*/
|
||||
class LoginFormPolicyGuardTest {
|
||||
|
||||
private static SecretCipher passthroughCipher() {
|
||||
return new SecretCipher() {
|
||||
@Override public boolean isAvailable() { return true; }
|
||||
@Override public String encrypt(String plaintext) { return "ENC(" + plaintext + ")"; }
|
||||
@Override public String decrypt(String value) { return value; }
|
||||
@Override public boolean isEncrypted(String value) { return value != null && value.startsWith("ENC("); }
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* A trusted-device service with the feature OFF, so {@code isTrusted} is always false and the guard's captcha
|
||||
* path runs exactly as before. (These requests carry no trusted-device cookie anyway; the dedicated skip is
|
||||
* covered by {@link TrustedDeviceServiceTest}.)
|
||||
*/
|
||||
private static TrustedDeviceService td() {
|
||||
ProtectionProperties props = new ProtectionProperties();
|
||||
props.getRememberDevice().setEnabled(false);
|
||||
return new TrustedDeviceService(props, null, passthroughCipher());
|
||||
}
|
||||
|
||||
private static StorageLayout layout(Path root) {
|
||||
StorageProperties props = new StorageProperties();
|
||||
props.setExternal(root.resolve("external"));
|
||||
props.setSites(root.resolve("external").resolve("sites"));
|
||||
return StorageLayout.from(props);
|
||||
}
|
||||
|
||||
private static ProtectionConfigStore store(Path root, boolean appHoneypotEnabled) {
|
||||
ProtectionProperties props = new ProtectionProperties();
|
||||
props.getLogin().setHoneypotEnabled(appHoneypotEnabled);
|
||||
return new ProtectionConfigStore(props, layout(root), new YamlStore(), passthroughCipher());
|
||||
}
|
||||
|
||||
/** A verifier stub that records the token/ip it was called with and returns a fixed result. */
|
||||
private static final class StubVerifier extends CaptchaVerifier {
|
||||
boolean called;
|
||||
String seenToken;
|
||||
String seenIp;
|
||||
private final boolean result;
|
||||
|
||||
StubVerifier(boolean result) {
|
||||
super((url, body) -> { throw new AssertionError("the stub must not perform a real exchange"); });
|
||||
this.result = result;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean verify(ProtectionSettings.Captcha config, String token, String remoteIp) {
|
||||
this.called = true;
|
||||
this.seenToken = token;
|
||||
this.seenIp = remoteIp;
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
||||
private static MockHttpServletRequest post() {
|
||||
MockHttpServletRequest request = new MockHttpServletRequest("POST", "/app/login");
|
||||
request.setRemoteAddr("203.0.113.7");
|
||||
return request;
|
||||
}
|
||||
|
||||
private static ProtectionSettings.Captcha activeCaptcha(String provider) {
|
||||
return new ProtectionSettings.Captcha(true, provider, "SITEKEY", "SECRET", 0.5);
|
||||
}
|
||||
|
||||
// ---- honeypot ----------------------------------------------------------
|
||||
|
||||
@Test
|
||||
void aFilledTrapIsRejectedAsHoneypot(@TempDir Path root) {
|
||||
LoginFormPolicyGuard guard = new LoginFormPolicyGuard(store(root, true), new StubVerifier(true), td());
|
||||
MockHttpServletRequest req = post();
|
||||
req.addParameter(LoginFormGuard.HONEYPOT_FIELD, "http://spam.example");
|
||||
LoginFormVerdict verdict = guard.check(req, ProtectionScope.application());
|
||||
assertFalse(verdict.allowed(), "a non-blank trap is a bot");
|
||||
assertEquals(LoginFormVerdict.Reason.HONEYPOT, verdict.reason());
|
||||
assertEquals("error", verdict.redirectFlag(), "honeypot hides behind the generic ?error flag");
|
||||
}
|
||||
|
||||
@Test
|
||||
void anEmptyTrapPassesWhenCaptchaInactive(@TempDir Path root) {
|
||||
LoginFormPolicyGuard guard = new LoginFormPolicyGuard(store(root, true), new StubVerifier(true), td());
|
||||
assertTrue(guard.check(post(), ProtectionScope.application()).allowed(), "blank trap, no captcha → OK");
|
||||
}
|
||||
|
||||
@Test
|
||||
void theHoneypotShortCircuitsBeforeCaptcha(@TempDir Path root) throws IOException {
|
||||
// A filled trap is rejected as a honeypot even with captcha active — the verifier is never consulted.
|
||||
ProtectionConfigStore store = store(root, true);
|
||||
store.savePerSite("acme", new ProtectionSettings(true, 5, 300, 900, activeCaptcha("recaptcha-v2")));
|
||||
StubVerifier verifier = new StubVerifier(true);
|
||||
LoginFormPolicyGuard guard = new LoginFormPolicyGuard(store, verifier, td());
|
||||
MockHttpServletRequest req = post();
|
||||
req.addParameter(LoginFormGuard.HONEYPOT_FIELD, "bot");
|
||||
LoginFormVerdict verdict = guard.check(req, ProtectionScope.forSite("acme"));
|
||||
assertEquals(LoginFormVerdict.Reason.HONEYPOT, verdict.reason());
|
||||
assertFalse(verifier.called, "the honeypot rejects before the captcha check runs");
|
||||
}
|
||||
|
||||
// ---- captcha (active) --------------------------------------------------
|
||||
|
||||
@Test
|
||||
void anActiveCaptchaWithNoTokenIsRejected(@TempDir Path root) throws IOException {
|
||||
ProtectionConfigStore store = store(root, false); // honeypot off — isolate the captcha path
|
||||
store.savePerSite("acme", new ProtectionSettings(false, 5, 300, 900, activeCaptcha("recaptcha-v3")));
|
||||
StubVerifier verifier = new StubVerifier(false); // provider would reject a missing token
|
||||
LoginFormPolicyGuard guard = new LoginFormPolicyGuard(store, verifier, td());
|
||||
|
||||
LoginFormVerdict verdict = guard.check(post(), ProtectionScope.forSite("acme"));
|
||||
assertFalse(verdict.allowed(), "captcha active + no valid token → rejected");
|
||||
assertEquals(LoginFormVerdict.Reason.CAPTCHA, verdict.reason());
|
||||
assertEquals("captcha", verdict.redirectFlag(), "captcha maps to its own ?captcha flag");
|
||||
}
|
||||
|
||||
@Test
|
||||
void anActiveCaptchaReadsTheProviderTokenParamAndPasses(@TempDir Path root) throws IOException {
|
||||
ProtectionConfigStore store = store(root, false);
|
||||
store.savePerSite("acme", new ProtectionSettings(false, 5, 300, 900, activeCaptcha("recaptcha-v3")));
|
||||
StubVerifier verifier = new StubVerifier(true);
|
||||
LoginFormPolicyGuard guard = new LoginFormPolicyGuard(store, verifier, td());
|
||||
|
||||
MockHttpServletRequest req = post();
|
||||
req.addParameter("g-recaptcha-response", "the-token"); // reCAPTCHA's token param
|
||||
LoginFormVerdict verdict = guard.check(req, ProtectionScope.forSite("acme"));
|
||||
|
||||
assertTrue(verdict.allowed(), "a verifier-approved token passes");
|
||||
assertTrue(verifier.called);
|
||||
assertEquals("the-token", verifier.seenToken, "the guard reads the provider-specific token param");
|
||||
assertEquals("203.0.113.7", verifier.seenIp, "the gated client IP is passed to the verifier");
|
||||
}
|
||||
|
||||
@Test
|
||||
void anActiveCaptchaWithAnInvalidTokenIsRejected(@TempDir Path root) throws IOException {
|
||||
ProtectionConfigStore store = store(root, false);
|
||||
store.savePerSite("acme", new ProtectionSettings(false, 5, 300, 900, activeCaptcha("recaptcha-v2")));
|
||||
StubVerifier verifier = new StubVerifier(false); // provider rejects it
|
||||
LoginFormPolicyGuard guard = new LoginFormPolicyGuard(store, verifier, td());
|
||||
|
||||
MockHttpServletRequest req = post();
|
||||
req.addParameter("g-recaptcha-response", "bad-token");
|
||||
LoginFormVerdict verdict = guard.check(req, ProtectionScope.forSite("acme"));
|
||||
assertFalse(verdict.allowed());
|
||||
assertEquals(LoginFormVerdict.Reason.CAPTCHA, verdict.reason());
|
||||
}
|
||||
|
||||
// ---- captcha (inactive) ------------------------------------------------
|
||||
|
||||
// ---- trusted-device skip (login only) ----------------------------------
|
||||
|
||||
private static SecretCipher realCipher() {
|
||||
RunwaySecurityProperties security = new RunwaySecurityProperties();
|
||||
security.setSecretKey("guard-skip-test-master-key-0123456789");
|
||||
return new AesGcmSecretCipher(security);
|
||||
}
|
||||
|
||||
/** Mints a real trusted-device cookie for {@code scope} via the service's own issue path. */
|
||||
private static Cookie mint(TrustedDeviceService svc, ProtectionScope scope, String loginUri) {
|
||||
MockHttpServletRequest req = new MockHttpServletRequest("POST", loginUri);
|
||||
req.addParameter("remember-device", "1");
|
||||
MockHttpServletResponse res = new MockHttpServletResponse();
|
||||
svc.rememberIfRequested(req, res, scope);
|
||||
String header = res.getHeader(HttpHeaders.SET_COOKIE);
|
||||
String nameValue = header.substring(0, header.indexOf(';'));
|
||||
int eq = nameValue.indexOf('=');
|
||||
return new Cookie(nameValue.substring(0, eq), nameValue.substring(eq + 1));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aTrustedDeviceSkipsTheCaptchaOnLoginButNotOnForgotPassword(@TempDir Path root) throws IOException {
|
||||
SecretCipher cipher = realCipher();
|
||||
ProtectionConfigStore store = store(root, false); // honeypot off — isolate the captcha path
|
||||
store.savePerSite("acme", new ProtectionSettings(false, 5, 300, 900, activeCaptcha("recaptcha-v2")));
|
||||
TrustedDeviceService svc = new TrustedDeviceService(new ProtectionProperties(), store, cipher);
|
||||
ProtectionScope scope = ProtectionScope.forSite("acme");
|
||||
Cookie cookie = mint(svc, scope, "/login");
|
||||
|
||||
// On the LOGIN form: the trusted cookie skips the captcha — a verifier that would reject a missing token
|
||||
// is never even consulted, and the login is allowed.
|
||||
StubVerifier onLogin = new StubVerifier(false);
|
||||
MockHttpServletRequest loginPost = new MockHttpServletRequest("POST", "/login");
|
||||
loginPost.setCookies(cookie);
|
||||
LoginFormVerdict login = new LoginFormPolicyGuard(store, onLogin, svc).check(loginPost, scope);
|
||||
assertTrue(login.allowed(), "a trusted device is not challenged on the login form");
|
||||
assertFalse(onLogin.called, "…and the captcha verifier is never called for it");
|
||||
|
||||
// On the FORGOT-PASSWORD form: the SAME cookie does NOT skip the captcha (login-only narrowing).
|
||||
StubVerifier onForgot = new StubVerifier(false);
|
||||
MockHttpServletRequest forgotPost = new MockHttpServletRequest("POST", "/forgot-password");
|
||||
forgotPost.setCookies(cookie);
|
||||
LoginFormVerdict forgot = new LoginFormPolicyGuard(store, onForgot, svc).check(forgotPost, scope);
|
||||
assertFalse(forgot.allowed(), "the trusted cookie must NOT skip the recovery-form captcha");
|
||||
assertTrue(onForgot.called, "…the verifier IS consulted there (no token → rejected)");
|
||||
}
|
||||
|
||||
@Test
|
||||
void anInactiveCaptchaIsNotChallenged(@TempDir Path root) throws IOException {
|
||||
// enabled but keys blank → inactive → the verifier is never consulted and the login passes.
|
||||
ProtectionConfigStore store = store(root, false);
|
||||
ProtectionSettings.Captcha noKeys = new ProtectionSettings.Captcha(true, "recaptcha-v2", "", "", 0.5);
|
||||
store.savePerSite("acme", new ProtectionSettings(false, 5, 300, 900, noKeys));
|
||||
StubVerifier verifier = new StubVerifier(false);
|
||||
LoginFormPolicyGuard guard = new LoginFormPolicyGuard(store, verifier, td());
|
||||
|
||||
AtomicReference<LoginFormVerdict> verdict = new AtomicReference<>(
|
||||
guard.check(post(), ProtectionScope.forSite("acme")));
|
||||
assertTrue(verdict.get().allowed(), "captcha with no keys is inactive → no challenge");
|
||||
assertFalse(verifier.called, "an inactive captcha never calls the verifier");
|
||||
assertNull(verdict.get().reason());
|
||||
}
|
||||
|
||||
/** An encoded login path (/app/%6Cogin) is the login path as the dispatcher routes it, so the same rules apply. */
|
||||
@Test
|
||||
void theRoutedPathIsTheDecodedOne() {
|
||||
MockHttpServletRequest encoded = new MockHttpServletRequest("POST", "/app/%6Cogin");
|
||||
encoded.setServletPath("/app/login");
|
||||
assertEquals("/app/login", LoginFormPolicyGuard.routedPath(encoded));
|
||||
MockHttpServletRequest site = new MockHttpServletRequest("GET", "/l%6Fgin");
|
||||
site.setServletPath("/login");
|
||||
assertEquals("/login", LoginFormPolicyGuard.routedPath(site));
|
||||
// A bare request with no servlet path (some test shapes) falls back to the URI.
|
||||
assertEquals("/app/login", LoginFormPolicyGuard.routedPath(new MockHttpServletRequest("POST", "/app/login")));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
package mx.quest.protection;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.Reader;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Properties;
|
||||
import java.util.regex.Pattern;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
|
||||
/**
|
||||
* A message without arguments is printed verbatim, so it must not carry the MessageFormat apostrophe escape.
|
||||
*
|
||||
* <h2>Why</h2>
|
||||
* The kernel's message source runs a message through {@link java.text.MessageFormat} only when it is given
|
||||
* arguments. In a message with {@code {0}}, {@code ''} is a literal apostrophe; in one without, it reaches the page
|
||||
* as two. The per-site protection screen said "this site''s login" until 1.0.0 (reported from a live deployment).
|
||||
*/
|
||||
class MessageApostropheTest {
|
||||
|
||||
private static final Pattern ARGUMENT = Pattern.compile("\\{\\d");
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"i18n/messages.properties", "i18n/messages_es.properties"})
|
||||
void messagesWithoutArgumentsUseASingleApostrophe(String bundle) throws IOException {
|
||||
Properties messages = new Properties();
|
||||
try (Reader in = Files.newBufferedReader(Path.of(bundle), StandardCharsets.UTF_8)) {
|
||||
messages.load(in);
|
||||
}
|
||||
List<String> doubled = new ArrayList<>();
|
||||
messages.forEach((key, value) -> {
|
||||
String text = (String) value;
|
||||
if (!ARGUMENT.matcher(text).find() && text.contains("''")) {
|
||||
doubled.add(key + "=" + text);
|
||||
}
|
||||
});
|
||||
assertEquals(List.of(), doubled, bundle + ": these print '' verbatim");
|
||||
}
|
||||
}
|
||||
+138
@@ -0,0 +1,138 @@
|
||||
package mx.quest.protection;
|
||||
|
||||
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;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.Base64;
|
||||
import mx.quest.runway.crypto.SecretCipher;
|
||||
import mx.quest.runway.security.ProtectionScope;
|
||||
import mx.quest.runway.storage.StorageLayout;
|
||||
import mx.quest.runway.storage.StorageProperties;
|
||||
import mx.quest.runway.storage.YamlStore;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
|
||||
/**
|
||||
* The writable app scope: a {@link ProtectionConfigStore#saveApp} applies to the live
|
||||
* snapshot IMMEDIATELY (so {@link ProtectionConfigStore#appSettings()} — which the login gate/guard call fresh —
|
||||
* reflects it with no restart), persists to {@code external/plugin-settings/protection-app.yml} with the captcha
|
||||
* secret encrypted at rest, and the file (a prior save) is authoritative on the next boot; with no saved file the
|
||||
* snapshot seeds from {@link ProtectionProperties} (backward-compat with {@code runway.plugin.protection.login.*}).
|
||||
*/
|
||||
class ProtectionAppScopeTest {
|
||||
|
||||
/** A reversible test cipher: encrypt wraps base64 in {@code ENC(...)}, decrypt unwraps it. */
|
||||
private static SecretCipher fakeCipher() {
|
||||
return new SecretCipher() {
|
||||
@Override public boolean isAvailable() { return true; }
|
||||
|
||||
@Override public String encrypt(String plaintext) {
|
||||
return "ENC(" + Base64.getEncoder().encodeToString(plaintext.getBytes()) + ")";
|
||||
}
|
||||
|
||||
@Override public String decrypt(String value) {
|
||||
if (!isEncrypted(value)) {
|
||||
return value;
|
||||
}
|
||||
String b64 = value.substring("ENC(".length(), value.length() - 1);
|
||||
return new String(Base64.getDecoder().decode(b64));
|
||||
}
|
||||
|
||||
@Override public boolean isEncrypted(String value) {
|
||||
return value != null && value.startsWith("ENC(") && value.endsWith(")");
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
private static StorageLayout layout(Path root) {
|
||||
StorageProperties props = new StorageProperties();
|
||||
props.setExternal(root.resolve("external"));
|
||||
props.setSites(root.resolve("external").resolve("sites"));
|
||||
return StorageLayout.from(props);
|
||||
}
|
||||
|
||||
private static ProtectionProperties appProps() {
|
||||
ProtectionProperties p = new ProtectionProperties();
|
||||
p.getLogin().setHoneypotEnabled(false);
|
||||
p.getLogin().setMaxAttempts(7);
|
||||
p.getLogin().setWindowSeconds(111);
|
||||
p.getLogin().setLockoutSeconds(222);
|
||||
return p;
|
||||
}
|
||||
|
||||
@Test
|
||||
void appScopeSeedsFromPropertiesWhenNoFileExists(@TempDir Path root) {
|
||||
ProtectionConfigStore store = new ProtectionConfigStore(appProps(), layout(root), new YamlStore(), fakeCipher());
|
||||
ProtectionSettings s = store.appSettings();
|
||||
// Backward-compat: with no saved app-config file, the snapshot is derived from the properties.
|
||||
assertFalse(s.honeypotEnabled());
|
||||
assertEquals(7, s.maxAttempts());
|
||||
assertEquals(111, s.windowSeconds());
|
||||
assertEquals(222, s.lockoutSeconds());
|
||||
}
|
||||
|
||||
@Test
|
||||
void saveAppAppliesImmediatelyToTheLiveSnapshot(@TempDir Path root) throws IOException {
|
||||
ProtectionConfigStore store = new ProtectionConfigStore(appProps(), layout(root), new YamlStore(), fakeCipher());
|
||||
ProtectionSettings updated = new ProtectionSettings(true, 3, 60, 120,
|
||||
new ProtectionSettings.Captcha(true, "recaptcha-v3", "pub-key", "the-secret", 0.6));
|
||||
store.saveApp(updated);
|
||||
|
||||
// The live snapshot (what the login gate/guard read fresh) reflects the save with no restart.
|
||||
ProtectionSettings live = store.appSettings();
|
||||
assertTrue(live.honeypotEnabled());
|
||||
assertEquals(3, live.maxAttempts());
|
||||
assertEquals(60, live.windowSeconds());
|
||||
assertEquals(120, live.lockoutSeconds());
|
||||
assertTrue(live.captcha().enabled());
|
||||
assertEquals("recaptcha-v3", live.captcha().provider());
|
||||
assertEquals("the-secret", live.captcha().secretKey(), "the live secret is the plaintext the verifier uses");
|
||||
|
||||
// resolve(application) goes through the same snapshot.
|
||||
assertEquals(live, store.resolve(ProtectionScope.application()));
|
||||
}
|
||||
|
||||
@Test
|
||||
void saveAppPersistsWithTheSecretEncryptedAndTheFileIsAuthoritativeOnReboot(@TempDir Path root) throws IOException {
|
||||
StorageLayout layout = layout(root);
|
||||
SecretCipher cipher = fakeCipher();
|
||||
ProtectionConfigStore store = new ProtectionConfigStore(appProps(), layout, new YamlStore(), cipher);
|
||||
store.saveApp(new ProtectionSettings(true, 4, 200, 300,
|
||||
new ProtectionSettings.Captcha(true, "recaptcha-v2", "site-k", "app-secret-value", 0.5)));
|
||||
|
||||
Path file = layout.pluginSettings().resolve(ProtectionConfigStore.APP_CONFIG_FILE);
|
||||
String onDisk = Files.readString(file);
|
||||
assertTrue(onDisk.contains("ENC("), "the app captcha secret is stored encrypted");
|
||||
assertFalse(onDisk.contains("app-secret-value"), "the plaintext app secret is never written to disk");
|
||||
|
||||
// A NEW store (a reboot) seeds from the saved file — NOT the properties — and decrypts the secret back.
|
||||
ProtectionConfigStore rebooted = new ProtectionConfigStore(appProps(), layout, new YamlStore(), cipher);
|
||||
ProtectionSettings seeded = rebooted.appSettings();
|
||||
assertEquals(4, seeded.maxAttempts(), "the saved file, not the properties (which say 7), is authoritative");
|
||||
assertEquals(200, seeded.windowSeconds());
|
||||
assertEquals(300, seeded.lockoutSeconds());
|
||||
assertEquals("app-secret-value", seeded.captcha().secretKey(), "the app secret decrypts back on reboot");
|
||||
}
|
||||
|
||||
@Test
|
||||
void savingAnAppSecretWithoutACipherFailsLoudly(@TempDir Path root) {
|
||||
SecretCipher unavailable = new SecretCipher() {
|
||||
@Override public boolean isAvailable() { return false; }
|
||||
@Override public String encrypt(String plaintext) { throw new IllegalStateException("no key"); }
|
||||
@Override public String decrypt(String value) { return value; }
|
||||
@Override public boolean isEncrypted(String value) { return value != null && value.startsWith("ENC("); }
|
||||
};
|
||||
ProtectionConfigStore store =
|
||||
new ProtectionConfigStore(appProps(), layout(root), new YamlStore(), unavailable);
|
||||
ProtectionSettings withSecret = new ProtectionSettings(true, 4, 60, 120,
|
||||
new ProtectionSettings.Captcha(true, "recaptcha-v2", "site", "a-secret", 0.5));
|
||||
// A secret must never be persisted in the clear: no key → the save fails rather than writing plaintext.
|
||||
assertThrows(IllegalStateException.class, () -> store.saveApp(withSecret));
|
||||
assertFalse(store.secretStorable(), "the store reports the secret is not storable (drives the screen hint)");
|
||||
}
|
||||
}
|
||||
+277
@@ -0,0 +1,277 @@
|
||||
package mx.quest.protection;
|
||||
|
||||
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;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.Base64;
|
||||
import java.util.List;
|
||||
import mx.quest.runway.crypto.SecretCipher;
|
||||
import mx.quest.runway.security.ProtectionScope;
|
||||
import mx.quest.runway.storage.StorageLayout;
|
||||
import mx.quest.runway.storage.StorageProperties;
|
||||
import mx.quest.runway.storage.YamlStore;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
|
||||
/**
|
||||
* Per-scope resolution and the per-site round-trip: app scope comes from {@link ProtectionProperties}; per-site
|
||||
* scope round-trips through {@code sites/<id>/plugins/protection.yml} with the captcha secret <b>encrypted at
|
||||
* rest</b> and decrypted back on read; and every fault path degrades to {@link ProtectionSettings#defaults()}.
|
||||
*/
|
||||
class ProtectionConfigStoreTest {
|
||||
|
||||
/** A reversible test cipher: encrypt wraps base64 in {@code ENC(...)}, decrypt unwraps it. */
|
||||
private static SecretCipher fakeCipher() {
|
||||
return new SecretCipher() {
|
||||
@Override
|
||||
public boolean isAvailable() {
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String encrypt(String plaintext) {
|
||||
return "ENC(" + Base64.getEncoder().encodeToString(plaintext.getBytes()) + ")";
|
||||
}
|
||||
|
||||
@Override
|
||||
public String decrypt(String value) {
|
||||
if (!isEncrypted(value)) {
|
||||
return value;
|
||||
}
|
||||
String b64 = value.substring("ENC(".length(), value.length() - 1);
|
||||
return new String(Base64.getDecoder().decode(b64));
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isEncrypted(String value) {
|
||||
return value != null && value.startsWith("ENC(") && value.endsWith(")");
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
private static StorageLayout layout(Path root) {
|
||||
StorageProperties props = new StorageProperties();
|
||||
props.setExternal(root.resolve("external"));
|
||||
props.setSites(root.resolve("external").resolve("sites"));
|
||||
return StorageLayout.from(props);
|
||||
}
|
||||
|
||||
private static ProtectionProperties appProps() {
|
||||
ProtectionProperties p = new ProtectionProperties();
|
||||
p.getLogin().setHoneypotEnabled(false);
|
||||
p.getLogin().setMaxAttempts(7);
|
||||
p.getLogin().setWindowSeconds(111);
|
||||
p.getLogin().setLockoutSeconds(222);
|
||||
p.getLogin().getCaptcha().setEnabled(true);
|
||||
p.getLogin().getCaptcha().setSiteKey("app-site-key");
|
||||
p.getLogin().getCaptcha().setSecretKey("app-plaintext-secret"); // app-level: bound as plaintext here
|
||||
return p;
|
||||
}
|
||||
|
||||
@Test
|
||||
void appScopeComesFromTheProperties(@TempDir Path root) {
|
||||
ProtectionConfigStore store = new ProtectionConfigStore(appProps(), layout(root), new YamlStore(), fakeCipher());
|
||||
ProtectionSettings s = store.resolve(ProtectionScope.application());
|
||||
assertFalse(s.honeypotEnabled(), "app honeypot flag from properties");
|
||||
assertEquals(7, s.maxAttempts());
|
||||
assertEquals(111, s.windowSeconds());
|
||||
assertEquals(222, s.lockoutSeconds());
|
||||
assertTrue(s.captcha().enabled());
|
||||
assertEquals("app-plaintext-secret", s.captcha().secretKey(), "app secret decrypts (plaintext passes through)");
|
||||
}
|
||||
|
||||
@Test
|
||||
void everyPathUsesTheSameLockoutDefaults(@TempDir Path root) throws IOException {
|
||||
ProtectionSettings fresh = new ProtectionConfigStore(new ProtectionProperties(), layout(root), new YamlStore(),
|
||||
fakeCipher()).resolve(ProtectionScope.application());
|
||||
ProtectionSettings expected = ProtectionSettings.defaults();
|
||||
assertEquals(List.of(5, 300, 900), List.of(fresh.maxAttempts(), fresh.windowSeconds(), fresh.lockoutSeconds()),
|
||||
"a fresh install");
|
||||
assertEquals(List.of(5, 300, 900),
|
||||
List.of(expected.maxAttempts(), expected.windowSeconds(), expected.lockoutSeconds()), "defaults()");
|
||||
|
||||
StorageLayout layout = layout(root.resolve("saved"));
|
||||
Files.createDirectories(layout.pluginSettings());
|
||||
Files.writeString(layout.pluginSettings().resolve("protection-app.yml"), "honeypotEnabled: true\n");
|
||||
ProtectionSettings omitted = new ProtectionConfigStore(new ProtectionProperties(), layout, new YamlStore(),
|
||||
fakeCipher()).resolve(ProtectionScope.application());
|
||||
assertEquals(List.of(5, 300, 900),
|
||||
List.of(omitted.maxAttempts(), omitted.windowSeconds(), omitted.lockoutSeconds()),
|
||||
"a saved file that omits the lockout keys");
|
||||
assertEquals(5, new ProtectionSettings(true, 0, -1, 0, null).maxAttempts(), "a non-positive value");
|
||||
}
|
||||
|
||||
@Test
|
||||
void loginPropertiesShadowedByTheSavedPanelFileAreReportedAtStartup(@TempDir Path root) throws IOException {
|
||||
ch.qos.logback.classic.Logger logger =
|
||||
(ch.qos.logback.classic.Logger) org.slf4j.LoggerFactory.getLogger(ProtectionConfigStore.class);
|
||||
ch.qos.logback.core.read.ListAppender<ch.qos.logback.classic.spi.ILoggingEvent> appender =
|
||||
new ch.qos.logback.core.read.ListAppender<>();
|
||||
appender.start();
|
||||
logger.addAppender(appender);
|
||||
try {
|
||||
StorageLayout layout = layout(root);
|
||||
Files.createDirectories(layout.pluginSettings());
|
||||
Files.writeString(layout.pluginSettings().resolve("protection-app.yml"), "maxAttempts: 9\n");
|
||||
|
||||
new ProtectionConfigStore(new ProtectionProperties(), layout, new YamlStore(), fakeCipher());
|
||||
assertTrue(appender.list.stream().noneMatch(e -> e.getFormattedMessage().contains("login.*")),
|
||||
"properties at their defaults: nothing to say");
|
||||
|
||||
ProtectionSettings applied = new ProtectionConfigStore(appProps(), layout, new YamlStore(), fakeCipher())
|
||||
.resolve(ProtectionScope.application());
|
||||
assertEquals(9, applied.maxAttempts(), "the saved panel file applies");
|
||||
assertTrue(appender.list.stream().anyMatch(e -> e.getLevel() == ch.qos.logback.classic.Level.WARN
|
||||
&& e.getFormattedMessage().contains("runway.plugin.protection.login.* is set")),
|
||||
"a set property that does not apply is reported");
|
||||
} finally {
|
||||
logger.detachAppender(appender);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void perSiteRoundTripsWithTheCaptchaSecretEncryptedAtRest(@TempDir Path root) throws IOException {
|
||||
SecretCipher cipher = fakeCipher();
|
||||
StorageLayout layout = layout(root);
|
||||
ProtectionConfigStore store = new ProtectionConfigStore(new ProtectionProperties(), layout, new YamlStore(), cipher);
|
||||
|
||||
ProtectionSettings toSave = new ProtectionSettings(true, 4, 60, 120,
|
||||
new ProtectionSettings.Captcha(true, "recaptcha-v3", "site-key-123", "super-secret-value", 0.7));
|
||||
store.savePerSite("acme", toSave);
|
||||
|
||||
// On disk the secret is ENC(...), never the plaintext — and the app-scope lockout keys are NOT written per-site.
|
||||
Path file = layout.sitePluginConfigFile("acme", "protection");
|
||||
String onDisk = Files.readString(file);
|
||||
assertTrue(onDisk.contains("ENC("), "the captcha secret is stored encrypted");
|
||||
assertFalse(onDisk.contains("super-secret-value"), "the plaintext secret is never written to disk");
|
||||
assertFalse(onDisk.contains("maxAttempts") || onDisk.contains("lockoutSeconds"),
|
||||
"the per-site file carries no lockout keys (lockout is app-scope)");
|
||||
|
||||
// Read back: honeypot + captcha round-trip and the secret is decrypted. The lockout is app-scope, so per-site
|
||||
// it reads back at defaults (never the saved 4/60/120 — those are not stored per-site).
|
||||
ProtectionSettings read = store.resolve(ProtectionScope.forSite("acme"));
|
||||
assertTrue(read.honeypotEnabled());
|
||||
assertTrue(read.captcha().enabled());
|
||||
assertEquals("recaptcha-v3", read.captcha().provider());
|
||||
assertEquals("site-key-123", read.captcha().siteKey());
|
||||
assertEquals("super-secret-value", read.captcha().secretKey(), "the secret decrypts back to plaintext");
|
||||
assertEquals(0.7, read.captcha().scoreThreshold());
|
||||
}
|
||||
|
||||
@Test
|
||||
void anAbsentPerSiteFileYieldsDefaults(@TempDir Path root) {
|
||||
ProtectionConfigStore store =
|
||||
new ProtectionConfigStore(new ProtectionProperties(), layout(root), new YamlStore(), fakeCipher());
|
||||
ProtectionSettings s = store.resolve(ProtectionScope.forSite("no-such-site"));
|
||||
assertEquals(ProtectionSettings.defaults(), s, "absent file → defaults (fail-safe)");
|
||||
}
|
||||
|
||||
@Test
|
||||
void aSiteLessTenantScopeYieldsDefaults(@TempDir Path root) {
|
||||
ProtectionConfigStore store =
|
||||
new ProtectionConfigStore(new ProtectionProperties(), layout(root), new YamlStore(), fakeCipher());
|
||||
// forSite(null) is a site-less tenant scope (unresolvable site) → defaults, never another site's config.
|
||||
assertEquals(ProtectionSettings.defaults(), store.resolve(ProtectionScope.forSite(null)));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aCorruptPerSiteFileDegradesToDefaults(@TempDir Path root) throws IOException {
|
||||
StorageLayout layout = layout(root);
|
||||
Path file = layout.sitePluginConfigFile("broken", "protection");
|
||||
Files.createDirectories(file.getParent());
|
||||
Files.writeString(file, "this: [is: not: valid: yaml: {{{");
|
||||
ProtectionConfigStore store =
|
||||
new ProtectionConfigStore(new ProtectionProperties(), layout, new YamlStore(), fakeCipher());
|
||||
assertEquals(ProtectionSettings.defaults(), store.resolve(ProtectionScope.forSite("broken")),
|
||||
"a hand-corrupted file must not 500 the login — degrade to defaults");
|
||||
}
|
||||
|
||||
@Test
|
||||
void savingASecretWithoutAnAvailableCipherFailsLoudly(@TempDir Path root) {
|
||||
SecretCipher unavailable = new SecretCipher() {
|
||||
@Override public boolean isAvailable() { return false; }
|
||||
@Override public String encrypt(String plaintext) { throw new IllegalStateException("no key"); }
|
||||
@Override public String decrypt(String value) { return value; }
|
||||
@Override public boolean isEncrypted(String value) { return value != null && value.startsWith("ENC("); }
|
||||
};
|
||||
ProtectionConfigStore store =
|
||||
new ProtectionConfigStore(new ProtectionProperties(), layout(root), new YamlStore(), unavailable);
|
||||
ProtectionSettings withSecret = new ProtectionSettings(true, 4, 60, 120,
|
||||
new ProtectionSettings.Captcha(true, "recaptcha-v2", "site", "a-secret", 0.5));
|
||||
// A secret must never be persisted in the clear: no key → the save fails rather than writing plaintext.
|
||||
assertThrows(IllegalStateException.class, () -> store.savePerSite("acme", withSecret));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aBlankSecretIsStoredBlankNotEncrypted(@TempDir Path root) throws IOException {
|
||||
StorageLayout layout = layout(root);
|
||||
ProtectionConfigStore store =
|
||||
new ProtectionConfigStore(new ProtectionProperties(), layout, new YamlStore(), fakeCipher());
|
||||
ProtectionSettings noSecret = new ProtectionSettings(true, 4, 60, 120,
|
||||
new ProtectionSettings.Captcha(false, "recaptcha-v2", "", "", 0.5));
|
||||
store.savePerSite("acme", noSecret);
|
||||
String onDisk = Files.readString(layout.sitePluginConfigFile("acme", "protection"));
|
||||
assertFalse(onDisk.contains("ENC("), "a blank secret is stored blank, not encrypted");
|
||||
}
|
||||
|
||||
// --- operator rescue: disable a site's login CAPTCHA from the app console -------------------------
|
||||
|
||||
@Test
|
||||
void disableSiteCaptchaTurnsItOffAndPreservesTheStoredKeys(@TempDir Path root) throws IOException {
|
||||
StorageLayout layout = layout(root);
|
||||
ProtectionConfigStore store =
|
||||
new ProtectionConfigStore(new ProtectionProperties(), layout, new YamlStore(), fakeCipher());
|
||||
store.savePerSite("acme", new ProtectionSettings(true, 4, 60, 120,
|
||||
new ProtectionSettings.Captcha(true, "recaptcha-v2", "site-key-abc", "top-secret", 0.5)));
|
||||
assertTrue(store.siteCaptchaEnabled("acme"), "captcha starts enabled");
|
||||
|
||||
assertTrue(store.disableSiteCaptcha("acme"), "a change was written");
|
||||
|
||||
assertFalse(store.siteCaptchaEnabled("acme"), "captcha is now off");
|
||||
ProtectionSettings read = store.resolve(ProtectionScope.forSite("acme"));
|
||||
assertFalse(read.captcha().enabled());
|
||||
assertEquals("recaptcha-v2", read.captcha().provider(), "the provider is preserved");
|
||||
assertEquals("site-key-abc", read.captcha().siteKey(), "the site key is preserved");
|
||||
assertEquals("top-secret", read.captcha().secretKey(), "the secret is preserved (decrypts back), not wiped");
|
||||
String onDisk = Files.readString(layout.sitePluginConfigFile("acme", "protection"));
|
||||
assertTrue(onDisk.contains("ENC("), "the secret stays encrypted on disk");
|
||||
assertFalse(onDisk.contains("top-secret"), "the plaintext secret is never written");
|
||||
}
|
||||
|
||||
@Test
|
||||
void disableSiteCaptchaWorksWithoutAnEncryptionKey(@TempDir Path root) throws IOException {
|
||||
// The rescue must not require a cipher: the ENC(...) secret is carried through untouched. Seed a file that
|
||||
// has an encrypted secret, then disable with an UNAVAILABLE cipher and confirm it still succeeds.
|
||||
StorageLayout layout = layout(root);
|
||||
new ProtectionConfigStore(new ProtectionProperties(), layout, new YamlStore(), fakeCipher())
|
||||
.savePerSite("acme", new ProtectionSettings(true, 0, 0, 0,
|
||||
new ProtectionSettings.Captcha(true, "recaptcha-v2", "k", "s", 0.5)));
|
||||
SecretCipher unavailable = new SecretCipher() {
|
||||
@Override public boolean isAvailable() { return false; }
|
||||
@Override public String encrypt(String plaintext) { throw new IllegalStateException("no key"); }
|
||||
@Override public String decrypt(String value) { return value; }
|
||||
@Override public boolean isEncrypted(String value) { return value != null && value.startsWith("ENC("); }
|
||||
};
|
||||
ProtectionConfigStore noKey =
|
||||
new ProtectionConfigStore(new ProtectionProperties(), layout, new YamlStore(), unavailable);
|
||||
assertTrue(noKey.disableSiteCaptcha("acme"), "the rescue succeeds even with no encryption key configured");
|
||||
assertFalse(noKey.siteCaptchaEnabled("acme"), "captcha is off");
|
||||
}
|
||||
|
||||
@Test
|
||||
void disableSiteCaptchaIsANoOpWhenAbsentOrAlreadyOff(@TempDir Path root) throws IOException {
|
||||
StorageLayout layout = layout(root);
|
||||
ProtectionConfigStore store =
|
||||
new ProtectionConfigStore(new ProtectionProperties(), layout, new YamlStore(), fakeCipher());
|
||||
assertFalse(store.disableSiteCaptcha("no-such-site"), "nothing to disable when no config exists");
|
||||
store.savePerSite("acme", new ProtectionSettings(true, 0, 0, 0,
|
||||
new ProtectionSettings.Captcha(false, "recaptcha-v2", "k", "", 0.5)));
|
||||
assertFalse(store.siteCaptchaEnabled("acme"), "captcha is already off");
|
||||
assertFalse(store.disableSiteCaptcha("acme"), "no change when captcha is already off");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,128 @@
|
||||
package mx.quest.protection;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertInstanceOf;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
import mx.quest.runway.crypto.SecretCipher;
|
||||
import mx.quest.runway.platform.PlatformSettingsStore;
|
||||
import mx.quest.runway.protect.EdgeGuard;
|
||||
import mx.quest.runway.protect.EdgeRequest;
|
||||
import mx.quest.runway.security.LoginAttemptGate;
|
||||
import mx.quest.runway.security.LoginFormGuard;
|
||||
import mx.quest.runway.site.SiteResolver;
|
||||
import mx.quest.runway.site.SiteStore;
|
||||
import mx.quest.runway.storage.StorageLayout;
|
||||
import mx.quest.runway.storage.StorageProperties;
|
||||
import mx.quest.runway.storage.YamlStore;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.test.context.TestPropertySource;
|
||||
import org.springframework.test.context.junit.jupiter.SpringJUnitConfig;
|
||||
|
||||
/**
|
||||
* The plugin's {@code @Configuration} (what the loader registers) supplies working {@code @Primary}
|
||||
* {@link EdgeGuard}, {@link LoginAttemptGate} and {@link LoginFormGuard} beans — so once loaded they arm the
|
||||
* kernel's security floor, binding their thresholds from {@code runway.plugin.protection.*}. The kernel storage
|
||||
* beans it depends on ({@link StorageLayout}, {@link YamlStore}, {@link SecretCipher}) are supplied here as the
|
||||
* host would at runtime.
|
||||
*/
|
||||
@SpringJUnitConfig({ProtectionConfig.class, ProtectionConfigTest.HostBeans.class})
|
||||
@TestPropertySource(properties = {
|
||||
"runway.plugin.protection.rate-limit.capacity=2",
|
||||
"runway.plugin.protection.rate-limit.refill-per-second=0",
|
||||
"runway.plugin.protection.login.max-attempts=1"
|
||||
})
|
||||
class ProtectionConfigTest {
|
||||
|
||||
@Autowired
|
||||
private EdgeGuard edgeGuard;
|
||||
|
||||
@Autowired
|
||||
private LoginAttemptGate loginGate;
|
||||
|
||||
@Autowired
|
||||
private LoginFormGuard loginFormGuard;
|
||||
|
||||
@Test
|
||||
void theConfigSuppliesTheRealPolicyGuards() {
|
||||
assertInstanceOf(RateLimitEdgeGuard.class, edgeGuard, "the @Primary EdgeGuard is the rate limiter");
|
||||
assertInstanceOf(SlidingWindowLoginGate.class, loginGate, "the @Primary LoginAttemptGate is the lockout");
|
||||
assertInstanceOf(LoginFormPolicyGuard.class, loginFormGuard,
|
||||
"the @Primary LoginFormGuard is the honeypot + captcha policy guard");
|
||||
}
|
||||
|
||||
@Test
|
||||
void theBoundThresholdsAreEnforced() {
|
||||
EdgeRequest request = new EdgeRequest("9.9.9.9", "GET", "/");
|
||||
assertTrue(edgeGuard.check(request).allowed());
|
||||
assertTrue(edgeGuard.check(request).allowed());
|
||||
assertFalse(edgeGuard.check(request).allowed(), "capacity=2 from settings is exhausted → rejected");
|
||||
|
||||
loginGate.recordFailure("9.9.9.9");
|
||||
assertTrue(loginGate.isLocked("9.9.9.9"), "max-attempts=1 from settings → locked after one failure");
|
||||
}
|
||||
|
||||
/** The kernel-provided storage/crypto beans the plugin config injects (supplied by the host at runtime). */
|
||||
@Configuration(proxyBeanMethods = false)
|
||||
static class HostBeans {
|
||||
|
||||
@Bean
|
||||
StorageLayout storageLayout() {
|
||||
return StorageLayout.from(new StorageProperties());
|
||||
}
|
||||
|
||||
@Bean
|
||||
YamlStore yamlStore() {
|
||||
return new YamlStore();
|
||||
}
|
||||
|
||||
@Bean
|
||||
SiteResolver siteResolver(StorageLayout layout, YamlStore yaml) {
|
||||
// The kernel bean the plugin's login-view captcha configurer injects; a real resolver over an empty
|
||||
// storage tree (no site files) is enough — the config test never renders a login view.
|
||||
return new SiteResolver(new SiteStore(layout, yaml), new PlatformSettingsStore(layout, yaml));
|
||||
}
|
||||
|
||||
@Bean
|
||||
mx.quest.runway.spi.service.RequestContext requestContext() {
|
||||
// The SPI request context the tenant Protection screen reads its bound site from; the host provides it
|
||||
// at runtime. No request is bound in this test, so it answers empty (as the kernel's does off-request).
|
||||
return java.util.Optional::empty;
|
||||
}
|
||||
|
||||
@Bean("operatorAwareMessageSource")
|
||||
org.springframework.context.MessageSource operatorAwareMessageSource() {
|
||||
// The console message source the Protection screen controllers inject (@Qualifier); host-provided at runtime.
|
||||
return new org.springframework.context.support.StaticMessageSource();
|
||||
}
|
||||
|
||||
@Bean
|
||||
SecretCipher secretCipher() {
|
||||
// A no-op cipher: unavailable (no key), pass-through decrypt. Sufficient for the app-scope path here.
|
||||
return new SecretCipher() {
|
||||
@Override
|
||||
public boolean isAvailable() {
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String encrypt(String plaintext) {
|
||||
throw new IllegalStateException("no key");
|
||||
}
|
||||
|
||||
@Override
|
||||
public String decrypt(String value) {
|
||||
return value;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isEncrypted(String value) {
|
||||
return value != null && value.startsWith("ENC(");
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
+71
@@ -0,0 +1,71 @@
|
||||
package mx.quest.protection;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.URISyntaxException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import tools.jackson.databind.JsonNode;
|
||||
import tools.jackson.databind.json.JsonMapper;
|
||||
|
||||
/**
|
||||
* The plugin's own {@code runway.plugin.protection.*} keys get Spring configuration metadata (IDE completion and
|
||||
* type checks). Guards the regression where the configuration processor silently never ran: on JDK 23+ it must be
|
||||
* on the compiler's {@code annotationProcessorPaths}, not merely on the classpath.
|
||||
*
|
||||
* <p>The file is read from <b>this module's</b> compiled classes, never through the class loader: the kernel's
|
||||
* own {@code META-INF/spring-configuration-metadata.json} is on the test classpath too (runway-app is a
|
||||
* {@code provided} dependency) and would otherwise be found first.
|
||||
*/
|
||||
class ProtectionConfigurationMetadataTest {
|
||||
|
||||
private static Map<String, JsonNode> properties() throws IOException, URISyntaxException {
|
||||
Path classes = Path.of(ProtectionProperties.class.getProtectionDomain().getCodeSource().getLocation().toURI());
|
||||
Path metadata = classes.resolve("META-INF/spring-configuration-metadata.json");
|
||||
assertTrue(Files.isRegularFile(metadata), "the plugin's metadata is generated at " + metadata
|
||||
+ " (is spring-boot-configuration-processor on the compiler's annotationProcessorPaths?)");
|
||||
JsonNode root = JsonMapper.builder().build().readTree(Files.readString(metadata));
|
||||
Map<String, JsonNode> byName = new HashMap<>();
|
||||
root.get("properties").forEach(p -> byName.put(p.get("name").asString(), p));
|
||||
return byName;
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {
|
||||
"runway.plugin.protection.rate-limit.capacity",
|
||||
"runway.plugin.protection.rate-limit.refill-per-second",
|
||||
"runway.plugin.protection.rate-limit.auto-block.enabled",
|
||||
"runway.plugin.protection.allowlist",
|
||||
"runway.plugin.protection.login.max-attempts",
|
||||
"runway.plugin.protection.login.captcha.provider",
|
||||
"runway.plugin.protection.login.captcha.secret-key",
|
||||
"runway.plugin.protection.remember-device.days",
|
||||
})
|
||||
void everyPluginKeyIsInTheMetadata(String key) throws Exception {
|
||||
assertTrue(properties().containsKey(key), key + " is missing from the plugin's configuration metadata");
|
||||
}
|
||||
|
||||
@Test
|
||||
void theMetadataCarriesTypesAndDefaults() throws Exception {
|
||||
Map<String, JsonNode> props = properties();
|
||||
JsonNode capacity = props.get("runway.plugin.protection.rate-limit.capacity");
|
||||
assertEquals("java.lang.Integer", capacity.get("type").asString());
|
||||
assertEquals(120, capacity.get("defaultValue").asInt());
|
||||
assertEquals(30, props.get("runway.plugin.protection.remember-device.days").get("defaultValue").asInt());
|
||||
}
|
||||
|
||||
@Test
|
||||
void onlyThePluginsOwnPrefixIsDescribedHere() throws Exception {
|
||||
assertFalse(properties().isEmpty());
|
||||
properties().keySet().forEach(name -> assertTrue(name.startsWith("runway.plugin.protection."),
|
||||
name + " is outside the plugin's prefix — the kernel's metadata was picked up instead"));
|
||||
}
|
||||
}
|
||||
+43
@@ -0,0 +1,43 @@
|
||||
package mx.quest.protection;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
import java.lang.reflect.Method;
|
||||
import java.util.Arrays;
|
||||
import mx.quest.runway.spi.service.ConsoleScreen;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.web.bind.annotation.ControllerAdvice;
|
||||
|
||||
/**
|
||||
* The protection screens render in the console shell through the SPI's {@code @ConsoleScreen} (the kernel's
|
||||
* advice fills the shell), not through a plugin {@code @ControllerAdvice} that links the host's
|
||||
* {@code OperatorShellModel}.
|
||||
*/
|
||||
class ProtectionConsoleScreensTest {
|
||||
|
||||
@Test
|
||||
void theScreensThatRenderTheShellAreConsoleScreens() {
|
||||
assertTrue(SiteProtectionController.class.isAnnotationPresent(ConsoleScreen.class));
|
||||
assertTrue(DosController.class.isAnnotationPresent(ConsoleScreen.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
void thePluginRegistersNoControllerAdviceAndNoShellModel() {
|
||||
for (Method bean : ProtectionConfig.class.getDeclaredMethods()) {
|
||||
assertFalse(bean.getReturnType().isAnnotationPresent(ControllerAdvice.class),
|
||||
bean.getName() + " returns a @ControllerAdvice");
|
||||
assertFalse(Arrays.stream(bean.getParameterTypes())
|
||||
.anyMatch(type -> type.getName().equals("mx.quest.runway.console.OperatorShellModel")),
|
||||
bean.getName() + " injects the host's OperatorShellModel");
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void theTenantScreenReadsItsSiteThroughTheSpi() {
|
||||
assertTrue(Arrays.stream(SiteProtectionController.class.getConstructors()[0].getParameterTypes())
|
||||
.anyMatch(type -> type == mx.quest.runway.spi.service.RequestContext.class));
|
||||
assertFalse(Arrays.stream(SiteProtectionController.class.getDeclaredFields())
|
||||
.anyMatch(field -> field.getType().getName().equals("mx.quest.runway.site.SiteResolver")));
|
||||
}
|
||||
}
|
||||
+199
@@ -0,0 +1,199 @@
|
||||
package mx.quest.protection;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.Base64;
|
||||
import java.util.Optional;
|
||||
import mx.quest.runway.crypto.SecretCipher;
|
||||
import mx.quest.runway.spi.model.SiteView;
|
||||
import mx.quest.runway.spi.service.RequestContext;
|
||||
import mx.quest.runway.storage.StorageLayout;
|
||||
import mx.quest.runway.storage.StorageProperties;
|
||||
import mx.quest.runway.storage.YamlStore;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.context.support.StaticMessageSource;
|
||||
import org.springframework.ui.Model;
|
||||
import org.springframework.validation.support.BindingAwareModelMap;
|
||||
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
|
||||
import org.springframework.web.servlet.mvc.support.RedirectAttributesModelMap;
|
||||
|
||||
/**
|
||||
* The two screens' controller logic, exercised directly (gating is proven separately by
|
||||
* {@code ProtectionScreenGatingTest}). Covers: the app screen persists + applies live and renders the plugin
|
||||
* content template; the per-site screen writes ONLY the bound tenancy's file (isolation); a blank captcha-secret
|
||||
* field preserves the stored secret, a non-blank one encrypts it; and the GET model masks the secret.
|
||||
*/
|
||||
class ProtectionControllerLogicTest {
|
||||
|
||||
private static SecretCipher fakeCipher() {
|
||||
return new SecretCipher() {
|
||||
@Override public boolean isAvailable() { return true; }
|
||||
|
||||
@Override public String encrypt(String plaintext) {
|
||||
return "ENC(" + Base64.getEncoder().encodeToString(plaintext.getBytes()) + ")";
|
||||
}
|
||||
|
||||
@Override public String decrypt(String value) {
|
||||
if (!isEncrypted(value)) {
|
||||
return value;
|
||||
}
|
||||
return new String(Base64.getDecoder().decode(value.substring(4, value.length() - 1)));
|
||||
}
|
||||
|
||||
@Override public boolean isEncrypted(String value) {
|
||||
return value != null && value.startsWith("ENC(") && value.endsWith(")");
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
private static StorageLayout layout(Path root) {
|
||||
StorageProperties props = new StorageProperties();
|
||||
props.setExternal(root.resolve("external"));
|
||||
props.setSites(root.resolve("external").resolve("sites"));
|
||||
return StorageLayout.from(props);
|
||||
}
|
||||
|
||||
private static StaticMessageSource messages() {
|
||||
return new StaticMessageSource(); // returns the fallback for any key — fine for flash-text assertions
|
||||
}
|
||||
|
||||
/** The SPI request context a tenant-console request bound to {@code siteId} answers with. */
|
||||
private static RequestContext boundTo(String siteId) {
|
||||
SiteView site = new SiteView(siteId, siteId, java.util.Locale.ENGLISH, java.util.List.of(), null);
|
||||
return () -> Optional.of(site);
|
||||
}
|
||||
|
||||
private static ProtectionConfigStore store(StorageLayout layout, SecretCipher cipher) {
|
||||
return new ProtectionConfigStore(new ProtectionProperties(), layout, new YamlStore(), cipher);
|
||||
}
|
||||
|
||||
// --- App screen -----------------------------------------------------------------------------------
|
||||
|
||||
@Test
|
||||
void theAppSaveAppliesLiveAndRedirectsToThePluginSettingsPage(@TempDir Path root) {
|
||||
StorageLayout layout = layout(root);
|
||||
ProtectionConfigStore store = store(layout, fakeCipher());
|
||||
AppProtectionController controller = new AppProtectionController(store, messages());
|
||||
RedirectAttributes redirect = new RedirectAttributesModelMap();
|
||||
|
||||
String view = controller.save(false, 3, 60, 120, true, "recaptcha-v3", "pub", "the-secret", 0.6, redirect);
|
||||
|
||||
// The panel's POST redirects back to the plugin settings page (where the panel renders).
|
||||
assertEquals("redirect:/__app/plugins/protection/settings", view);
|
||||
// Applied live (no restart): the store's app snapshot reflects the save immediately.
|
||||
ProtectionSettings live = store.appSettings();
|
||||
assertFalse(live.honeypotEnabled());
|
||||
assertEquals(3, live.maxAttempts());
|
||||
assertTrue(live.captcha().enabled());
|
||||
assertEquals("recaptcha-v3", live.captcha().provider());
|
||||
assertEquals("the-secret", live.captcha().secretKey());
|
||||
// Persisted with the secret encrypted at rest.
|
||||
assertTrue(redirect.getFlashAttributes().containsKey("flash"));
|
||||
}
|
||||
|
||||
// --- Per-site screen + isolation ------------------------------------------------------------------
|
||||
|
||||
@Test
|
||||
void thePerSiteSaveWritesOnlyTheBoundSitesFile(@TempDir Path root) throws IOException {
|
||||
StorageLayout layout = layout(root);
|
||||
ProtectionConfigStore store = store(layout, fakeCipher());
|
||||
SiteProtectionController controller = new SiteProtectionController(boundTo("alpha"), store, messages());
|
||||
|
||||
controller.save(true, true, "recaptcha-v2", "site-a", "alpha-secret", 0.5,
|
||||
new RedirectAttributesModelMap());
|
||||
|
||||
// Site "alpha" got a file; site "bravo" did NOT — the bound tenancy is the only one touched (isolation).
|
||||
Path alphaFile = layout.sitePluginConfigFile("alpha", "protection");
|
||||
Path bravoFile = layout.sitePluginConfigFile("bravo", "protection");
|
||||
assertTrue(Files.exists(alphaFile), "the bound site's file was written");
|
||||
assertFalse(Files.exists(bravoFile), "no other site's file was touched");
|
||||
// The app scope is untouched by the per-site save.
|
||||
assertFalse(Files.exists(layout.pluginSettings().resolve(ProtectionConfigStore.APP_CONFIG_FILE)),
|
||||
"the per-site screen never writes the app-scope config");
|
||||
// The per-site file carries honeypot + captcha ONLY — the app-scope lockout keys are never written per-site.
|
||||
String yaml = Files.readString(alphaFile);
|
||||
assertFalse(yaml.contains("maxAttempts") || yaml.contains("windowSeconds") || yaml.contains("lockoutSeconds"),
|
||||
"the per-site protection file must not carry the app-scope lockout keys: " + yaml);
|
||||
assertTrue(yaml.contains("honeypotEnabled") && yaml.contains("captcha"),
|
||||
"it carries the per-site honeypot + captcha");
|
||||
}
|
||||
|
||||
@Test
|
||||
void twoSitesAreFullyIsolated(@TempDir Path root) {
|
||||
StorageLayout layout = layout(root);
|
||||
ProtectionConfigStore store = store(layout, fakeCipher());
|
||||
|
||||
new SiteProtectionController(boundTo("alpha"), store, messages())
|
||||
.save(true, false, "recaptcha-v2", "alpha-site", "", 0.5, new RedirectAttributesModelMap());
|
||||
new SiteProtectionController(boundTo("bravo"), store, messages())
|
||||
.save(false, false, "recaptcha-v2", "bravo-site", "", 0.5, new RedirectAttributesModelMap());
|
||||
|
||||
// Each site reads back exactly its own per-site config (honeypot + captcha) — neither leaks into the other.
|
||||
assertTrue(store.perSiteSettings("alpha").honeypotEnabled());
|
||||
assertEquals("alpha-site", store.perSiteSettings("alpha").captcha().siteKey());
|
||||
assertFalse(store.perSiteSettings("bravo").honeypotEnabled());
|
||||
assertEquals("bravo-site", store.perSiteSettings("bravo").captcha().siteKey());
|
||||
}
|
||||
|
||||
@Test
|
||||
void anExistingPerSiteFileWithLegacyLockoutKeysStillReads(@TempDir Path root) throws IOException {
|
||||
StorageLayout layout = layout(root);
|
||||
ProtectionConfigStore store = store(layout, fakeCipher());
|
||||
Path file = layout.sitePluginConfigFile("legacy", "protection");
|
||||
Files.createDirectories(file.getParent());
|
||||
// A pre-change file that still carries the (now-inert) lockout keys alongside honeypot + captcha; it must
|
||||
// load cleanly (StoredSiteProtection ignores the unknown keys) rather than degrading to defaults.
|
||||
Files.writeString(file, "honeypotEnabled: false\nmaxAttempts: 3\nwindowSeconds: 60\nlockoutSeconds: 120\n"
|
||||
+ "captcha:\n enabled: true\n provider: hcaptcha\n siteKey: legacy-key\n");
|
||||
|
||||
ProtectionSettings s = store.perSiteSettings("legacy");
|
||||
assertFalse(s.honeypotEnabled(), "honeypot bound from the legacy file");
|
||||
assertEquals("legacy-key", s.captcha().siteKey(), "captcha bound from the legacy file (lockout keys ignored)");
|
||||
}
|
||||
|
||||
// --- Secret masking + preserve-on-blank -----------------------------------------------------------
|
||||
|
||||
@Test
|
||||
void aBlankSecretOnPostPreservesTheStoredSecret(@TempDir Path root) {
|
||||
StorageLayout layout = layout(root);
|
||||
ProtectionConfigStore store = store(layout, fakeCipher());
|
||||
SiteProtectionController controller = new SiteProtectionController(boundTo("acme"), store, messages());
|
||||
|
||||
// 1) Save WITH a secret.
|
||||
controller.save(true, true, "recaptcha-v2","site-k", "original-secret", 0.5,
|
||||
new RedirectAttributesModelMap());
|
||||
assertEquals("original-secret", store.perSiteSettings("acme").captcha().secretKey());
|
||||
|
||||
// 2) Re-save with the secret field BLANK (and a changed site key) — the stored secret must be KEPT.
|
||||
controller.save(true, true, "recaptcha-v2","site-k-CHANGED", " ", 0.5,
|
||||
new RedirectAttributesModelMap());
|
||||
ProtectionSettings after = store.perSiteSettings("acme");
|
||||
assertEquals("original-secret", after.captcha().secretKey(), "a blank secret field keeps the stored secret");
|
||||
assertEquals("site-k-CHANGED", after.captcha().siteKey(), "the public site key still updated");
|
||||
|
||||
// 3) A non-blank value REPLACES it.
|
||||
controller.save(true, true, "recaptcha-v2","site-k-CHANGED", "new-secret", 0.5,
|
||||
new RedirectAttributesModelMap());
|
||||
assertEquals("new-secret", store.perSiteSettings("acme").captcha().secretKey());
|
||||
}
|
||||
|
||||
@Test
|
||||
void thePerSiteGetMasksTheSecret(@TempDir Path root) {
|
||||
StorageLayout layout = layout(root);
|
||||
ProtectionConfigStore store = store(layout, fakeCipher());
|
||||
SiteProtectionController controller = new SiteProtectionController(boundTo("acme"), store, messages());
|
||||
controller.save(true, true, "recaptcha-v2","site-k", "hidden-secret", 0.5,
|
||||
new RedirectAttributesModelMap());
|
||||
|
||||
Model model = new BindingAwareModelMap();
|
||||
controller.form(model);
|
||||
assertEquals(Boolean.TRUE, model.getAttribute("captchaSecretConfigured"), "the secret is reported configured");
|
||||
assertFalse(model.asMap().containsValue("hidden-secret"), "the plaintext secret is NEVER in the model");
|
||||
}
|
||||
}
|
||||
+51
@@ -0,0 +1,51 @@
|
||||
package mx.quest.protection;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.List;
|
||||
import mx.quest.runway.plugin.LoadedPlugin;
|
||||
import mx.quest.runway.plugin.PluginDescriptor;
|
||||
import mx.quest.runway.plugin.PluginResolution;
|
||||
import mx.quest.runway.plugin.PluginVersion;
|
||||
import mx.quest.runway.spi.RunwaySpi;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
/**
|
||||
* The shipped descriptor of the essential plugin against the SPI 1.0.0 loader rules: it is
|
||||
* on the kernel's version line ({@code 1.0.0}) and declares the kernel's SPI as its floor, so the mandatory floor can
|
||||
* never block it — a blocked essential plugin would put the whole platform in fail-closed mode.
|
||||
*/
|
||||
class ProtectionDescriptorK4Test {
|
||||
|
||||
private static PluginDescriptor shipped() throws IOException {
|
||||
try (InputStream in = Files.newInputStream(Path.of("plugin.yml"))) { // the module dir (surefire's CWD)
|
||||
PluginDescriptor descriptor = PluginDescriptor.read(in);
|
||||
descriptor.validate();
|
||||
return descriptor;
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void theShippedDescriptorIsOnTheKernelsLineAndDeclaresTheKernelsSpi() throws IOException {
|
||||
PluginDescriptor descriptor = shipped();
|
||||
assertEquals("protection", descriptor.id());
|
||||
assertTrue(descriptor.isEssential());
|
||||
assertEquals("1.0.0", descriptor.version(), "versioned on the kernel's line from rc1");
|
||||
assertEquals(PluginVersion.parse("1.0.0"), descriptor.spiFloor());
|
||||
assertEquals(PluginVersion.parse(RunwaySpi.VERSION).major(), descriptor.spiFloor().major(),
|
||||
"the floor names the kernel's own SPI major line");
|
||||
}
|
||||
|
||||
@Test
|
||||
void theRunningLoaderAcceptsIt() throws IOException {
|
||||
PluginResolution.Result result = PluginResolution.resolve(
|
||||
List.of(new LoadedPlugin(shipped(), Path.of("."))));
|
||||
assertTrue(result.blocked().isEmpty(), "never blocked by the floor rules: " + result.blocked());
|
||||
assertEquals(1, result.loadable().size());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
package mx.quest.protection;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.ui.Model;
|
||||
import org.springframework.validation.support.BindingAwareModelMap;
|
||||
|
||||
/**
|
||||
* The shared screen form logic ({@link ProtectionForm}): a blank captcha-secret field KEEPS the stored secret, a
|
||||
* non-blank one replaces it, the provider is normalized to a known value, non-positive thresholds are floored to
|
||||
* sane defaults (so a save can never lock everyone out), and the GET model exposes the secret only as a boolean —
|
||||
* never its value.
|
||||
*/
|
||||
class ProtectionFormTest {
|
||||
|
||||
private static ProtectionSettings withSecret(String secret) {
|
||||
return new ProtectionSettings(true, 5, 300, 900,
|
||||
new ProtectionSettings.Captcha(true, "recaptcha-v2", "old-site", secret, 0.5));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aBlankSecretFieldKeepsTheStoredSecret() {
|
||||
ProtectionSettings current = withSecret("stored-secret");
|
||||
ProtectionSettings merged = ProtectionForm.merge(current, true, 5, 300, 900, true,
|
||||
"recaptcha-v2", "new-site", " ", 0.5);
|
||||
assertEquals("stored-secret", merged.captcha().secretKey(), "blank field preserves the stored secret");
|
||||
assertEquals("new-site", merged.captcha().siteKey(), "the public site key still updates");
|
||||
}
|
||||
|
||||
@Test
|
||||
void aNonBlankSecretFieldReplacesTheStoredSecret() {
|
||||
ProtectionSettings merged = ProtectionForm.merge(withSecret("stored-secret"), true, 5, 300, 900, true,
|
||||
"recaptcha-v2", "site", " brand-new-secret ", 0.5);
|
||||
assertEquals("brand-new-secret", merged.captcha().secretKey(), "a non-blank secret replaces (and is trimmed)");
|
||||
}
|
||||
|
||||
@Test
|
||||
void anUnknownOrLegacyProviderNormalizesToRecaptchaV2() {
|
||||
ProtectionSettings merged = ProtectionForm.merge(withSecret(""), true, 5, 300, 900, true,
|
||||
"bogus-provider", "site", "", 0.5);
|
||||
assertEquals("recaptcha-v2", merged.captcha().provider());
|
||||
// A dropped legacy provider (Turnstile / hCaptcha) likewise migrates to the v2 default.
|
||||
assertEquals("recaptcha-v2",
|
||||
ProtectionForm.merge(withSecret(""), true, 5, 300, 900, true, "turnstile", "s", "", 0.5)
|
||||
.captcha().provider());
|
||||
// A supported provider (any case) is preserved lower-cased.
|
||||
assertEquals("recaptcha-v3",
|
||||
ProtectionForm.merge(withSecret(""), true, 5, 300, 900, true, "reCAPTCHA-V3", "s", "", 0.5)
|
||||
.captcha().provider());
|
||||
}
|
||||
|
||||
@Test
|
||||
void nonPositiveThresholdsAreFlooredToSaneDefaults() {
|
||||
// Zero/negative thresholds must not lock everyone out — ProtectionSettings' constructor floors them.
|
||||
ProtectionSettings merged = ProtectionForm.merge(withSecret(""), true, 0, -1, 0, false, "recaptcha-v2", "", "", 0.5);
|
||||
assertTrue(merged.maxAttempts() > 0, "maxAttempts floored to a positive default");
|
||||
assertTrue(merged.windowSeconds() > 0, "windowSeconds floored to a positive default");
|
||||
assertTrue(merged.lockoutSeconds() > 0, "lockoutSeconds floored to a positive default");
|
||||
}
|
||||
|
||||
@Test
|
||||
void populateMasksTheSecretAsABooleanOnly() {
|
||||
Model model = new BindingAwareModelMap();
|
||||
ProtectionForm.populate(model, withSecret("s3cr3t"), true);
|
||||
assertEquals(Boolean.TRUE, model.getAttribute("captchaSecretConfigured"));
|
||||
assertEquals(Boolean.TRUE, model.getAttribute("captchaSecretStorable"));
|
||||
assertFalse(model.asMap().containsValue("s3cr3t"), "the plaintext secret is NEVER put into the model");
|
||||
|
||||
Model none = new BindingAwareModelMap();
|
||||
ProtectionForm.populate(none, withSecret(""), false);
|
||||
assertEquals(Boolean.FALSE, none.getAttribute("captchaSecretConfigured"), "no secret → not configured");
|
||||
assertEquals(Boolean.FALSE, none.getAttribute("captchaSecretStorable"), "no cipher → not storable (hint)");
|
||||
}
|
||||
}
|
||||
+219
@@ -0,0 +1,219 @@
|
||||
package mx.quest.protection;
|
||||
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.when;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import mx.quest.runway.authz.AuthorizationService;
|
||||
import mx.quest.runway.authz.AuthzExpressions;
|
||||
import mx.quest.runway.authz.Permission;
|
||||
import mx.quest.runway.authz.PermissionCatalog;
|
||||
import mx.quest.runway.crypto.SecretCipher;
|
||||
import mx.quest.runway.security.RunwayUserDetails;
|
||||
import mx.quest.runway.security.User;
|
||||
import mx.quest.runway.site.Site;
|
||||
import mx.quest.runway.site.SiteResolver;
|
||||
import mx.quest.runway.spi.model.Realm;
|
||||
import mx.quest.runway.storage.StorageLayout;
|
||||
import mx.quest.runway.storage.StorageProperties;
|
||||
import mx.quest.runway.storage.YamlStore;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
|
||||
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
|
||||
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
|
||||
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
import org.springframework.security.web.SecurityFilterChain;
|
||||
import org.springframework.test.context.junit.jupiter.web.SpringJUnitWebConfig;
|
||||
import org.springframework.test.web.servlet.MockMvc;
|
||||
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
|
||||
import org.springframework.web.context.WebApplicationContext;
|
||||
|
||||
/**
|
||||
* The two screens are permission-gated: {@code /__app/protection} on the plugin's own
|
||||
* {@code protection|settings} control point, {@code /__admin/protection} on the kernel {@code CONFIGURE_SITE}
|
||||
* permission. Both {@code @PreAuthorize} through the kernel {@code authz} expression; a principal who fails the
|
||||
* check gets {@code 403}, one who passes reaches the controller (a {@code 3xx} redirect on POST). This proves
|
||||
* the gate is wired; the controllers enforce regardless of menu visibility.
|
||||
*
|
||||
* <p>The principal is placed on the {@link SecurityContextHolder} directly (rather than via
|
||||
* {@code spring-security-test}, which is not on this module's test classpath), which is exactly what
|
||||
* {@code @authz.may} reads.
|
||||
*/
|
||||
@SpringJUnitWebConfig(ProtectionScreenGatingTest.Config.class)
|
||||
class ProtectionScreenGatingTest {
|
||||
|
||||
private static final Permission APP_SETTINGS = new Permission("protection|settings", Realm.APPLICATION);
|
||||
private static final Permission CONFIGURE_SITE = new Permission("CONFIGURE_SITE", Realm.TENANT);
|
||||
|
||||
@Autowired
|
||||
private WebApplicationContext context;
|
||||
@Autowired
|
||||
private AuthorizationService authorization;
|
||||
|
||||
private MockMvc mvc;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
mvc = MockMvcBuilders.webAppContextSetup(context).build();
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void clearContext() {
|
||||
SecurityContextHolder.clearContext();
|
||||
}
|
||||
|
||||
private static void signIn(Realm realm) {
|
||||
User user = new User("op1", "op", "", "Op", "", true, false, realm, Set.of(), List.of());
|
||||
RunwayUserDetails details = new RunwayUserDetails(user);
|
||||
SecurityContextHolder.getContext().setAuthentication(
|
||||
new UsernamePasswordAuthenticationToken(details, "n/a", details.getAuthorities()));
|
||||
}
|
||||
|
||||
/** Asserts the action fails with a method-security access denial (unwrapping any servlet/nested wrapper). */
|
||||
private static void assertDenied(org.junit.jupiter.api.function.Executable action) {
|
||||
Throwable thrown = org.junit.jupiter.api.Assertions.assertThrows(Throwable.class, action);
|
||||
for (Throwable t = thrown; t != null; t = t.getCause()) {
|
||||
if (t instanceof org.springframework.security.authorization.AuthorizationDeniedException) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
org.junit.jupiter.api.Assertions.fail("expected an AuthorizationDeniedException, got: " + thrown);
|
||||
}
|
||||
|
||||
@Test
|
||||
void theAppScreenForbidsAPrincipalWithoutTheControlPoint() {
|
||||
signIn(Realm.APPLICATION);
|
||||
when(authorization.mayAccess(any(), eq(APP_SETTINGS), any())).thenReturn(false);
|
||||
// The @PreAuthorize gate denies before the controller runs — proven by the access-denied it raises. (In the
|
||||
// full app the security chain's ExceptionTranslationFilter maps this to a 403; here the bare method-security
|
||||
// context has no such filter, so the denial surfaces as the exception itself.) The app login policy is a
|
||||
// POST-only save now (the controls render as a panel on the plugin settings page, not a standalone GET).
|
||||
assertDenied(() -> mvc.perform(post("/__app/protection").param("maxAttempts", "5")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void theAppScreenAdmitsAPrincipalWithTheControlPoint() throws Exception {
|
||||
signIn(Realm.APPLICATION);
|
||||
when(authorization.mayAccess(any(), eq(APP_SETTINGS), any())).thenReturn(true);
|
||||
// A POST that passes the gate reaches the controller and redirects (no template render on POST).
|
||||
mvc.perform(post("/__app/protection")
|
||||
.param("honeypotEnabled", "true").param("maxAttempts", "5")
|
||||
.param("windowSeconds", "300").param("lockoutSeconds", "900"))
|
||||
.andExpect(status().is3xxRedirection());
|
||||
}
|
||||
|
||||
@Test
|
||||
void thePerSiteScreenForbidsAPrincipalWithoutConfigureSite() {
|
||||
signIn(Realm.TENANT);
|
||||
when(authorization.mayAccess(any(), eq(CONFIGURE_SITE), any())).thenReturn(false);
|
||||
assertDenied(() -> mvc.perform(get("/__admin/protection")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void thePerSiteScreenAdmitsAPrincipalWithConfigureSite() throws Exception {
|
||||
signIn(Realm.TENANT);
|
||||
when(authorization.mayAccess(any(), eq(CONFIGURE_SITE), any())).thenReturn(true);
|
||||
// The per-site form is honeypot + CAPTCHA (no lockout — that's app-scope); a passing gate reaches the save.
|
||||
mvc.perform(post("/__admin/protection")
|
||||
.param("honeypotEnabled", "true").param("captchaEnabled", "false"))
|
||||
.andExpect(status().is3xxRedirection());
|
||||
}
|
||||
|
||||
/**
|
||||
* A minimal web context: method security on, a permit-all chain (the {@code @PreAuthorize} is the gate under
|
||||
* test), the {@code authz} expression bean over a mocked {@link AuthorizationService}/{@link PermissionCatalog},
|
||||
* the two controllers + the store. No kernel security chains are needed — the request principal is placed on
|
||||
* the {@link SecurityContextHolder} by the test.
|
||||
*/
|
||||
@Configuration
|
||||
@org.springframework.web.servlet.config.annotation.EnableWebMvc
|
||||
@EnableWebSecurity
|
||||
@EnableMethodSecurity
|
||||
static class Config {
|
||||
|
||||
@Bean
|
||||
SecurityFilterChain chain(HttpSecurity http) throws Exception {
|
||||
http.csrf(c -> c.disable()).authorizeHttpRequests(a -> a.anyRequest().permitAll());
|
||||
return http.build();
|
||||
}
|
||||
|
||||
@Bean
|
||||
AuthorizationService authorizationService() {
|
||||
return mock(AuthorizationService.class);
|
||||
}
|
||||
|
||||
@Bean
|
||||
PermissionCatalog permissionCatalog() {
|
||||
PermissionCatalog catalog = mock(PermissionCatalog.class);
|
||||
when(catalog.find("protection|settings")).thenReturn(Optional.of(APP_SETTINGS));
|
||||
when(catalog.find("CONFIGURE_SITE")).thenReturn(Optional.of(CONFIGURE_SITE));
|
||||
return catalog;
|
||||
}
|
||||
|
||||
@Bean
|
||||
SiteResolver siteResolver() {
|
||||
Site site = mock(Site.class);
|
||||
when(site.id()).thenReturn("acme");
|
||||
SiteResolver resolver = mock(SiteResolver.class);
|
||||
when(resolver.current()).thenReturn(Optional.of(site));
|
||||
return resolver;
|
||||
}
|
||||
|
||||
@Bean("authz")
|
||||
AuthzExpressions authz(AuthorizationService authz, PermissionCatalog catalog, SiteResolver siteResolver) {
|
||||
return new AuthzExpressions(authz, catalog, siteResolver);
|
||||
}
|
||||
|
||||
@Bean
|
||||
ProtectionConfigStore store() {
|
||||
StorageProperties props = new StorageProperties();
|
||||
props.setExternal(java.nio.file.Path.of(System.getProperty("java.io.tmpdir"), "runway-gating-"
|
||||
+ System.nanoTime()));
|
||||
StorageLayout layout = StorageLayout.from(props);
|
||||
return new ProtectionConfigStore(new ProtectionProperties(), layout, new YamlStore(), noCipher());
|
||||
}
|
||||
|
||||
@Bean
|
||||
AppProtectionController appController(ProtectionConfigStore store,
|
||||
@org.springframework.beans.factory.annotation.Qualifier("operatorAwareMessageSource")
|
||||
org.springframework.context.MessageSource messages) {
|
||||
return new AppProtectionController(store, messages);
|
||||
}
|
||||
|
||||
@Bean
|
||||
SiteProtectionController siteController(ProtectionConfigStore store,
|
||||
@org.springframework.beans.factory.annotation.Qualifier("operatorAwareMessageSource")
|
||||
org.springframework.context.MessageSource messages) {
|
||||
return new SiteProtectionController(
|
||||
() -> Optional.of(new mx.quest.runway.spi.model.SiteView("acme", "Acme",
|
||||
java.util.Locale.ENGLISH, java.util.List.of(), null)), store, messages);
|
||||
}
|
||||
|
||||
@Bean("operatorAwareMessageSource")
|
||||
org.springframework.context.MessageSource messages() {
|
||||
return new org.springframework.context.support.StaticMessageSource();
|
||||
}
|
||||
|
||||
private static SecretCipher noCipher() {
|
||||
return new SecretCipher() {
|
||||
@Override public boolean isAvailable() { return false; }
|
||||
@Override public String encrypt(String plaintext) { throw new IllegalStateException("no key"); }
|
||||
@Override public String decrypt(String value) { return value; }
|
||||
@Override public boolean isEncrypted(String value) { return value != null && value.startsWith("ENC("); }
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
+257
@@ -0,0 +1,257 @@
|
||||
package mx.quest.protection;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import mx.quest.runway.authz.AuthorizationService;
|
||||
import mx.quest.runway.authz.PermissionCatalog;
|
||||
import mx.quest.runway.console.MenuRegistry;
|
||||
import mx.quest.runway.console.OperatorProperties;
|
||||
import mx.quest.runway.console.OperatorShellModel;
|
||||
import mx.quest.runway.console.PluginTemplateResolver;
|
||||
import mx.quest.runway.crypto.SecretCipher;
|
||||
import mx.quest.runway.plugin.LoadedPlugin;
|
||||
import mx.quest.runway.plugin.PluginDescriptor;
|
||||
import mx.quest.runway.plugin.RunningPlugins;
|
||||
import mx.quest.runway.site.Site;
|
||||
import mx.quest.runway.site.SiteResolver;
|
||||
import mx.quest.runway.storage.StorageLayout;
|
||||
import mx.quest.runway.storage.StorageProperties;
|
||||
import mx.quest.runway.storage.YamlStore;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.Mockito;
|
||||
import org.springframework.context.support.ReloadableResourceBundleMessageSource;
|
||||
import org.springframework.context.support.StaticApplicationContext;
|
||||
import org.springframework.core.convert.support.DefaultConversionService;
|
||||
import org.springframework.mock.web.MockHttpServletRequest;
|
||||
import org.springframework.mock.web.MockHttpServletResponse;
|
||||
import org.springframework.mock.web.MockServletContext;
|
||||
import org.springframework.ui.Model;
|
||||
import org.springframework.validation.support.BindingAwareModelMap;
|
||||
import org.springframework.web.context.request.RequestContextHolder;
|
||||
import org.springframework.web.context.request.ServletRequestAttributes;
|
||||
import org.thymeleaf.context.IContext;
|
||||
import org.thymeleaf.context.WebContext;
|
||||
import org.thymeleaf.spring6.SpringTemplateEngine;
|
||||
import org.thymeleaf.spring6.expression.ThymeleafEvaluationContext;
|
||||
import org.thymeleaf.templatemode.TemplateMode;
|
||||
import org.thymeleaf.templateresolver.ClassLoaderTemplateResolver;
|
||||
import org.thymeleaf.web.IWebExchange;
|
||||
import org.thymeleaf.web.servlet.JakartaServletWebApplication;
|
||||
|
||||
/**
|
||||
* The two protection render surfaces:
|
||||
* <ul>
|
||||
* <li>The <b>app login-protection PANEL</b> ({@code templates/admin-app.html}) — a bare fragment bound to the
|
||||
* plugin's own {@link AppProtectionPanel} bean via {@code ${@appProtectionPanel.*}}. This test RENDERS it with
|
||||
* that bean in scope and is the regression guard for a real trap: {@code th:attr} evaluates in a RESTRICTED
|
||||
* expression context that forbids {@code @bean} access, so every pre-filled field must use a <b>dedicated</b>
|
||||
* processor ({@code th:value} / {@code th:placeholder} / {@code th:checked} / …), never {@code th:attr}. A
|
||||
* relapse to {@code th:attr} would make this test (and the live page) throw.</li>
|
||||
* <li>The <b>per-site screen</b> ({@code __plugin__/protection/site-protection}) — still a {@code contentTemplate}
|
||||
* rendered inside {@code op-layout} with the admin topbar (the tenant realm keeps its dedicated screen).</li>
|
||||
* </ul>
|
||||
*/
|
||||
class ProtectionScreenRenderTest {
|
||||
|
||||
/** The plugin project root (where templates/ + i18n/ live) — the CWD when the module's tests run. */
|
||||
private static final Path PLUGIN_ROOT = Path.of(System.getProperty("user.dir"));
|
||||
|
||||
@AfterEach
|
||||
void clearRequest() {
|
||||
RequestContextHolder.resetRequestAttributes();
|
||||
}
|
||||
|
||||
private static PluginDescriptor descriptor() throws IOException {
|
||||
try (InputStream in = Files.newInputStream(PLUGIN_ROOT.resolve("plugin.yml"))) {
|
||||
return PluginDescriptor.read(in);
|
||||
}
|
||||
}
|
||||
|
||||
private static SpringTemplateEngine engine(RunningPlugins running) {
|
||||
ClassLoaderTemplateResolver operator = new ClassLoaderTemplateResolver();
|
||||
operator.setPrefix("templates/");
|
||||
operator.setSuffix(".html");
|
||||
operator.setResolvablePatterns(Set.of("operator/*"));
|
||||
operator.setTemplateMode(TemplateMode.HTML);
|
||||
operator.setUseDecoupledLogic(true);
|
||||
operator.setCacheable(false);
|
||||
operator.setOrder(2);
|
||||
|
||||
PluginTemplateResolver plugin = new PluginTemplateResolver(running);
|
||||
plugin.setCacheable(false);
|
||||
|
||||
ReloadableResourceBundleMessageSource messages = new ReloadableResourceBundleMessageSource();
|
||||
messages.setBasenames("classpath:i18n/operator-messages",
|
||||
"file:" + PLUGIN_ROOT.resolve("i18n").resolve("messages"));
|
||||
messages.setDefaultEncoding("UTF-8");
|
||||
messages.setUseCodeAsDefaultMessage(true);
|
||||
// As in production (OperatorMessageSource): no fallback to the HOST's locale. Without this the English
|
||||
// render resolved Spanish on a workstation whose LANG is es_MX — a test that passed or failed by machine.
|
||||
messages.setFallbackToSystemLocale(false);
|
||||
|
||||
SpringTemplateEngine engine = new SpringTemplateEngine();
|
||||
engine.addTemplateResolver(operator);
|
||||
engine.addTemplateResolver(plugin);
|
||||
engine.setTemplateEngineMessageSource(messages);
|
||||
return engine;
|
||||
}
|
||||
|
||||
private static RunningPlugins runningWithProtection() throws IOException {
|
||||
LoadedPlugin loaded = new LoadedPlugin(descriptor(), PLUGIN_ROOT);
|
||||
RunningPlugins running = Mockito.mock(RunningPlugins.class);
|
||||
Mockito.when(running.installed()).thenReturn(List.of(loaded));
|
||||
return running;
|
||||
}
|
||||
|
||||
private static OperatorShellModel shellModel(RunningPlugins running, SiteResolver siteResolver) {
|
||||
AuthorizationService authz = Mockito.mock(AuthorizationService.class);
|
||||
PermissionCatalog catalog = Mockito.mock(PermissionCatalog.class);
|
||||
MenuRegistry menu = new MenuRegistry(running, authz, catalog);
|
||||
SecretCipher cipher = Mockito.mock(SecretCipher.class);
|
||||
Mockito.when(cipher.isAvailable()).thenReturn(true);
|
||||
mx.quest.runway.mail.PlatformMailer mailer = Mockito.mock(mx.quest.runway.mail.PlatformMailer.class);
|
||||
Mockito.when(mailer.isConfigured()).thenReturn(true);
|
||||
@SuppressWarnings("unchecked")
|
||||
org.springframework.beans.factory.ObjectProvider<org.springframework.boot.info.BuildProperties> buildProps =
|
||||
Mockito.mock(org.springframework.beans.factory.ObjectProvider.class);
|
||||
return new OperatorShellModel(menu, siteResolver, new OperatorProperties(), cipher, mailer, buildProps);
|
||||
}
|
||||
|
||||
// --- The app login-protection PANEL (fragment bound to the plugin's own bean) ---------------------------------
|
||||
|
||||
/** An {@link AppProtectionPanel} over a real store seeded with {@code settings} (written to a temp data dir). */
|
||||
private static AppProtectionPanel panel(ProtectionSettings settings) throws IOException {
|
||||
StorageProperties props = new StorageProperties();
|
||||
props.setExternal(Files.createTempDirectory("prot-panel"));
|
||||
ProtectionConfigStore store = new ProtectionConfigStore(
|
||||
new ProtectionProperties(), StorageLayout.from(props), new YamlStore(), passthroughCipher());
|
||||
store.saveApp(settings);
|
||||
return new AppProtectionPanel(store);
|
||||
}
|
||||
|
||||
/** Renders the bare admin-app fragment with the {@code appProtectionPanel} bean in scope. */
|
||||
private String renderPanel(AppProtectionPanel panel) throws IOException {
|
||||
RunningPlugins running = runningWithProtection();
|
||||
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/__app/plugins/protection/settings");
|
||||
request.setRequestURI("/__app/plugins/protection/settings");
|
||||
RequestContextHolder.setRequestAttributes(new ServletRequestAttributes(request));
|
||||
IContext ctx = webContext(request, new BindingAwareModelMap(), "appProtectionPanel", panel);
|
||||
return engine(running).process("__plugin__/protection/admin-app", ctx);
|
||||
}
|
||||
|
||||
@Test
|
||||
void theAppPanelBindsItsFieldsFromThePluginBean() throws IOException {
|
||||
ProtectionSettings settings = new ProtectionSettings(true, 7, 300, 900,
|
||||
new ProtectionSettings.Captcha(true, "recaptcha-v2", "public-site-key", "", 0.5));
|
||||
String html = renderPanel(panel(settings));
|
||||
|
||||
assertTrue(html.contains("action=\"/__app/protection\""), "the panel's immediate-apply form posts here");
|
||||
assertTrue(html.contains("Login protection"), "plugin i18n label resolved (protection.screen.heading)");
|
||||
assertTrue(html.contains("reCAPTCHA v2"), "a provider option label resolved from plugin i18n");
|
||||
assertTrue(html.contains("value=\"7\""), "the field pre-fills from the bean (maxAttempts=7 via th:value)");
|
||||
assertTrue(html.contains("public-site-key"), "the PUBLIC site key is rendered (it is not secret)");
|
||||
assertFalse(html.contains("protection.screen.heading"), "the raw plugin i18n key must not leak");
|
||||
// The panel is a fragment inside the kernel's plugin-settings page; its own markup passes the audit.
|
||||
List<String> problems = ConsoleA11yAudit.audit("admin-app panel", html, false);
|
||||
assertTrue(problems.isEmpty(), String.join("\n", problems));
|
||||
}
|
||||
|
||||
@Test
|
||||
void theCaptchaSecretIsNeverRenderedIntoTheInput() throws IOException {
|
||||
ProtectionSettings withSecret = new ProtectionSettings(true, 5, 300, 900,
|
||||
new ProtectionSettings.Captcha(true, "recaptcha-v2", "public-site-key", "TOP-SECRET-VALUE", 0.5));
|
||||
String html = renderPanel(panel(withSecret));
|
||||
|
||||
assertFalse(html.contains("TOP-SECRET-VALUE"), "the captcha secret is NEVER rendered into the page");
|
||||
assertTrue(html.contains("public-site-key"), "the PUBLIC site key is rendered (it is not secret)");
|
||||
}
|
||||
|
||||
// --- The per-site screen (unchanged: a full contentTemplate rendered inside op-layout) ------------------------
|
||||
|
||||
@Test
|
||||
void theSiteScreenRendersInsideOpLayoutWithTheAdminChrome() throws IOException {
|
||||
Site site = Mockito.mock(Site.class);
|
||||
Mockito.when(site.id()).thenReturn("acme");
|
||||
SiteResolver siteResolver = Mockito.mock(SiteResolver.class);
|
||||
Mockito.when(siteResolver.current()).thenReturn(Optional.of(site));
|
||||
|
||||
RunningPlugins running = runningWithProtection();
|
||||
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/__admin/protection");
|
||||
request.setRequestURI("/__admin/protection");
|
||||
RequestContextHolder.setRequestAttributes(new ServletRequestAttributes(request));
|
||||
Model model = new BindingAwareModelMap();
|
||||
shellModel(running, siteResolver).populate(model, request, null);
|
||||
ProtectionForm.populate(model, ProtectionSettings.defaults(), true);
|
||||
model.addAttribute("contentTemplate", "__plugin__/protection/site-protection");
|
||||
model.addAttribute("pageTitleKey", "protection.screen.site.title");
|
||||
String html = engine(running).process("operator/op-layout", webContext(request, model, null, null));
|
||||
|
||||
assertTrue(html.contains("rw-topbar-admin"), "plugin screen rendered inside op-layout with the admin topbar");
|
||||
assertFalse(html.contains("rw-topbar-app"));
|
||||
assertTrue(html.contains("action=\"/__admin/protection\""), "the per-site plugin form is present");
|
||||
assertTrue(html.contains("Login protection"));
|
||||
// The whole page (kernel chrome + this screen) passes the console's accessibility audit.
|
||||
List<String> problems = ConsoleA11yAudit.audit("/__admin/protection", html);
|
||||
assertTrue(problems.isEmpty(), String.join("\n", problems));
|
||||
}
|
||||
|
||||
// --- Thymeleaf harness ---------------------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* A web-aware Thymeleaf context carrying the model + a Spring evaluation context. When {@code beanName} is
|
||||
* non-null the bean is registered so {@code ${@beanName...}} resolves (the panel fragment reads its bean this
|
||||
* way). A {@link WebContext} (not a bare {@code Context}) is needed because the topbar builds
|
||||
* {@code @{/__ui-lang}} link expressions.
|
||||
*/
|
||||
private static IContext webContext(MockHttpServletRequest request, Model model, String beanName, Object bean) {
|
||||
MockServletContext servletContext = new MockServletContext();
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
JakartaServletWebApplication application = JakartaServletWebApplication.buildApplication(servletContext);
|
||||
IWebExchange exchange = application.buildExchange(request, response);
|
||||
WebContext ctx = new WebContext(exchange, Locale.ENGLISH);
|
||||
model.asMap().forEach(ctx::setVariable);
|
||||
StaticApplicationContext appContext = new StaticApplicationContext();
|
||||
if (beanName != null) {
|
||||
appContext.getBeanFactory().registerSingleton(beanName, bean);
|
||||
}
|
||||
appContext.refresh();
|
||||
ctx.setVariable(ThymeleafEvaluationContext.THYMELEAF_EVALUATION_CONTEXT_CONTEXT_VARIABLE_NAME,
|
||||
new ThymeleafEvaluationContext(appContext, DefaultConversionService.getSharedInstance()));
|
||||
return ctx;
|
||||
}
|
||||
|
||||
/** A pass-through cipher: available (so a secret can be "stored"), identity encrypt/decrypt — enough for render. */
|
||||
private static SecretCipher passthroughCipher() {
|
||||
return new SecretCipher() {
|
||||
@Override
|
||||
public boolean isAvailable() {
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String encrypt(String plaintext) {
|
||||
return plaintext;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String decrypt(String value) {
|
||||
return value;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isEncrypted(String value) {
|
||||
return false;
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
+211
@@ -0,0 +1,211 @@
|
||||
package mx.quest.protection;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
import java.nio.file.Path;
|
||||
import java.util.List;
|
||||
import mx.quest.runway.protect.EdgeRequest;
|
||||
import mx.quest.runway.protect.EdgeVerdict;
|
||||
import mx.quest.runway.protect.RejectionOutcome;
|
||||
import mx.quest.runway.storage.YamlStore;
|
||||
import mx.quest.runway.web.CidrSet;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
|
||||
/** Allowlist passes, a blocklisted IP is 403 (before the bucket), and an exhausted bucket is 429 with a Retry-After. */
|
||||
class RateLimitEdgeGuardTest {
|
||||
|
||||
@TempDir
|
||||
Path dir;
|
||||
|
||||
private static EdgeRequest from(String ip) {
|
||||
return new EdgeRequest(ip, "GET", "/");
|
||||
}
|
||||
|
||||
private IpBlocklist emptyBlocklist(CidrSet allowlist) {
|
||||
return new IpBlocklist(dir.resolve("blocklist.yml"), new YamlStore(), allowlist, () -> 1_000L);
|
||||
}
|
||||
|
||||
private TokenBucketRateLimiter limiter(int capacity, double refill) {
|
||||
return new TokenBucketRateLimiter(capacity, refill, 10, () -> 0L);
|
||||
}
|
||||
|
||||
@Test
|
||||
void anAllowlistedIpPassesWithoutConsumingTheBucket() {
|
||||
CidrSet allow = CidrSet.of(List.of("10.0.0.0/8"));
|
||||
RateLimitEdgeGuard guard = new RateLimitEdgeGuard(allow, emptyBlocklist(allow), limiter(1, 0.0));
|
||||
assertTrue(guard.check(from("10.1.2.3")).allowed());
|
||||
assertTrue(guard.check(from("10.1.2.3")).allowed(), "allowlist short-circuits before the bucket");
|
||||
}
|
||||
|
||||
/**
|
||||
* Loopback is NOT exempt from the rate limit (the descriptor said it was until rc1): behind a same-host proxy whose
|
||||
* forwarded address is not trusted, every client arrives as {@code 127.0.0.1}, and an implicit exemption would
|
||||
* switch the limit off for the whole internet. What loopback does get is never being BLOCKED, so its throttles
|
||||
* never escalate — the safety rail against auto-blocking the operator's own proxy or probe.
|
||||
*/
|
||||
@Test
|
||||
void loopbackIsRateLimitedButNeverEscalatesIntoABlock() {
|
||||
CidrSet allow = CidrSet.of(List.of());
|
||||
IpBlocklist blocklist = emptyBlocklist(allow);
|
||||
TokenBucketRateLimiter escalating = new TokenBucketRateLimiter(2, 0.0, 10, () -> 0L, blocklist,
|
||||
new TokenBucketRateLimiter.AutoBlock(true, 1, 60, 900), () -> 1_000L);
|
||||
RateLimitEdgeGuard guard = new RateLimitEdgeGuard(allow, blocklist, escalating);
|
||||
for (String loopback : List.of("127.0.0.1", "::1")) {
|
||||
assertTrue(guard.check(from(loopback)).allowed());
|
||||
assertTrue(guard.check(from(loopback)).allowed());
|
||||
EdgeVerdict throttled = guard.check(from(loopback));
|
||||
assertFalse(throttled.allowed(), loopback + " must be rate-limited like any client");
|
||||
assertEquals(429, throttled.status());
|
||||
assertEquals(1, throttled.retryAfterSeconds(), "a throttle, not an auto-block's remaining time");
|
||||
assertEquals(null, blocklist.match(loopback), loopback + " must never be auto-blocked");
|
||||
}
|
||||
// The control: the same breach from a routable address DOES escalate (threshold 1), so the absence above is
|
||||
// the loopback rail, not a disabled escalation.
|
||||
guard.check(from("203.0.113.5"));
|
||||
guard.check(from("203.0.113.5"));
|
||||
guard.check(from("203.0.113.5"));
|
||||
assertEquals("blocklist-auto", blocklist.match("203.0.113.5").kind());
|
||||
}
|
||||
|
||||
/** Listing loopback is how an operator exempts a same-host probe — it then passes before the bucket. */
|
||||
@Test
|
||||
void loopbackIsExemptOnlyWhenListed() {
|
||||
CidrSet allow = CidrSet.of(List.of("127.0.0.1/32"));
|
||||
RateLimitEdgeGuard guard = new RateLimitEdgeGuard(allow, emptyBlocklist(allow), limiter(1, 0.0));
|
||||
assertTrue(guard.check(from("127.0.0.1")).allowed());
|
||||
assertTrue(guard.check(from("127.0.0.1")).allowed(), "listed: never throttled");
|
||||
assertTrue(guard.check(from("::1")).allowed());
|
||||
assertFalse(guard.check(from("::1")).allowed(), "only what is listed is exempt");
|
||||
}
|
||||
|
||||
@Test
|
||||
void aBlocklistedIpIsForbiddenBeforeTheBucket() {
|
||||
CidrSet allow = CidrSet.of(List.of());
|
||||
IpBlocklist blocklist = emptyBlocklist(allow);
|
||||
blocklist.block("203.0.113.7", 900, "manual", true);
|
||||
// A bucket of capacity 0-effective would still 429; prove the 403 wins (checked first, no token consumed).
|
||||
RateLimitEdgeGuard guard = new RateLimitEdgeGuard(allow, blocklist, limiter(100, 1.0));
|
||||
EdgeVerdict verdict = guard.check(from("203.0.113.7"));
|
||||
assertFalse(verdict.allowed());
|
||||
assertEquals(403, verdict.status());
|
||||
}
|
||||
|
||||
@Test
|
||||
void exceedingTheRateLimitIs429WithRetryAfter() {
|
||||
CidrSet allow = CidrSet.of(List.of());
|
||||
RateLimitEdgeGuard guard = new RateLimitEdgeGuard(allow, emptyBlocklist(allow), limiter(2, 0.0));
|
||||
assertTrue(guard.check(from("1.2.3.4")).allowed());
|
||||
assertTrue(guard.check(from("1.2.3.4")).allowed());
|
||||
EdgeVerdict verdict = guard.check(from("1.2.3.4"));
|
||||
assertFalse(verdict.allowed());
|
||||
assertEquals(429, verdict.status());
|
||||
assertEquals(1, verdict.retryAfterSeconds());
|
||||
}
|
||||
|
||||
// ---- an auto-block is back-pressure, not a ban -----------------------------------------------
|
||||
|
||||
/**
|
||||
* The case that costs indexing: an auto-escalated block answers {@code 429} with the real remaining time.
|
||||
*
|
||||
* <p>The clock is pinned at 1000, so a 900 s block lifts at 1900 and the header must say 900 — not a
|
||||
* constant, not the configured duration, but what is actually left. A crawler that is told "forbidden"
|
||||
* with no retry time may stop coming back for what is a fifteen-minute time-out.
|
||||
*/
|
||||
@Test
|
||||
void anAutoEscalatedBlockIs429WithTheRemainingTime() {
|
||||
CidrSet allow = CidrSet.of(List.of());
|
||||
IpBlocklist blocklist = emptyBlocklist(allow);
|
||||
blocklist.block("198.51.100.9", 900, "auto: 60 breaches", false);
|
||||
|
||||
EdgeVerdict verdict =
|
||||
new RateLimitEdgeGuard(allow, blocklist, limiter(100, 1.0)).check(from("198.51.100.9"));
|
||||
|
||||
assertEquals(429, verdict.status(), "an auto-block is the rate limiter escalating, not a policy ban");
|
||||
assertEquals(900, verdict.retryAfterSeconds());
|
||||
assertEquals("blocklist-auto", verdict.reason(), "the metric/log tag must still say which kind it was");
|
||||
}
|
||||
|
||||
/**
|
||||
* An operator ban stays {@code 403} with no retry time.
|
||||
*
|
||||
* <p>This is the half that keeps the change honest: {@code 429} is not "nicer", it is a specific claim
|
||||
* that the caller may return shortly. For a deliberate ban that claim would be false.
|
||||
*/
|
||||
@Test
|
||||
void anOperatorBanStays403WithNoRetryTime() {
|
||||
CidrSet allow = CidrSet.of(List.of());
|
||||
IpBlocklist blocklist = emptyBlocklist(allow);
|
||||
blocklist.block("203.0.113.7", 900, "manual", true);
|
||||
|
||||
EdgeVerdict verdict =
|
||||
new RateLimitEdgeGuard(allow, blocklist, limiter(100, 1.0)).check(from("203.0.113.7"));
|
||||
|
||||
assertEquals(403, verdict.status());
|
||||
assertEquals(0, verdict.retryAfterSeconds(), "there is no honest retry time for a deliberate ban");
|
||||
}
|
||||
|
||||
/** An indefinite auto-block has no expiry to report, so it falls back to 403 rather than inventing one. */
|
||||
@Test
|
||||
void anIndefiniteAutoBlockFallsBackTo403() {
|
||||
CidrSet allow = CidrSet.of(List.of());
|
||||
IpBlocklist blocklist = emptyBlocklist(allow);
|
||||
blocklist.block("198.51.100.10", 0, "auto, no expiry", false);
|
||||
|
||||
EdgeVerdict verdict =
|
||||
new RateLimitEdgeGuard(allow, blocklist, limiter(100, 1.0)).check(from("198.51.100.10"));
|
||||
|
||||
assertEquals(403, verdict.status());
|
||||
assertEquals(0, verdict.retryAfterSeconds());
|
||||
}
|
||||
|
||||
/**
|
||||
* The remaining time counts down — it is read from the block, not from the configured duration.
|
||||
*
|
||||
* <p>A fixed {@code Retry-After} equal to the block length would look right in every single-instant test
|
||||
* and would keep telling a crawler to wait the full fifteen minutes one second before the block lifts.
|
||||
*/
|
||||
@Test
|
||||
void theRetryTimeCountsDownAsTheBlockRunsOut() {
|
||||
CidrSet allow = CidrSet.of(List.of());
|
||||
long[] now = {1_000L};
|
||||
IpBlocklist blocklist =
|
||||
new IpBlocklist(dir.resolve("b.yml"), new YamlStore(), allow, () -> now[0]);
|
||||
blocklist.block("198.51.100.11", 900, "auto", false);
|
||||
RateLimitEdgeGuard guard = new RateLimitEdgeGuard(allow, blocklist, limiter(100, 1.0));
|
||||
|
||||
now[0] = 1_800L;
|
||||
assertEquals(100, guard.check(from("198.51.100.11")).retryAfterSeconds());
|
||||
|
||||
now[0] = 1_899L;
|
||||
assertEquals(1, guard.check(from("198.51.100.11")).retryAfterSeconds(), "never 0 while still blocked");
|
||||
|
||||
now[0] = 1_901L;
|
||||
assertTrue(guard.check(from("198.51.100.11")).allowed(), "and then the block is simply over");
|
||||
}
|
||||
|
||||
/**
|
||||
* Every rejection this guard can produce is declared, and nothing it cannot.
|
||||
*
|
||||
* <p>Written as an exact set rather than a containment check: the risk runs in both directions. A missing
|
||||
* pair leaves that series absent until first use — the defect this fixes — and a spurious pair publishes a
|
||||
* permanent zero for a response no code path produces, which reads as evidence that it never happens.
|
||||
*
|
||||
* <p>{@code blocklist-auto} legitimately appears under both statuses (429 with a remaining time, 403 when
|
||||
* the block is indefinite); the three tests above pin that both are reachable.
|
||||
*/
|
||||
@Test
|
||||
void theGuardDeclaresExactlyTheRejectionsItCanProduce() {
|
||||
CidrSet allow = CidrSet.of(List.of());
|
||||
var declared = new RateLimitEdgeGuard(allow, emptyBlocklist(allow), limiter(1, 0.0)).declaredOutcomes();
|
||||
|
||||
assertEquals(java.util.Set.of(
|
||||
new RejectionOutcome(429, "rate-limit"),
|
||||
new RejectionOutcome(429, "blocklist-auto"),
|
||||
new RejectionOutcome(403, "blocklist-auto"),
|
||||
new RejectionOutcome(403, "blocklist-manual"),
|
||||
new RejectionOutcome(403, "blocklist-cidr")), declared);
|
||||
}
|
||||
}
|
||||
+109
@@ -0,0 +1,109 @@
|
||||
package mx.quest.protection;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
import java.nio.file.Path;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.atomic.AtomicLong;
|
||||
import mx.quest.runway.storage.YamlStore;
|
||||
import mx.quest.runway.web.CidrSet;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
|
||||
/**
|
||||
* The rate limiter's auto-escalation into the blocklist: an IP throttled {@code breachThreshold} times within the
|
||||
* window is auto-blocked; a loopback/allowlisted IP never is (the block is refused). Plus the offenders tally.
|
||||
*/
|
||||
class RateLimiterAutoEscalationTest {
|
||||
|
||||
@TempDir
|
||||
Path dir;
|
||||
|
||||
private final AtomicLong millis = new AtomicLong(0L);
|
||||
|
||||
private IpBlocklist blocklist(CidrSet allowlist) {
|
||||
// The blocklist clock is in SECONDS; keep it fixed — we assert on membership, not on block expiry here.
|
||||
return new IpBlocklist(dir.resolve("blocklist.yml"), new YamlStore(), allowlist, () -> 0L);
|
||||
}
|
||||
|
||||
/** A limiter with capacity 1 / no refill (so every request after the first throttles) and the given auto-block. */
|
||||
private TokenBucketRateLimiter limiter(IpBlocklist blocklist, int threshold, long windowSeconds) {
|
||||
return new TokenBucketRateLimiter(1, 0.0, 1_000, () -> 0L, blocklist,
|
||||
new TokenBucketRateLimiter.AutoBlock(true, threshold, windowSeconds, 900), millis::get);
|
||||
}
|
||||
|
||||
@Test
|
||||
void anIpIsAutoBlockedAfterBreachThresholdThrottlesInTheWindow() {
|
||||
IpBlocklist blocklist = blocklist(CidrSet.of(List.of()));
|
||||
TokenBucketRateLimiter limiter = limiter(blocklist, 3, 60);
|
||||
|
||||
assertTrue(limiter.tryAcquire("9.9.9.9"), "first request consumes the only token");
|
||||
assertFalse(blocklist.isBlocked("9.9.9.9"));
|
||||
// Three throttles reach the threshold and trigger the auto-block.
|
||||
assertFalse(limiter.tryAcquire("9.9.9.9")); // breach 1
|
||||
assertFalse(blocklist.isBlocked("9.9.9.9"));
|
||||
assertFalse(limiter.tryAcquire("9.9.9.9")); // breach 2
|
||||
assertFalse(blocklist.isBlocked("9.9.9.9"));
|
||||
assertFalse(limiter.tryAcquire("9.9.9.9")); // breach 3 => auto-block
|
||||
assertTrue(blocklist.isBlocked("9.9.9.9"), "the 3rd throttle in the window auto-blocks the IP");
|
||||
|
||||
// The auto block was NOT persisted (in-memory only).
|
||||
assertFalse(blocklist.list().isEmpty());
|
||||
assertFalse(blocklist.list().get(0).manual(), "the auto block is not a manual (persisted) entry");
|
||||
}
|
||||
|
||||
@Test
|
||||
void throttlesOutsideTheWindowDoNotAccumulateToABlock() {
|
||||
IpBlocklist blocklist = blocklist(CidrSet.of(List.of()));
|
||||
TokenBucketRateLimiter limiter = limiter(blocklist, 3, 60); // 60s window
|
||||
|
||||
limiter.tryAcquire("8.8.8.8"); // token consumed
|
||||
limiter.tryAcquire("8.8.8.8"); // breach 1 at t=0
|
||||
millis.set(120_000L); // +120s — the first breach falls out of the 60s window
|
||||
limiter.tryAcquire("8.8.8.8"); // breach 2 (only 1 in window after prune, so this makes 1)
|
||||
millis.set(121_000L);
|
||||
limiter.tryAcquire("8.8.8.8"); // still under threshold within the window
|
||||
assertFalse(blocklist.isBlocked("8.8.8.8"), "spread-out throttles never reach the threshold in one window");
|
||||
}
|
||||
|
||||
@Test
|
||||
void escalationNeverBlocksAnAllowlistedOrLoopbackIp() {
|
||||
IpBlocklist blocklist = blocklist(CidrSet.of(List.of("10.0.0.0/8")));
|
||||
TokenBucketRateLimiter limiter = limiter(blocklist, 2, 60);
|
||||
|
||||
for (int i = 0; i < 10; i++) {
|
||||
limiter.tryAcquire("10.1.2.3"); // hammer an allowlisted IP
|
||||
}
|
||||
assertFalse(blocklist.isBlocked("10.1.2.3"), "an allowlisted IP is never auto-blocked (block refused)");
|
||||
}
|
||||
|
||||
@Test
|
||||
void offendersAreTrackedByThrottledCountDescending() {
|
||||
IpBlocklist blocklist = blocklist(CidrSet.of(List.of()));
|
||||
// High threshold so nothing auto-blocks — we only want the offenders tally here.
|
||||
TokenBucketRateLimiter limiter = limiter(blocklist, 1_000, 60);
|
||||
|
||||
limiter.tryAcquire("1.1.1.1"); // token
|
||||
limiter.tryAcquire("1.1.1.1"); // throttled x1
|
||||
limiter.tryAcquire("2.2.2.2"); // token
|
||||
limiter.tryAcquire("2.2.2.2"); // throttled
|
||||
limiter.tryAcquire("2.2.2.2"); // throttled x2
|
||||
|
||||
List<TokenBucketRateLimiter.Offender> top = limiter.topOffenders(10);
|
||||
assertEquals(2, top.size());
|
||||
assertEquals("2.2.2.2", top.get(0).ip(), "the busiest throttled IP is first");
|
||||
assertEquals(2, top.get(0).throttled());
|
||||
assertEquals("1.1.1.1", top.get(1).ip());
|
||||
assertEquals(1, top.get(1).throttled());
|
||||
}
|
||||
|
||||
@Test
|
||||
void offendersOnlyIncludeThrottledIps() {
|
||||
IpBlocklist blocklist = blocklist(CidrSet.of(List.of()));
|
||||
TokenBucketRateLimiter limiter = limiter(blocklist, 1_000, 60);
|
||||
limiter.tryAcquire("3.3.3.3"); // one clean request, never throttled
|
||||
assertTrue(limiter.topOffenders(10).isEmpty(), "an IP that was never throttled is not an offender");
|
||||
}
|
||||
}
|
||||
+96
@@ -0,0 +1,96 @@
|
||||
package mx.quest.protection;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
import java.util.function.Supplier;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
/** Lockout after maxAttempts within the window; unlock after the lockout; window pruning; success resets. */
|
||||
class SlidingWindowLoginGateTest {
|
||||
|
||||
/** Fixed thresholds as a settings supplier (seconds), captcha off, honeypot on (irrelevant to the gate). */
|
||||
private static Supplier<ProtectionSettings> settings(int maxAttempts, int windowSeconds, int lockoutSeconds) {
|
||||
ProtectionSettings s = new ProtectionSettings(true, maxAttempts, windowSeconds, lockoutSeconds,
|
||||
ProtectionSettings.Captcha.disabled());
|
||||
return () -> s;
|
||||
}
|
||||
|
||||
@Test
|
||||
void locksAfterMaxAttemptsAndUnlocksAfterTheLockout() {
|
||||
long[] now = {1000};
|
||||
SlidingWindowLoginGate gate = new SlidingWindowLoginGate(settings(3, 10, 60), () -> now[0]);
|
||||
assertFalse(gate.isLocked("ip"));
|
||||
gate.recordFailure("ip");
|
||||
gate.recordFailure("ip");
|
||||
assertFalse(gate.isLocked("ip"), "2 of 3");
|
||||
gate.recordFailure("ip");
|
||||
assertTrue(gate.isLocked("ip"), "3rd failure within the window locks");
|
||||
now[0] += 60_001;
|
||||
assertFalse(gate.isLocked("ip"), "unlocked after the lockout elapses");
|
||||
}
|
||||
|
||||
@Test
|
||||
void failuresOlderThanTheWindowDoNotCount() {
|
||||
long[] now = {1000};
|
||||
SlidingWindowLoginGate gate = new SlidingWindowLoginGate(settings(2, 10, 60), () -> now[0]);
|
||||
gate.recordFailure("ip");
|
||||
now[0] = 12_000; // the first failure is now outside the 10s window
|
||||
gate.recordFailure("ip");
|
||||
assertFalse(gate.isLocked("ip"), "only one failure falls inside the window");
|
||||
}
|
||||
|
||||
@Test
|
||||
void theMapIsBoundedAgainstAManyIpFlood() {
|
||||
long[] now = {1000};
|
||||
// maxIps = 2: a flood of fresh IPs cannot grow the map without bound (reclaim/clear keeps it small).
|
||||
SlidingWindowLoginGate gate = new SlidingWindowLoginGate(settings(5, 10, 60), 2, () -> now[0]);
|
||||
for (int i = 0; i < 100; i++) {
|
||||
now[0] += 1;
|
||||
gate.recordFailure("ip-" + i); // each a distinct IP
|
||||
}
|
||||
// A locked IP still works (correctness preserved under the bound) and the gate did not OOM tracking 100 IPs.
|
||||
gate.recordFailure("victim");
|
||||
gate.recordFailure("victim");
|
||||
gate.recordFailure("victim");
|
||||
gate.recordFailure("victim");
|
||||
gate.recordFailure("victim");
|
||||
assertTrue(gate.isLocked("victim"), "lockout still works under the memory bound");
|
||||
}
|
||||
|
||||
@Test
|
||||
void aSuccessClearsTheCounter() {
|
||||
long[] now = {1000};
|
||||
SlidingWindowLoginGate gate = new SlidingWindowLoginGate(settings(1, 10, 60), () -> now[0]);
|
||||
gate.recordFailure("ip");
|
||||
assertTrue(gate.isLocked("ip"));
|
||||
gate.recordSuccess("ip");
|
||||
assertFalse(gate.isLocked("ip"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void thresholdsAreReadFreshSoAConfigChangeAppliesWithoutRestart() {
|
||||
long[] now = {1000};
|
||||
// A mutable settings holder: raise maxAttempts mid-flight and the gate honors the new value immediately.
|
||||
ProtectionSettings[] holder = {new ProtectionSettings(true, 1, 10, 60, ProtectionSettings.Captcha.disabled())};
|
||||
SlidingWindowLoginGate gate = new SlidingWindowLoginGate(() -> holder[0], () -> now[0]);
|
||||
gate.recordFailure("ip");
|
||||
assertTrue(gate.isLocked("ip"), "maxAttempts=1 → locked after one failure");
|
||||
|
||||
gate.recordSuccess("ip"); // clear, then relax the policy
|
||||
holder[0] = new ProtectionSettings(true, 5, 10, 60, ProtectionSettings.Captcha.disabled());
|
||||
gate.recordFailure("ip");
|
||||
assertFalse(gate.isLocked("ip"), "maxAttempts=5 now → one failure no longer locks (read fresh)");
|
||||
}
|
||||
|
||||
@Test
|
||||
void aNullSupplierDegradesToDefaultsRatherThanThrowing() {
|
||||
long[] now = {1000};
|
||||
// Fail-safe: a null/failing supplier must not break the lockout — it uses ProtectionSettings.defaults().
|
||||
SlidingWindowLoginGate gate = new SlidingWindowLoginGate(null, () -> now[0]);
|
||||
for (int i = 0; i < 10; i++) {
|
||||
gate.recordFailure("ip"); // defaults() → maxAttempts 10
|
||||
}
|
||||
assertTrue(gate.isLocked("ip"), "defaults (10 attempts) still lock — never a no-op");
|
||||
}
|
||||
}
|
||||
+39
@@ -0,0 +1,39 @@
|
||||
package mx.quest.protection;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
/** The token bucket admits up to capacity, refills over time, and isolates buckets per key. */
|
||||
class TokenBucketRateLimiterTest {
|
||||
|
||||
@Test
|
||||
void admitsUpToCapacityThenRejects() {
|
||||
long[] now = {0};
|
||||
TokenBucketRateLimiter limiter = new TokenBucketRateLimiter(3, 1.0, 1000, () -> now[0]);
|
||||
assertTrue(limiter.tryAcquire("ip"));
|
||||
assertTrue(limiter.tryAcquire("ip"));
|
||||
assertTrue(limiter.tryAcquire("ip"));
|
||||
assertFalse(limiter.tryAcquire("ip"), "the bucket is empty");
|
||||
}
|
||||
|
||||
@Test
|
||||
void refillsOverTime() {
|
||||
long[] now = {0};
|
||||
TokenBucketRateLimiter limiter = new TokenBucketRateLimiter(1, 1.0, 1000, () -> now[0]); // 1 token, 1/sec
|
||||
assertTrue(limiter.tryAcquire("ip"));
|
||||
assertFalse(limiter.tryAcquire("ip"));
|
||||
now[0] = 1_000_000_000L; // +1 second
|
||||
assertTrue(limiter.tryAcquire("ip"), "one token refilled after a second");
|
||||
}
|
||||
|
||||
@Test
|
||||
void bucketsAreIsolatedPerKey() {
|
||||
long[] now = {0};
|
||||
TokenBucketRateLimiter limiter = new TokenBucketRateLimiter(1, 0.0, 1000, () -> now[0]);
|
||||
assertTrue(limiter.tryAcquire("a"));
|
||||
assertFalse(limiter.tryAcquire("a"));
|
||||
assertTrue(limiter.tryAcquire("b"), "a different IP has its own bucket");
|
||||
}
|
||||
}
|
||||
+264
@@ -0,0 +1,264 @@
|
||||
package mx.quest.protection;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
import jakarta.servlet.http.Cookie;
|
||||
import java.nio.file.Path;
|
||||
import mx.quest.runway.crypto.AesGcmSecretCipher;
|
||||
import mx.quest.runway.crypto.SecretCipher;
|
||||
import mx.quest.runway.security.ProtectionScope;
|
||||
import mx.quest.runway.security.RunwaySecurityProperties;
|
||||
import mx.quest.runway.storage.StorageLayout;
|
||||
import mx.quest.runway.storage.StorageProperties;
|
||||
import mx.quest.runway.storage.YamlStore;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.mock.web.MockHttpServletRequest;
|
||||
import org.springframework.mock.web.MockHttpServletResponse;
|
||||
|
||||
/**
|
||||
* The "remember this device" policy: a real AES-256-GCM {@link AesGcmSecretCipher} seals the cookie, so this exercises
|
||||
* the genuine round-trip AND the adversarial paths — a forged plaintext cookie, a tampered ciphertext, a
|
||||
* cross-realm / cross-site cookie, an expired stamp, opt-out, no-captcha, feature-off, and no-key — every one of
|
||||
* which must resolve to "not trusted" so the CAPTCHA is shown. Proves the cookie can only ever cause "more
|
||||
* CAPTCHA", never a skip it shouldn't.
|
||||
*/
|
||||
class TrustedDeviceServiceTest {
|
||||
|
||||
private static final String KEY = "trusted-device-test-master-key-0123456789";
|
||||
|
||||
private static SecretCipher realCipher() {
|
||||
RunwaySecurityProperties security = new RunwaySecurityProperties();
|
||||
security.setSecretKey(KEY);
|
||||
return new AesGcmSecretCipher(security);
|
||||
}
|
||||
|
||||
private static SecretCipher noKeyCipher() {
|
||||
return new AesGcmSecretCipher(new RunwaySecurityProperties()); // blank key ⇒ isAvailable() false
|
||||
}
|
||||
|
||||
private static StorageLayout layout(Path root) {
|
||||
StorageProperties props = new StorageProperties();
|
||||
props.setExternal(root.resolve("external"));
|
||||
props.setSites(root.resolve("external").resolve("sites"));
|
||||
return StorageLayout.from(props);
|
||||
}
|
||||
|
||||
/** A config store whose app scope AND site "acme"/"other" have an active CAPTCHA (so a cookie may be minted). */
|
||||
private static ProtectionConfigStore captchaStore(Path root, SecretCipher cipher) {
|
||||
ProtectionProperties props = new ProtectionProperties();
|
||||
props.getLogin().getCaptcha().setEnabled(true);
|
||||
props.getLogin().getCaptcha().setSiteKey("SITEKEY");
|
||||
props.getLogin().getCaptcha().setSecretKey("SECRET");
|
||||
ProtectionConfigStore store = new ProtectionConfigStore(props, layout(root), new YamlStore(), cipher);
|
||||
ProtectionSettings.Captcha active = new ProtectionSettings.Captcha(true, "recaptcha-v2", "SITEKEY", "SECRET", 0.5);
|
||||
try {
|
||||
store.savePerSite("acme", new ProtectionSettings(false, 5, 300, 900, active));
|
||||
store.savePerSite("other", new ProtectionSettings(false, 5, 300, 900, active));
|
||||
} catch (java.io.IOException e) {
|
||||
throw new java.io.UncheckedIOException(e);
|
||||
}
|
||||
return store;
|
||||
}
|
||||
|
||||
private static TrustedDeviceService service(ProtectionConfigStore store, SecretCipher cipher) {
|
||||
ProtectionProperties props = new ProtectionProperties(); // remember-device defaults: enabled, 30 days
|
||||
return new TrustedDeviceService(props, store, cipher);
|
||||
}
|
||||
|
||||
/** Runs the issue path and returns the Set-Cookie as a {@link Cookie} (name+value), or {@code null} if none. */
|
||||
private static Cookie issue(TrustedDeviceService svc, ProtectionScope scope, boolean optIn) {
|
||||
MockHttpServletRequest req = new MockHttpServletRequest("POST",
|
||||
scope.realm() == ProtectionScope.Realm.APPLICATION ? "/app/login" : "/login");
|
||||
if (optIn) {
|
||||
req.addParameter(TrustedDeviceService.REMEMBER_PARAM, "1");
|
||||
}
|
||||
MockHttpServletResponse res = new MockHttpServletResponse();
|
||||
svc.rememberIfRequested(req, res, scope);
|
||||
String header = res.getHeader(HttpHeaders.SET_COOKIE);
|
||||
if (header == null) {
|
||||
return null;
|
||||
}
|
||||
String nameValue = header.substring(0, header.indexOf(';'));
|
||||
int eq = nameValue.indexOf('=');
|
||||
return new Cookie(nameValue.substring(0, eq), nameValue.substring(eq + 1));
|
||||
}
|
||||
|
||||
private static boolean trustedWith(TrustedDeviceService svc, ProtectionScope scope, Cookie cookie) {
|
||||
MockHttpServletRequest req = new MockHttpServletRequest("POST", "/login");
|
||||
if (cookie != null) {
|
||||
req.setCookies(cookie);
|
||||
}
|
||||
return svc.isTrusted(req, scope);
|
||||
}
|
||||
|
||||
// ---- the happy path ---------------------------------------------------------------------------
|
||||
|
||||
@Test
|
||||
void anIssuedCookieIsTrustedForTheSameScope(@TempDir Path root) {
|
||||
SecretCipher cipher = realCipher();
|
||||
TrustedDeviceService svc = service(captchaStore(root, cipher), cipher);
|
||||
Cookie app = issue(svc, ProtectionScope.application(), true);
|
||||
assertNotNull(app, "an opted-in login with an active captcha mints a cookie");
|
||||
assertTrue(app.getName().equals("runway_td_app"), "the app-realm cookie is named per realm");
|
||||
assertTrue(trustedWith(svc, ProtectionScope.application(), app), "the same device is trusted next time");
|
||||
|
||||
Cookie site = issue(svc, ProtectionScope.forSite("acme"), true);
|
||||
assertNotNull(site);
|
||||
assertTrue(site.getName().equals("runway_td_site_acme"), "the tenant cookie is named per site (site_ namespace)");
|
||||
assertTrue(trustedWith(svc, ProtectionScope.forSite("acme"), site));
|
||||
}
|
||||
|
||||
// ---- opt-in / gating: no cookie when it shouldn't be minted -----------------------------------
|
||||
|
||||
@Test
|
||||
void noCookieWithoutTheOptIn(@TempDir Path root) {
|
||||
SecretCipher cipher = realCipher();
|
||||
TrustedDeviceService svc = service(captchaStore(root, cipher), cipher);
|
||||
assertNull(issue(svc, ProtectionScope.application(), false), "no cookie unless the box was ticked");
|
||||
}
|
||||
|
||||
@Test
|
||||
void noCookieWhenTheScopeHasNoActiveCaptcha(@TempDir Path root) {
|
||||
SecretCipher cipher = realCipher();
|
||||
// A store with NO captcha configured anywhere → nothing to skip → no cookie even if opted in.
|
||||
ProtectionConfigStore bare = new ProtectionConfigStore(new ProtectionProperties(), layout(root),
|
||||
new YamlStore(), cipher);
|
||||
TrustedDeviceService svc = service(bare, cipher);
|
||||
assertNull(issue(svc, ProtectionScope.application(), true), "no captcha to skip ⇒ no cookie minted");
|
||||
}
|
||||
|
||||
@Test
|
||||
void featureDisabledMintsNothingAndTrustsNothing(@TempDir Path root) {
|
||||
SecretCipher cipher = realCipher();
|
||||
ProtectionProperties props = new ProtectionProperties();
|
||||
props.getRememberDevice().setEnabled(false);
|
||||
TrustedDeviceService svc = new TrustedDeviceService(props, captchaStore(root, cipher), cipher);
|
||||
assertNull(issue(svc, ProtectionScope.application(), true), "disabled ⇒ never mint");
|
||||
// Even a cookie that WOULD be valid isn't honored while the feature is off.
|
||||
TrustedDeviceService on = service(captchaStore(root, cipher), cipher);
|
||||
Cookie valid = issue(on, ProtectionScope.application(), true);
|
||||
assertFalse(trustedWith(svc, ProtectionScope.application(), valid), "disabled ⇒ never trust");
|
||||
}
|
||||
|
||||
@Test
|
||||
void noKeyMintsNothingAndTrustsNothing(@TempDir Path root) {
|
||||
SecretCipher noKey = noKeyCipher();
|
||||
// With no key the feature is off, so the store is never consulted — a bare one suffices.
|
||||
ProtectionConfigStore bare = new ProtectionConfigStore(new ProtectionProperties(), layout(root),
|
||||
new YamlStore(), noKey);
|
||||
TrustedDeviceService svc = service(bare, noKey);
|
||||
assertNull(issue(svc, ProtectionScope.application(), true), "no master key ⇒ can't sign ⇒ no cookie");
|
||||
assertFalse(svc.isEnabled(), "the feature reports itself off when the cipher is unavailable");
|
||||
assertFalse(trustedWith(svc, ProtectionScope.application(),
|
||||
new Cookie("runway_td_app", "anything")), "no key ⇒ never trust");
|
||||
}
|
||||
|
||||
@Test
|
||||
void anUnscopedTenantIsNeverIssuedOrTrusted(@TempDir Path root) {
|
||||
SecretCipher cipher = realCipher();
|
||||
TrustedDeviceService svc = service(captchaStore(root, cipher), cipher);
|
||||
ProtectionScope unscoped = ProtectionScope.forSite(null);
|
||||
assertNull(issue(svc, unscoped, true), "a tenant login with no resolved site can't be keyed");
|
||||
assertFalse(trustedWith(svc, unscoped, new Cookie("runway_td_site_x", "anything")),
|
||||
"…and isTrusted short-circuits before cookie keying for an unscoped tenant");
|
||||
}
|
||||
|
||||
@Test
|
||||
void theTrustWindowIsClampedToASaneRange(@TempDir Path root) {
|
||||
SecretCipher cipher = realCipher();
|
||||
assertEquals(1, svcWithDays(cipher, 0).rememberDays(), "0 clamps up to 1");
|
||||
assertEquals(1, svcWithDays(cipher, -5).rememberDays(), "negative clamps up to 1");
|
||||
assertEquals(365, svcWithDays(cipher, 10_000).rememberDays(), "an absurd value clamps down to 365");
|
||||
assertEquals(30, svcWithDays(cipher, 30).rememberDays(), "an in-range value passes through");
|
||||
}
|
||||
|
||||
@Test
|
||||
void anEncTaggedButUnsealedCookieIsRejected(@TempDir Path root) {
|
||||
SecretCipher cipher = realCipher();
|
||||
TrustedDeviceService svc = service(captchaStore(root, cipher), cipher);
|
||||
// ENC(...)-tagged so it passes the isEncrypted guard, but the inner text is not a real GCM ciphertext →
|
||||
// decrypt throws → not trusted. Complements the plaintext-forgery case (both crypto forgeries fail closed).
|
||||
Cookie fake = new Cookie("runway_td_app",
|
||||
"ENC(APPLICATION||" + (System.currentTimeMillis() + 99_999_999L) + ")");
|
||||
assertFalse(trustedWith(svc, ProtectionScope.application(), fake),
|
||||
"an ENC-tagged but not-truly-sealed value fails to decrypt → not trusted");
|
||||
}
|
||||
|
||||
private static TrustedDeviceService svcWithDays(SecretCipher cipher, int days) {
|
||||
ProtectionProperties props = new ProtectionProperties();
|
||||
props.getRememberDevice().setDays(days);
|
||||
return new TrustedDeviceService(props, null, cipher);
|
||||
}
|
||||
|
||||
// ---- adversarial: every forgery/tamper/mismatch resolves to NOT trusted -----------------------
|
||||
|
||||
@Test
|
||||
void aForgedPlaintextCookieIsRejected(@TempDir Path root) {
|
||||
SecretCipher cipher = realCipher();
|
||||
TrustedDeviceService svc = service(captchaStore(root, cipher), cipher);
|
||||
// A client hand-crafts an un-encrypted value naming the right realm + a far-future expiry. SecretCipher
|
||||
// passes a non-ENC value through, so WITHOUT the isEncrypted() guard this would be trusted.
|
||||
Cookie forged = new Cookie("runway_td_app", "APPLICATION||" + (System.currentTimeMillis() + 99_999_999L));
|
||||
assertFalse(trustedWith(svc, ProtectionScope.application(), forged), "a plaintext (unsigned) cookie is not trusted");
|
||||
}
|
||||
|
||||
@Test
|
||||
void aTamperedCiphertextIsRejected(@TempDir Path root) {
|
||||
SecretCipher cipher = realCipher();
|
||||
TrustedDeviceService svc = service(captchaStore(root, cipher), cipher);
|
||||
Cookie good = issue(svc, ProtectionScope.application(), true);
|
||||
// Flip a character in the middle of the sealed value → the GCM auth tag no longer matches → decrypt throws.
|
||||
String v = good.getValue();
|
||||
int mid = v.length() / 2;
|
||||
char flipped = v.charAt(mid) == 'A' ? 'B' : 'A';
|
||||
String tampered = v.substring(0, mid) + flipped + v.substring(mid + 1);
|
||||
assertFalse(trustedWith(svc, ProtectionScope.application(), new Cookie("runway_td_app", tampered)),
|
||||
"a modified ciphertext fails the GCM auth check → not trusted");
|
||||
}
|
||||
|
||||
@Test
|
||||
void anAppCookiePresentedToATenantScopeIsRejected(@TempDir Path root) {
|
||||
SecretCipher cipher = realCipher();
|
||||
TrustedDeviceService svc = service(captchaStore(root, cipher), cipher);
|
||||
Cookie app = issue(svc, ProtectionScope.application(), true);
|
||||
// Re-label the app cookie under the tenant cookie name so the NAME scoping can't be what rejects it —
|
||||
// the payload's realm binding must. (Defense in depth beyond host-only + per-site name.)
|
||||
Cookie relabelled = new Cookie("runway_td_site_acme", app.getValue());
|
||||
assertFalse(trustedWith(svc, ProtectionScope.forSite("acme"), relabelled),
|
||||
"an APPLICATION-sealed cookie can't skip a TENANT captcha (realm bound in the payload)");
|
||||
}
|
||||
|
||||
@Test
|
||||
void aSiteCookiePresentedToAnotherSiteIsRejected(@TempDir Path root) {
|
||||
SecretCipher cipher = realCipher();
|
||||
TrustedDeviceService svc = service(captchaStore(root, cipher), cipher);
|
||||
Cookie acme = issue(svc, ProtectionScope.forSite("acme"), true);
|
||||
// Present acme's sealed value under another site's cookie name → the payload's site binding must reject it.
|
||||
Cookie relabelled = new Cookie("runway_td_site_other", acme.getValue());
|
||||
assertFalse(trustedWith(svc, ProtectionScope.forSite("other"), relabelled),
|
||||
"site A's cookie can't skip site B's captcha (site bound in the payload)");
|
||||
}
|
||||
|
||||
@Test
|
||||
void anExpiredCookieIsRejected(@TempDir Path root) {
|
||||
SecretCipher cipher = realCipher();
|
||||
TrustedDeviceService svc = service(captchaStore(root, cipher), cipher);
|
||||
// Seal a well-formed payload whose expiry is already in the past (same cipher the service trusts).
|
||||
String expired = cipher.encrypt("APPLICATION||" + (System.currentTimeMillis() - 1_000L));
|
||||
assertFalse(trustedWith(svc, ProtectionScope.application(), new Cookie("runway_td_app", expired)),
|
||||
"a past-expiry stamp is not trusted");
|
||||
}
|
||||
|
||||
@Test
|
||||
void noCookieAtAllIsNotTrusted(@TempDir Path root) {
|
||||
SecretCipher cipher = realCipher();
|
||||
TrustedDeviceService svc = service(captchaStore(root, cipher), cipher);
|
||||
assertFalse(trustedWith(svc, ProtectionScope.application(), null), "no cookie ⇒ not trusted");
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user