Runway 1.0.0
This commit is contained in:
commit
dcf819146b
1372 files changed
+188168
No files matched your search
@@ -0,0 +1,124 @@
|
||||
# =============================================================================
|
||||
# Essential Protection plugin — i18n (English)
|
||||
# Appended LAST to the operator message source (add-only; never overrides a core key).
|
||||
# =============================================================================
|
||||
|
||||
# --- Menu entries (app + tenant realm Protection links) ----------------------
|
||||
protection.menu.protection=Essential Protection
|
||||
protection.menu.dos=DoS activity
|
||||
|
||||
# --- Control-point permission label ------------------------------------------
|
||||
protection.perm.settings=Configure protection
|
||||
|
||||
# --- App-level settings schema labels (generic settings form: the platform rate-limit floor only; login/CAPTCHA
|
||||
# are edited on the dedicated Essential Protection screen, not this schema) ---
|
||||
protection.settings.allowlist=Never rate-limit or auto-block these IPs/CIDRs (your own audits, probes, load tests)
|
||||
protection.settings.rl.capacity=Rate-limit burst capacity
|
||||
protection.settings.rl.refill=Rate-limit refill per second
|
||||
protection.settings.ab.enabled=Auto-block repeat offenders
|
||||
protection.settings.ab.threshold=Auto-block after this many rate-limit breaches
|
||||
protection.settings.ab.window=Counted within (seconds)
|
||||
protection.settings.ab.duration=Auto-block duration (seconds)
|
||||
protection.settings.rd.enabled=Allow "remember this device" (skip the login captcha on trusted devices)
|
||||
protection.settings.rd.days=Remember a device for (days)
|
||||
|
||||
# --- Dedicated Protection screens (app + per-site) ---------------------------
|
||||
protection.screen.app.title=Login protection
|
||||
protection.screen.site.title=Login protection
|
||||
protection.screen.heading=Login protection
|
||||
protection.screen.app.intro=These settings govern the operator login. Changes apply immediately — the next login attempt is evaluated against them, with no restart.
|
||||
protection.screen.site.intro=These settings govern this site's login. Changes apply immediately, and affect only this site.
|
||||
protection.screen.noCipher=No encryption key is configured, so a CAPTCHA secret cannot be stored. Configure runway.security.secret-key to enable it.
|
||||
|
||||
protection.screen.deterrents=Deterrents
|
||||
protection.screen.honeypot=Enable the hidden honeypot field
|
||||
protection.screen.honeypot.hint=A trap field a human never fills; a bot that fills it is rejected.
|
||||
|
||||
protection.screen.lockout=Per-IP lockout
|
||||
protection.screen.attempts=Max attempts
|
||||
protection.screen.attempts.hint=Failed logins within the window before the IP is locked.
|
||||
protection.screen.window=Window (seconds)
|
||||
protection.screen.window.hint=The sliding window over which failures accumulate.
|
||||
protection.screen.lockoutSecs=Lockout (seconds)
|
||||
protection.screen.lockoutSecs.hint=How long an IP stays locked once the threshold is reached.
|
||||
|
||||
protection.screen.captcha=External CAPTCHA
|
||||
protection.screen.captcha.enable=Require a CAPTCHA challenge
|
||||
protection.screen.provider=Provider
|
||||
protection.screen.provider.recaptcha-v2=reCAPTCHA v2
|
||||
protection.screen.provider.recaptcha-v3=reCAPTCHA v3
|
||||
protection.screen.siteKey=Site key (public)
|
||||
protection.screen.siteKey.hint=The public site key rendered into the challenge widget.
|
||||
protection.screen.secretKey=Secret key
|
||||
protection.screen.secretKey.hint=Verified server-side, stored encrypted. Leave blank to keep the current secret.
|
||||
protection.screen.secretKey.set=A secret is stored — leave blank to keep it
|
||||
protection.screen.secretKey.unset=No secret stored
|
||||
protection.screen.score=Score threshold (reCAPTCHA v3)
|
||||
protection.screen.score.hint=The minimum score a v3 response must meet (0.0–1.0).
|
||||
|
||||
protection.screen.save=Save
|
||||
protection.screen.saved=Protection settings saved.
|
||||
protection.screen.failed=Could not save protection settings.
|
||||
|
||||
# --- DoS activity screen (app realm) -----------------------------------------
|
||||
dos.screen.title=DoS activity
|
||||
dos.screen.heading=DoS activity
|
||||
dos.screen.intro=The platform-wide abuse floor. Offenders are IPs the rate limiter is throttling; blocked IPs are turned away before the login. Manual blocks survive a restart; auto blocks expire on their own.
|
||||
|
||||
dos.block.card=Block an address
|
||||
dos.block.ip=IP or CIDR
|
||||
dos.block.reason=Reason
|
||||
dos.block.seconds=Duration (seconds)
|
||||
dos.block.seconds.hint=0 blocks indefinitely.
|
||||
dos.block.submit=Block
|
||||
dos.block.done=Address blocked.
|
||||
dos.block.blank=Enter an IP address or CIDR to block.
|
||||
dos.block.refused=Refusing to block your own address or an allowlisted one.
|
||||
dos.block.indefinite=indefinite
|
||||
dos.unblock=Unblock
|
||||
dos.unblock.done=Address unblocked.
|
||||
|
||||
dos.ended.card=Recently ended blocks
|
||||
dos.ended.hint=Blocks that have expired or been lifted since this server started. Kept in memory only (newest 100), so this list empties on restart \u2014 the runway.protect log is the durable record.
|
||||
dos.ended.empty=No blocks have ended yet.
|
||||
dos.th.ended.ip=IP / CIDR
|
||||
dos.th.ended.reason=Reason
|
||||
dos.th.ended.source=Source
|
||||
dos.th.ended.ended=Ended
|
||||
dos.blocks.card=Blocked addresses
|
||||
dos.blocks.empty=No addresses are currently blocked.
|
||||
dos.offenders.card=Rate-limit offenders
|
||||
dos.offenders.empty=No offenders yet — the rate limiter is not throttling anyone.
|
||||
|
||||
dos.col.ip=IP / CIDR
|
||||
dos.col.reason=Reason
|
||||
dos.col.source=Source
|
||||
dos.col.until=Expires
|
||||
dos.col.actions=Actions
|
||||
dos.col.requests=Requests
|
||||
dos.col.throttled=Throttled (429)
|
||||
dos.col.blocked=Blocked
|
||||
|
||||
dos.source.manual=manual
|
||||
dos.source.auto=auto
|
||||
dos.yes=Yes
|
||||
dos.no=No
|
||||
|
||||
# Settings form sections and help lines (1.0.0)
|
||||
protection.group.ratelimit=Rate limit
|
||||
protection.group.ratelimit.help=Every visitor's address gets a bucket of requests that refills over time. A request that finds it empty gets 429 Too Many Requests. Applies to every site and both consoles, before the site is known.
|
||||
protection.group.autoblock=Auto-block
|
||||
protection.group.autoblock.help=An address that keeps hitting the rate limit is blocked for a while. Auto-blocks are kept in memory and clear on restart; blocks you set on the DoS screen are kept.
|
||||
protection.group.exempt=Exemptions
|
||||
protection.group.exempt.help=Addresses the rate limit and auto-block never apply to.
|
||||
protection.group.device=Remember this device
|
||||
protection.group.device.help=After a login that solved the CAPTCHA, the device may skip the login CAPTCHA for a while. It never skips the password or the lockout.
|
||||
protection.help.allowlist=One IP or CIDR per line, e.g. 203.0.113.7 or 198.51.100.0/24. For your own audits, probes and load tests. Loopback is not exempt unless listed: behind a same-host proxy every visitor arrives from loopback.
|
||||
protection.help.rl.capacity=How many requests one address may make back to back before it is slowed down. Default 120.
|
||||
protection.help.rl.refill=How many requests per second an address gets back after a burst. Default 2; 0.5 means one every two seconds. Must be above 0.
|
||||
protection.help.ab.enabled=Off: an address over the limit only gets 429s and is never blocked.
|
||||
protection.help.ab.threshold=How many 429s within the window before the address is blocked. Default 60.
|
||||
protection.help.ab.window=The period the 429s are counted over. Default 60 seconds.
|
||||
protection.help.ab.duration=How long an auto-block lasts; the visitor gets 429 with the remaining time in Retry-After. Default 900 (15 minutes).
|
||||
protection.help.rd.enabled=Off: the login CAPTCHA is shown on every login.
|
||||
protection.help.rd.days=How long a device is remembered, 1 to 365. Default 30.
|
||||
@@ -0,0 +1,124 @@
|
||||
# =============================================================================
|
||||
# Essential Protection plugin — i18n (Español)
|
||||
# Añadido AL FINAL de la fuente de mensajes del operador (solo añade; nunca sobreescribe una clave del núcleo).
|
||||
# =============================================================================
|
||||
|
||||
# --- Entradas de menú (enlaces Protección de los ámbitos aplicación + inquilino) ---
|
||||
protection.menu.protection=Protección esencial
|
||||
protection.menu.dos=Actividad DoS
|
||||
|
||||
# --- Etiqueta del permiso (punto de control) ---------------------------------
|
||||
protection.perm.settings=Configurar protección
|
||||
|
||||
# --- Etiquetas del esquema de ajustes de nivel aplicación (formulario genérico: solo el suelo de límite de tasa;
|
||||
# el honeypot/bloqueo/CAPTCHA de acceso se editan en la pantalla dedicada de Protección esencial) ---
|
||||
protection.settings.allowlist=Nunca limitar ni bloquear autom\u00e1ticamente estas IP/CIDR (tus propias auditor\u00edas, sondas, pruebas de carga)
|
||||
protection.settings.rl.capacity=Capacidad de ráfaga del límite de tasa
|
||||
protection.settings.rl.refill=Recarga por segundo del límite de tasa
|
||||
protection.settings.ab.enabled=Bloquear automáticamente a los reincidentes
|
||||
protection.settings.ab.threshold=Bloquear tras esta cantidad de excesos del límite
|
||||
protection.settings.ab.window=Contadas en (segundos)
|
||||
protection.settings.ab.duration=Duración del bloqueo automático (segundos)
|
||||
protection.settings.rd.enabled=Permitir «recordar este dispositivo» (omitir el captcha de inicio de sesión en dispositivos de confianza)
|
||||
protection.settings.rd.days=Recordar un dispositivo durante (días)
|
||||
|
||||
# --- Pantallas dedicadas de Protección (aplicación + por sitio) --------------
|
||||
protection.screen.app.title=Protección de acceso
|
||||
protection.screen.site.title=Protección de acceso
|
||||
protection.screen.heading=Protección de acceso
|
||||
protection.screen.app.intro=Estos ajustes rigen el acceso de operadores. Los cambios se aplican de inmediato: el siguiente intento de acceso se evalúa con ellos, sin reiniciar.
|
||||
protection.screen.site.intro=Estos ajustes rigen el acceso de este sitio. Los cambios se aplican de inmediato y afectan solo a este sitio.
|
||||
protection.screen.noCipher=No hay clave de cifrado configurada, así que no se puede guardar el secreto del CAPTCHA. Configura runway.security.secret-key para habilitarlo.
|
||||
|
||||
protection.screen.deterrents=Disuasivos
|
||||
protection.screen.honeypot=Activar el campo trampa (honeypot) oculto
|
||||
protection.screen.honeypot.hint=Un campo trampa que una persona nunca rellena; un bot que lo rellena es rechazado.
|
||||
|
||||
protection.screen.lockout=Bloqueo por IP
|
||||
protection.screen.attempts=Máx. intentos
|
||||
protection.screen.attempts.hint=Accesos fallidos dentro de la ventana antes de bloquear la IP.
|
||||
protection.screen.window=Ventana (segundos)
|
||||
protection.screen.window.hint=La ventana deslizante en la que se acumulan los fallos.
|
||||
protection.screen.lockoutSecs=Bloqueo (segundos)
|
||||
protection.screen.lockoutSecs.hint=Cuánto permanece bloqueada una IP al alcanzar el umbral.
|
||||
|
||||
protection.screen.captcha=CAPTCHA externo
|
||||
protection.screen.captcha.enable=Exigir un reto CAPTCHA
|
||||
protection.screen.provider=Proveedor
|
||||
protection.screen.provider.recaptcha-v2=reCAPTCHA v2
|
||||
protection.screen.provider.recaptcha-v3=reCAPTCHA v3
|
||||
protection.screen.siteKey=Clave de sitio (pública)
|
||||
protection.screen.siteKey.hint=La clave de sitio pública que se muestra en el widget del reto.
|
||||
protection.screen.secretKey=Clave secreta
|
||||
protection.screen.secretKey.hint=Se verifica en el servidor y se guarda cifrada. Déjalo en blanco para conservar el secreto actual.
|
||||
protection.screen.secretKey.set=Hay un secreto guardado — déjalo en blanco para conservarlo
|
||||
protection.screen.secretKey.unset=No hay secreto guardado
|
||||
protection.screen.score=Umbral de puntuación (reCAPTCHA v3)
|
||||
protection.screen.score.hint=La puntuación mínima que debe alcanzar una respuesta v3 (0.0–1.0).
|
||||
|
||||
protection.screen.save=Guardar
|
||||
protection.screen.saved=Ajustes de protección guardados.
|
||||
protection.screen.failed=No se pudieron guardar los ajustes de protección.
|
||||
|
||||
# --- Pantalla de actividad DoS (ámbito aplicación) ---------------------------
|
||||
dos.screen.title=Actividad DoS
|
||||
dos.screen.heading=Actividad DoS
|
||||
dos.screen.intro=El piso de defensa contra abuso de toda la plataforma. Los infractores son IPs que el limitador de tasa está frenando; las IPs bloqueadas se rechazan antes del acceso. Los bloqueos manuales sobreviven a un reinicio; los automáticos expiran por sí solos.
|
||||
|
||||
dos.block.card=Bloquear una dirección
|
||||
dos.block.ip=IP o CIDR
|
||||
dos.block.reason=Motivo
|
||||
dos.block.seconds=Duración (segundos)
|
||||
dos.block.seconds.hint=0 bloquea indefinidamente.
|
||||
dos.block.submit=Bloquear
|
||||
dos.block.done=Dirección bloqueada.
|
||||
dos.block.blank=Introduce una dirección IP o CIDR para bloquear.
|
||||
dos.block.refused=No se bloquea tu propia dirección ni una de la lista de permitidos.
|
||||
dos.block.indefinite=indefinido
|
||||
dos.unblock=Desbloquear
|
||||
dos.unblock.done=Dirección desbloqueada.
|
||||
|
||||
dos.ended.card=Bloqueos terminados recientemente
|
||||
dos.ended.hint=Bloqueos que han expirado o se han levantado desde que arranc\u00f3 este servidor. Se guardan solo en memoria (los 100 m\u00e1s recientes), as\u00ed que la lista se vac\u00eda al reiniciar \u2014 el registro runway.protect es la constancia duradera.
|
||||
dos.ended.empty=Todav\u00eda no ha terminado ning\u00fan bloqueo.
|
||||
dos.th.ended.ip=IP / CIDR
|
||||
dos.th.ended.reason=Motivo
|
||||
dos.th.ended.source=Origen
|
||||
dos.th.ended.ended=Termin\u00f3
|
||||
dos.blocks.card=Direcciones bloqueadas
|
||||
dos.blocks.empty=No hay direcciones bloqueadas actualmente.
|
||||
dos.offenders.card=Infractores del límite de tasa
|
||||
dos.offenders.empty=Aún no hay infractores: el limitador de tasa no está frenando a nadie.
|
||||
|
||||
dos.col.ip=IP / CIDR
|
||||
dos.col.reason=Motivo
|
||||
dos.col.source=Origen
|
||||
dos.col.until=Expira
|
||||
dos.col.actions=Acciones
|
||||
dos.col.requests=Solicitudes
|
||||
dos.col.throttled=Frenadas (429)
|
||||
dos.col.blocked=Bloqueada
|
||||
|
||||
dos.source.manual=manual
|
||||
dos.source.auto=automático
|
||||
dos.yes=Sí
|
||||
dos.no=No
|
||||
|
||||
# Settings form sections and help lines (1.0.0)
|
||||
protection.group.ratelimit=Límite de solicitudes
|
||||
protection.group.ratelimit.help=Cada dirección de visitante tiene un depósito de solicitudes que se rellena con el tiempo. Una solicitud que lo encuentra vacío recibe 429 Too Many Requests. Se aplica a todos los sitios y a ambas consolas, antes de saber qué sitio es.
|
||||
protection.group.autoblock=Bloqueo automático
|
||||
protection.group.autoblock.help=Una dirección que choca una y otra vez con el límite queda bloqueada un tiempo. Los bloqueos automáticos viven en memoria y se borran al reiniciar; los que fijas en la pantalla DoS se conservan.
|
||||
protection.group.exempt=Exenciones
|
||||
protection.group.exempt.help=Direcciones a las que nunca se aplican el límite ni el bloqueo automático.
|
||||
protection.group.device=Recordar este dispositivo
|
||||
protection.group.device.help=Tras un inicio de sesión que resolvió el CAPTCHA, el dispositivo puede omitir el CAPTCHA de inicio de sesión durante un tiempo. Nunca omite la contraseña ni el bloqueo por intentos.
|
||||
protection.help.allowlist=Una IP o CIDR por línea, p. ej. 203.0.113.7 o 198.51.100.0/24. Para tus auditorías, sondas y pruebas de carga. Loopback no está exento salvo que lo pongas: detrás de un proxy en el mismo equipo, todo visitante llega desde loopback.
|
||||
protection.help.rl.capacity=Cuántas solicitudes seguidas puede hacer una dirección antes de que se la frene. Por omisión 120.
|
||||
protection.help.rl.refill=Cuántas solicitudes por segundo recupera una dirección tras una ráfaga. Por omisión 2; 0.5 es una cada dos segundos. Debe ser mayor que 0.
|
||||
protection.help.ab.enabled=Desactivado: una dirección que excede el límite solo recibe 429 y nunca se bloquea.
|
||||
protection.help.ab.threshold=Cuántos 429 dentro de la ventana antes de bloquear la dirección. Por omisión 60.
|
||||
protection.help.ab.window=El periodo en el que se cuentan los 429. Por omisión 60 segundos.
|
||||
protection.help.ab.duration=Cuánto dura un bloqueo automático; el visitante recibe 429 con el tiempo restante en Retry-After. Por omisión 900 (15 minutos).
|
||||
protection.help.rd.enabled=Desactivado: el CAPTCHA de inicio de sesión se muestra en cada inicio de sesión.
|
||||
protection.help.rd.days=Cuánto tiempo se recuerda un dispositivo, de 1 a 365. Por omisión 30.
|
||||
@@ -0,0 +1,110 @@
|
||||
# Essential protection plugin — the kernel's security floor (DoS/abuse rate limit + login brute-force lockout).
|
||||
# The thin jar (runway-plugin-protection.jar) and this descriptor are deployed together in
|
||||
# external/plugins/protection/. The id MUST be 'protection' (the kernel security-floor allowlist).
|
||||
id: protection
|
||||
name: Essential Protection
|
||||
# The essential plugin ships with the kernel, in the same release, on the kernel's version line (docs/SPI-STABILITY.md, "The essential-plugin exception"):
|
||||
# 1.0.0 from Runway 1.0.0-rc1 (plugin versions are plain MAJOR.MINOR.PATCH, so the rc suffix lives only on the kernel
|
||||
# tag). The number went from 1.5.0 (0.5.0-beta14) back to 1.0.0 once, at rc1; seeding compares SHA-256 hashes, not
|
||||
# versions, and no plugin may `requires:` an essential plugin, so nothing keys on it.
|
||||
version: 1.0.0
|
||||
essential: true
|
||||
# The mandatory floor (SPI 1.0.0): every plugin with a mainClass declares one; the kernel's own plugin declares the
|
||||
# kernel's SPI, so the floor rule can never block it and trip the fail-closed security floor. It also keeps an
|
||||
# older kernel from registering a plugin that links SPI types it lacks: without a floor, a rollback from
|
||||
# 0.5.0-beta14 to beta13 over a refreshed protection folder died on a NoClassDefFoundError naming neither the plugin
|
||||
# nor the cause; with it, every kernel since 0.5.0-beta10 refuses the plugin with a reason naming both SPI levels.
|
||||
requiresSpi: ">=1.0.0"
|
||||
mainClass: mx.quest.protection.ProtectionConfig
|
||||
|
||||
# App-level settings (bound from external/plugin-settings/protection.yml as runway.plugin.protection.*).
|
||||
# ONLY the platform-wide abuse-floor knobs (the per-IP rate-limit token bucket) are a generic-form schema here —
|
||||
# a restart-applied PLATFORM concern, rendered as the generic form on this plugin's settings page. The operator
|
||||
# LOGIN protection (honeypot, lockout, CAPTCHA) is deliberately NOT a schema: it renders as this plugin's own
|
||||
# immediate-apply PANEL (templates/admin-app.html) BELOW that same form, editing via ProtectionConfigStore
|
||||
# (protection-app.yml) so a change takes effect on the next login with no restart. Both live on the ONE plugin
|
||||
# settings page (/__app/plugins/protection/settings) — login config has a single home, never shadowed by a second
|
||||
# editor. Per-site login protection likewise lives in sites/<id>/plugins/protection.yml (the /__admin/protection
|
||||
# screen), so that tenant-owned plugin data travels in the site backup. ProtectionProperties.Login is the SEED.
|
||||
settings:
|
||||
# EXEMPTION. CIDRs (and bare IPs) the abuse floor never throttles and never auto-blocks — the escape hatch
|
||||
# for a client that is SUPPOSED to be high-volume: your own SEO audit, a synthetic prober, a load test, a
|
||||
# first-party crawler, a monitoring probe. Everything has to be named here — loopback included: loopback is
|
||||
# never BLOCKED (IpBlocklist.isAllowlisted refuses a manual or auto block of 127.0.0.0/8 and ::1), but it IS
|
||||
# rate-limited like any client (RateLimitEdgeGuard consults only this list before the token bucket). That is
|
||||
# deliberate: behind a same-host reverse proxy that does not forward the client address to a trusted peer, every
|
||||
# request arrives from loopback, and exempting it would switch the rate limit off for the whole internet. A
|
||||
# same-host probe that must never see a 429 is listed here (127.0.0.1/32), knowing what that implies.
|
||||
#
|
||||
# This value ALWAYS bound and reached the guard — it was simply not declared, which is the WORSE state, and
|
||||
# it has real consequences: a same-host SEO audit locked the admin IP out for 15 minutes and returned
|
||||
# 13 FAIL / 25 WARN, every one a 429 rather than a defect, on a clean deployment; only the audit harness's
|
||||
# control request also returning 429 showed it was not a regression.
|
||||
#
|
||||
# Undeclared was worse than absent because the settings form writes the COMPLETE DECLARED KEY SET on save:
|
||||
# an operator who found this key in the source, set it, and got protection would have lost it silently the
|
||||
# next time anyone saved this page — locked out again with nothing to point at. That is the identical trap
|
||||
# the auto-block block below records, on the one setting whose whole job is preventing a self-lockout.
|
||||
#
|
||||
# Counter-intuitive, learned the same day: PROBING DURING A BLOCK FEEDS IT. Once an address is blocked,
|
||||
# requests stop reaching the limiter and hit the blocklist instead, so the rate-limit counter freezes while
|
||||
# blocklist-auto climbs. The correct response to being blocked is to STOP and wait out `block-seconds`.
|
||||
- { key: allowlist, type: list, label: protection.settings.allowlist,
|
||||
group: exempt, help: protection.help.allowlist }
|
||||
- { key: rate-limit.capacity, type: int, default: 120, range: "1..100000", label: protection.settings.rl.capacity,
|
||||
group: ratelimit, help: protection.help.rl.capacity }
|
||||
# A refill of 0 would never let an address recover once its burst is spent: the range starts above it.
|
||||
- { key: rate-limit.refill-per-second, type: decimal, default: 2, range: "0.01..10000", label: protection.settings.rl.refill,
|
||||
group: ratelimit, help: protection.help.rl.refill }
|
||||
# AUTO-ESCALATION. These govern what happens AFTER the rate limit trips: an address that breaches
|
||||
# `breach-threshold` times within `window-seconds` is auto-blocked for `block-seconds`. An auto-block answers
|
||||
# 429 with the remaining time in Retry-After (it is the limiter escalating, not a policy ban); an operator ban,
|
||||
# which has no honest retry time to offer, answers 403. An auto-block always ends: block-seconds is at least 1.
|
||||
# Previously the thresholds above were tunable while the CONSEQUENCE was fixed at 15 minutes and
|
||||
# invisible — an operator could not answer "how long am I blocked for?" from configuration. The values
|
||||
# DID bind, but being undeclared here meant any save of this form silently dropped a hand-edited key.
|
||||
# This branch fires with NO human in the loop, on real visitors, so its duration is the difference
|
||||
# between a speed bump and locking out a customer's NAT gateway for an afternoon.
|
||||
# Auto-blocks are IN-MEMORY ONLY and clear on restart; only manual operator blocks are persisted.
|
||||
- { key: rate-limit.auto-block.enabled, type: boolean, default: true, label: protection.settings.ab.enabled,
|
||||
group: autoblock, help: protection.help.ab.enabled }
|
||||
- { key: rate-limit.auto-block.breach-threshold, type: int, default: 60, range: "1..100000", label: protection.settings.ab.threshold,
|
||||
group: autoblock, help: protection.help.ab.threshold, showWhen: rate-limit.auto-block.enabled }
|
||||
- { key: rate-limit.auto-block.window-seconds, type: int, default: 60, range: "1..86400", label: protection.settings.ab.window,
|
||||
group: autoblock, help: protection.help.ab.window, showWhen: rate-limit.auto-block.enabled }
|
||||
- { key: rate-limit.auto-block.block-seconds, type: int, default: 900, range: "1..604800", label: protection.settings.ab.duration,
|
||||
group: autoblock, help: protection.help.ab.duration, showWhen: rate-limit.auto-block.enabled }
|
||||
# "Remember this device": lets a device that logged in successfully (solving the CAPTCHA once) skip the login
|
||||
# CAPTCHA for N days via a signed, per-realm/per-site, host-only cookie. Platform security-floor concern, so it
|
||||
# is app-level and governs both realms; restart-applied. Off ⇒ the CAPTCHA is always shown.
|
||||
- { key: remember-device.enabled, type: boolean, default: true, label: protection.settings.rd.enabled,
|
||||
group: device, help: protection.help.rd.enabled }
|
||||
- { key: remember-device.days, type: int, default: 30, range: "1..365", label: protection.settings.rd.days,
|
||||
group: device, help: protection.help.rd.days, showWhen: remember-device.enabled }
|
||||
# Sections of the settings form, in this order (presentation only).
|
||||
settingGroups:
|
||||
- { id: ratelimit, label: protection.group.ratelimit, help: protection.group.ratelimit.help }
|
||||
- { id: autoblock, label: protection.group.autoblock, help: protection.group.autoblock.help }
|
||||
- { id: exempt, label: protection.group.exempt, help: protection.group.exempt.help }
|
||||
- { id: device, label: protection.group.device, help: protection.group.device.help }
|
||||
|
||||
# A grantable permission gating the plugin's configuration surface (app realm).
|
||||
# defaultRoles is EMPTY: the control point starts ungranted — the app admin (SYSTEMADMIN wildcard) and
|
||||
# superadmin hold it; the seed SYSTEMOPERATOR role starts blank and is granted it explicitly if needed.
|
||||
permissions:
|
||||
- { id: settings, realm: application, label: protection.perm.settings, defaultRoles: [] }
|
||||
|
||||
# Console menu entries. The app-realm LOGIN-protection config has NO menu entry: it renders as this plugin's own
|
||||
# panel (templates/admin-app.html) on its settings page (/__app/plugins/protection/settings), reached from the
|
||||
# Plugins list — a plugin's config belongs on its plugin-settings page, not a bespoke menu item. What remains here:
|
||||
# the app DoS ACTIVITY screen, placed by REGION under the console ACTIVITY dropdown beside Bandwidth (it
|
||||
# is live abuse monitoring, not config, so it needs its own screen + entry); and the per-site login-protection screen
|
||||
# in the tenant realm, placed by REGION under the console SETTINGS dropdown alongside every other plugin's config
|
||||
# entry (it IS per-site configuration). An entry is hidden from a principal who fails the named permission (UX only
|
||||
# — the controllers still enforce): the app entry on the plugin's own protection|settings control point (the app
|
||||
# master/wildcard always passes), the tenant entry on the kernel CONFIGURE_SITE permission (as SEO/Icons do).
|
||||
menu:
|
||||
- { realm: application, region: activity, order: 71, label: protection.menu.dos,
|
||||
path: "/__app/dos", permission: "protection|settings" }
|
||||
- { realm: tenant, region: settings, order: 70, label: protection.menu.protection,
|
||||
path: "/__admin/protection", permission: "CONFIGURE_SITE" }
|
||||
@@ -0,0 +1,95 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
|
||||
<parent>
|
||||
<groupId>mx.quest</groupId>
|
||||
<artifactId>runway</artifactId>
|
||||
<version>1.0.0</version>
|
||||
</parent>
|
||||
|
||||
<artifactId>runway-plugin-protection</artifactId>
|
||||
<packaging>jar</packaging>
|
||||
|
||||
<description>
|
||||
The essential security-floor plugin: a @Primary EdgeGuard (per-IP token-bucket rate limit +
|
||||
IP allow/block lists) and a @Primary LoginAttemptGate (sliding-window brute-force lockout) that fill
|
||||
the kernel's 7c/7d seams. It is a separate artifact loaded by the plugin loader at runtime (NEVER on the
|
||||
kernel's component-scan classpath); its package lives outside mx.quest.runway. The thin jar drops into
|
||||
external/plugins/protection/ alongside its plugin.yml.
|
||||
</description>
|
||||
|
||||
<dependencies>
|
||||
<!-- The released SPI (compile: the plugin genuinely uses it; bundled is fine, it is the host's too). -->
|
||||
<dependency>
|
||||
<groupId>mx.quest</groupId>
|
||||
<artifactId>runway-spi</artifactId>
|
||||
<version>${project.version}</version>
|
||||
</dependency>
|
||||
|
||||
<!-- The host: the kernel provides EdgeGuard/LoginAttemptGate/CidrSet/ClientIp at runtime via the parent
|
||||
classloader, so this is provided (compiled against, never bundled into the thin plugin jar). -->
|
||||
<dependency>
|
||||
<groupId>mx.quest</groupId>
|
||||
<artifactId>runway-app</artifactId>
|
||||
<version>${project.version}</version>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
|
||||
<!-- Spring context / Boot for @Configuration / @ConfigurationProperties — host-provided at runtime. -->
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter</artifactId>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-test</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<resources>
|
||||
<resource>
|
||||
<directory>src/main/resources</directory>
|
||||
</resource>
|
||||
<!-- The license and the plugin permission travel inside the jar, so a jar fetched on its own
|
||||
still carries its terms. -->
|
||||
<resource>
|
||||
<directory>${project.basedir}/..</directory>
|
||||
<includes>
|
||||
<include>LICENSE</include>
|
||||
<include>LICENSE-EXCEPTION</include>
|
||||
</includes>
|
||||
<targetPath>META-INF</targetPath>
|
||||
</resource>
|
||||
</resources>
|
||||
<finalName>runway-plugin-protection</finalName>
|
||||
<plugins>
|
||||
<!--
|
||||
Generate META-INF/spring-configuration-metadata.json for runway.plugin.protection.* (IDE completion
|
||||
and type checks for operators editing external/application.yml or plugin-settings/protection.yml).
|
||||
The processor must be on the compiler's PROCESSOR path: JDK 23+ no longer runs processors it merely
|
||||
finds on the classpath, which is why this metadata silently never existed. Same setup as runway-app.
|
||||
The processor is compile-time only; nothing of it reaches the thin plugin jar but the JSON.
|
||||
-->
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<configuration>
|
||||
<annotationProcessorPaths>
|
||||
<path>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-configuration-processor</artifactId>
|
||||
</path>
|
||||
</annotationProcessorPaths>
|
||||
<annotationProcessorPathsUseDepMgmt>true</annotationProcessorPathsUseDepMgmt>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
</project>
|
||||
+84
@@ -0,0 +1,84 @@
|
||||
package mx.quest.protection;
|
||||
|
||||
import java.io.IOException;
|
||||
import org.springframework.beans.factory.annotation.Qualifier;
|
||||
import org.springframework.context.MessageSource;
|
||||
import org.springframework.context.i18n.LocaleContextHolder;
|
||||
import org.springframework.security.access.prepost.PreAuthorize;
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
|
||||
|
||||
/**
|
||||
* The <b>save</b> handler for the app-scope login-protection policy ({@link ProtectionSettings}) that governs the
|
||||
* <b>operator login</b>: the honeypot switch, the per-IP lockout thresholds, and the external CAPTCHA (provider,
|
||||
* public site key, secret, v3 score threshold). It edits <b>only</b> the app scope — never any tenant's per-site
|
||||
* config.
|
||||
*
|
||||
* <p>There is no standalone screen: the controls render as the plugin's own <b>panel</b> ({@code templates/
|
||||
* admin-app.html}, bound via {@link AppProtectionPanel}) on the kernel's plugin-settings page
|
||||
* ({@code /__app/plugins/protection/settings}) — a plugin's config lives on its own settings page, not a bespoke
|
||||
* menu entry. This controller only accepts the panel's POST and redirects back to that page. Gated by the plugin's
|
||||
* own {@code protection|settings} control point (app realm; the app master/wildcard admin always passes).
|
||||
*
|
||||
* <p><b>Immediate apply.</b> A save updates {@link ProtectionConfigStore}'s live app snapshot and persists it, so
|
||||
* the login gate and form guard — which read the store fresh on every check — see the change on the next login
|
||||
* with no restart (the panel's whole reason for being over the restart-only generic settings form).
|
||||
*
|
||||
* <p><b>Secret handling.</b> The captcha secret is <b>masked</b> in the panel (a boolean "configured?" flag, never
|
||||
* the plaintext or the {@code ENC(...)} blob), and a <b>blank</b> secret field on POST <b>keeps</b> the stored
|
||||
* secret (only a non-blank value replaces it, encrypted at rest).
|
||||
*
|
||||
* <p><b>Fail-safe validation.</b> The lockout thresholds are floored to sane positives before saving (a value
|
||||
* {@code ≤ 0} falls back to the {@link ProtectionSettings} defaults through its canonical constructor), so a save
|
||||
* can never persist a config that would lock every operator out irrecoverably.
|
||||
*/
|
||||
@Controller
|
||||
public class AppProtectionController {
|
||||
|
||||
/** Where the panel lives — the POST redirects back here so the flash shows on the plugin settings page. */
|
||||
static final String SETTINGS_PAGE = "/__app/plugins/protection/settings";
|
||||
|
||||
private final ProtectionConfigStore store;
|
||||
private final MessageSource messages;
|
||||
|
||||
public AppProtectionController(ProtectionConfigStore store,
|
||||
@Qualifier("operatorAwareMessageSource") MessageSource messages) {
|
||||
this.store = store;
|
||||
this.messages = messages;
|
||||
}
|
||||
|
||||
@PostMapping("/__app/protection")
|
||||
@PreAuthorize("@authz.may('protection|settings')")
|
||||
public String save(@RequestParam(name = "honeypotEnabled", defaultValue = "false") boolean honeypotEnabled,
|
||||
@RequestParam(defaultValue = "0") int maxAttempts,
|
||||
@RequestParam(defaultValue = "0") int windowSeconds,
|
||||
@RequestParam(defaultValue = "0") int lockoutSeconds,
|
||||
@RequestParam(name = "captchaEnabled", defaultValue = "false") boolean captchaEnabled,
|
||||
@RequestParam(required = false) String provider,
|
||||
@RequestParam(required = false) String siteKey,
|
||||
@RequestParam(required = false) String secretKey,
|
||||
@RequestParam(defaultValue = "0.5") double scoreThreshold,
|
||||
RedirectAttributes redirect) {
|
||||
ProtectionSettings current = store.appSettings();
|
||||
try {
|
||||
ProtectionSettings updated = ProtectionForm.merge(current, honeypotEnabled, maxAttempts, windowSeconds,
|
||||
lockoutSeconds, captchaEnabled, provider, siteKey, secretKey, scoreThreshold);
|
||||
store.saveApp(updated);
|
||||
redirect.addFlashAttribute("flash", message("protection.screen.saved", "Protection settings saved."));
|
||||
} catch (IllegalStateException noKey) {
|
||||
redirect.addFlashAttribute("error",
|
||||
message("protection.screen.noCipher", "Cannot store the captcha secret: no encryption key is "
|
||||
+ "configured (runway.security.secret-key)."));
|
||||
} catch (IOException e) {
|
||||
redirect.addFlashAttribute("error",
|
||||
message("protection.screen.failed", "Could not save protection settings."));
|
||||
}
|
||||
return "redirect:" + SETTINGS_PAGE;
|
||||
}
|
||||
|
||||
private String message(String key, String fallback) {
|
||||
return messages.getMessage(key, null, fallback, LocaleContextHolder.getLocale());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
package mx.quest.protection;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* The read-model the app-level Essential Protection panel ({@code templates/admin-app.html}) binds to. The panel
|
||||
* renders on the plugin's OWN settings page ({@code /__app/plugins/protection/settings}) — a kernel-owned page that
|
||||
* does not populate the plugin's model — so the fragment pulls the current app-scope login-protection settings
|
||||
* through this bean via {@code ${@appProtectionPanel.*}} rather than controller-set model attributes.
|
||||
*
|
||||
* <p>Every getter reads the live app snapshot ({@link ProtectionConfigStore#appSettings()}), so the panel reflects
|
||||
* the last {@linkplain AppProtectionController immediate save} with no restart. The captcha secret is exposed
|
||||
* <b>only</b> as a boolean ({@link #secretConfigured()}) — never the plaintext or the {@code ENC(...)} blob — so a
|
||||
* secret is never rendered into an input; {@link #secretStorable()} drives the "no encryption key" hint.
|
||||
*/
|
||||
public class AppProtectionPanel {
|
||||
|
||||
private final ProtectionConfigStore store;
|
||||
|
||||
public AppProtectionPanel(ProtectionConfigStore store) {
|
||||
this.store = store;
|
||||
}
|
||||
|
||||
private ProtectionSettings current() {
|
||||
return store.appSettings();
|
||||
}
|
||||
|
||||
public boolean honeypotEnabled() {
|
||||
return current().honeypotEnabled();
|
||||
}
|
||||
|
||||
public int maxAttempts() {
|
||||
return current().maxAttempts();
|
||||
}
|
||||
|
||||
public int windowSeconds() {
|
||||
return current().windowSeconds();
|
||||
}
|
||||
|
||||
public int lockoutSeconds() {
|
||||
return current().lockoutSeconds();
|
||||
}
|
||||
|
||||
public boolean captchaEnabled() {
|
||||
return current().captcha().enabled();
|
||||
}
|
||||
|
||||
public String provider() {
|
||||
return current().captcha().provider();
|
||||
}
|
||||
|
||||
public String siteKey() {
|
||||
return current().captcha().siteKey();
|
||||
}
|
||||
|
||||
public double scoreThreshold() {
|
||||
return current().captcha().scoreThreshold();
|
||||
}
|
||||
|
||||
/** The captcha providers the select offers (the four {@link CaptchaVerifier} knows). */
|
||||
public List<String> providers() {
|
||||
return ProtectionForm.PROVIDERS;
|
||||
}
|
||||
|
||||
/** Whether a captcha secret is currently stored — the panel shows a "configured" hint, never the value. */
|
||||
public boolean secretConfigured() {
|
||||
String secret = current().captcha().secretKey();
|
||||
return secret != null && !secret.isBlank();
|
||||
}
|
||||
|
||||
/** Whether a secret can be stored at all (an encryption key is configured); false ⇒ the panel warns. */
|
||||
public boolean secretStorable() {
|
||||
return store.secretStorable();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
package mx.quest.protection;
|
||||
|
||||
import java.util.List;
|
||||
import mx.quest.runway.web.CspHostContributor;
|
||||
|
||||
/**
|
||||
* Allowlists <b>Google reCAPTCHA</b>'s domains in the kernel Content-Security-Policy (via the {@link
|
||||
* CspHostContributor} seam), so a configured challenge renders and verifies cleanly — and so a strict
|
||||
* (enforce-mode) CSP and a CAPTCHA can coexist instead of the policy blocking the widget's script, iframe and
|
||||
* verification beacon.
|
||||
*
|
||||
* <p>The plugin supports exactly one provider (reCAPTCHA v2/v3), so the allowlist is a <b>static, minimal</b>
|
||||
* pair — {@code www.google.com} (the widget script + challenge iframe) and {@code www.gstatic.com} (its static
|
||||
* assets) — with no host that never loads. (Before 0.4.0 the plugin shipped Turnstile + hCaptcha too and
|
||||
* contributed the union of all providers' hosts; collapsing to one provider removed that always-present-but-idle
|
||||
* surface. A future provider returning as an override-plugin would contribute its own hosts through this same
|
||||
* seam, and — being the active provider — would replace, not widen, the set.) The hosts widen {@code script-src}
|
||||
* (the widget script), {@code frame-src} (the challenge iframe) and {@code connect-src} (verification/telemetry).
|
||||
*
|
||||
* <p>Under the kernel's {@code script-src} {@code 'strict-dynamic'} (the nonce migration), the {@code script-src}
|
||||
* contribution becomes an <b>old-browser fallback</b>: on a modern browser the login page's nonced reCAPTCHA
|
||||
* loader is trusted directly and pulls its {@code gstatic} chunks transitively, so the host allowlist is ignored
|
||||
* there. The {@code connect-src} (verify beacon) and {@code frame-src} (challenge iframe) contributions stay
|
||||
* <b>load-bearing</b> — {@code 'strict-dynamic'} governs {@code script-src} only, never those — so the hosts must
|
||||
* remain on all three; do not drop them.
|
||||
*
|
||||
* <p>The public site keys and the secret never touch this: it is a static host allowlist only.
|
||||
*/
|
||||
public final class CaptchaCspContributor implements CspHostContributor {
|
||||
|
||||
private static final List<String> HOSTS = List.of(
|
||||
"https://www.google.com", "https://www.gstatic.com"); // Google reCAPTCHA v2/v3 (script + iframe + connect)
|
||||
|
||||
@Override
|
||||
public List<String> cspHosts() {
|
||||
return HOSTS;
|
||||
}
|
||||
}
|
||||
+138
@@ -0,0 +1,138 @@
|
||||
package mx.quest.protection;
|
||||
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import mx.quest.runway.security.ProtectionScope;
|
||||
import mx.quest.runway.site.Site;
|
||||
import mx.quest.runway.site.SiteResolver;
|
||||
import org.springframework.web.servlet.HandlerInterceptor;
|
||||
import org.springframework.web.servlet.ModelAndView;
|
||||
|
||||
/**
|
||||
* Makes a login PAGE render the CAPTCHA widget without putting any provider knowledge in the kernel login
|
||||
* controllers or templates. Registered by the plugin as a {@link HandlerInterceptor} scoped to the two login-view
|
||||
* GETs ({@code /app/login} and {@code /login}); on those requests it resolves the {@link ProtectionScope} exactly
|
||||
* as the {@link LoginProtectionFilter} does — the application scope for the operator login, the
|
||||
* {@link SiteResolver#current() current site} for a tenant login — and, when that scope's
|
||||
* {@link ProtectionSettings.Captcha} is {@link ProtectionSettings.Captcha#active() active}, adds the generic,
|
||||
* provider-agnostic model flags the kernel's "captcha goes here" template slot binds:
|
||||
*
|
||||
* <ul>
|
||||
* <li>{@code captchaActive} — whether the widget/script should render at all;</li>
|
||||
* <li>{@code captchaProvider} — the reCAPTCHA mode ({@code recaptcha-v2}/{@code recaptcha-v3}), plus the two
|
||||
* booleans {@code captchaRecaptchaV2} / {@code captchaRecaptchaV3} so the template can pick the visible vs
|
||||
* invisible widget shape without a string switch;</li>
|
||||
* <li>{@code captchaSiteKey} — the <b>public</b> site key only;</li>
|
||||
* <li>{@code captchaWidgetClass} — the widget CSS class the reCAPTCHA JS API looks for ({@code g-recaptcha}
|
||||
* for v2; empty for the invisible v3);</li>
|
||||
* <li>{@code captchaScriptUrl} — the provider's widget script {@code src} (for reCAPTCHA v3 it carries the
|
||||
* {@code ?render=<siteKey>} the invisible-execute flow needs);</li>
|
||||
* <li>{@code captchaTokenField} — the request parameter the widget posts its token under, so the v3 hidden
|
||||
* field and the guard agree.</li>
|
||||
* </ul>
|
||||
*
|
||||
* <p><b>The CAPTCHA secret is never exposed.</b> Only {@link ProtectionSettings.Captcha#siteKey()} (public) and
|
||||
* the provider id reach the model — {@link ProtectionSettings.Captcha#secretKey()} is read solely server-side by
|
||||
* {@link CaptchaVerifier}. When the scope's captcha is inactive, the interceptor sets {@code captchaActive=false}
|
||||
* and nothing else, so the template renders no widget and no provider script.
|
||||
*
|
||||
* <p><b>Fail-safe.</b> A store fault degrades to {@link ProtectionSettings#defaults()} (captcha off) inside
|
||||
* {@link ProtectionConfigStore#resolve}, so a config problem hides the widget rather than breaking the login page.
|
||||
*/
|
||||
public final class CaptchaLoginViewContributor implements HandlerInterceptor {
|
||||
|
||||
private static final String APP_LOGIN_PATH = "/app/login";
|
||||
private static final String TENANT_LOGIN_PATH = "/login";
|
||||
private static final String APP_FORGOT_PATH = "/app/forgot-password";
|
||||
private static final String TENANT_FORGOT_PATH = "/forgot-password";
|
||||
|
||||
private final ProtectionConfigStore configStore;
|
||||
private final SiteResolver siteResolver;
|
||||
private final TrustedDeviceService trustedDeviceService;
|
||||
|
||||
public CaptchaLoginViewContributor(ProtectionConfigStore configStore, SiteResolver siteResolver,
|
||||
TrustedDeviceService trustedDeviceService) {
|
||||
this.configStore = configStore;
|
||||
this.siteResolver = siteResolver;
|
||||
this.trustedDeviceService = trustedDeviceService;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
|
||||
ModelAndView modelAndView) {
|
||||
if (modelAndView == null) {
|
||||
return; // a redirect or forward with no view/model — nothing to contribute to
|
||||
}
|
||||
// Only the GET view render gets the widget flags. A POST to a recovery path is a controller that returns a
|
||||
// "redirect:" — Spring would append every primitive model attribute we add to that redirect's query string
|
||||
// (captchaActive=…&captchaSiteKey=… leaking into the URL), so never contribute on a non-GET.
|
||||
if (!"GET".equalsIgnoreCase(request.getMethod())) {
|
||||
return;
|
||||
}
|
||||
// Defensive: never contribute primitive model flags to a redirect/forward — Spring would splice them into
|
||||
// the target's query string. No mapped handler does this today (they all return a plain view), but a future
|
||||
// GET that bounced an already-authenticated user would otherwise leak captchaActive=…&rememberDeviceDays=….
|
||||
String viewName = modelAndView.getViewName();
|
||||
if (viewName != null && (viewName.startsWith("redirect:") || viewName.startsWith("forward:"))) {
|
||||
return;
|
||||
}
|
||||
String uri = LoginFormPolicyGuard.routedPath(request);
|
||||
ProtectionScope scope = scopeFor(uri);
|
||||
if (scope == null) {
|
||||
return; // not one of the two login-view GETs
|
||||
}
|
||||
ProtectionSettings.Captcha captcha = configStore.resolve(scope).captcha();
|
||||
// A trusted device skips the CAPTCHA entirely — the widget is not even rendered — but ONLY on the login
|
||||
// form (the forgot-password form always shows its CAPTCHA, matching the guard's login-only skip).
|
||||
boolean trusted = isLoginPath(uri) && trustedDeviceService.isTrusted(request, scope);
|
||||
apply(modelAndView, captcha, trusted, isLoginPath(uri));
|
||||
}
|
||||
|
||||
/**
|
||||
* The scope for a login/recovery view GET path, or {@code null} if the interceptor does not serve it. The
|
||||
* password-recovery REQUEST form renders the same CAPTCHA as its realm's login (app scope for
|
||||
* {@code /app/forgot-password}, the current site's for {@code /forgot-password}), so a configured challenge
|
||||
* also guards the reset-email request against automated flooding.
|
||||
*/
|
||||
private ProtectionScope scopeFor(String uri) {
|
||||
if (APP_LOGIN_PATH.equals(uri) || APP_FORGOT_PATH.equals(uri)) {
|
||||
return ProtectionScope.application();
|
||||
}
|
||||
if (TENANT_LOGIN_PATH.equals(uri) || TENANT_FORGOT_PATH.equals(uri)) {
|
||||
return ProtectionScope.forSite(siteResolver.current().map(Site::id).orElse(null));
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/** Whether {@code uri} is a login form (not a forgot-password form): only there does "remember this device" apply. */
|
||||
private static boolean isLoginPath(String uri) {
|
||||
return APP_LOGIN_PATH.equals(uri) || TENANT_LOGIN_PATH.equals(uri);
|
||||
}
|
||||
|
||||
/**
|
||||
* Populates the model with the generic captcha slot flags plus the "remember this device" offer. The CAPTCHA
|
||||
* renders only when active AND the device isn't already trusted (a trusted device sets {@code captchaActive=false}
|
||||
* so no widget/script/key is emitted and the guard's matching skip lines up). The remember-device checkbox is
|
||||
* offered only where a CAPTCHA is actually shown on a LOGIN form and the feature is usable. When the CAPTCHA is
|
||||
* hidden, only the two/three flags are set; the public site key is the only key that ever reaches the view.
|
||||
*/
|
||||
private void apply(ModelAndView mav, ProtectionSettings.Captcha captcha, boolean trusted, boolean loginPath) {
|
||||
boolean showCaptcha = captcha.active() && !trusted;
|
||||
mav.addObject("captchaActive", showCaptcha);
|
||||
mav.addObject("rememberDeviceOffered", showCaptcha && loginPath && trustedDeviceService.isEnabled());
|
||||
mav.addObject("rememberDeviceDays", trustedDeviceService.rememberDays());
|
||||
if (!showCaptcha) {
|
||||
return;
|
||||
}
|
||||
// Both reCAPTCHA modes go through the same provider-shaped helpers (which normalize internally); the model
|
||||
// reduces to a single distinction — visible v2 vs invisible v3 — that the template branches on.
|
||||
boolean invisible = CaptchaVerifier.isInvisible(captcha.provider());
|
||||
mav.addObject("captchaProvider", invisible ? CaptchaVerifier.RECAPTCHA_V3 : CaptchaVerifier.DEFAULT_PROVIDER);
|
||||
mav.addObject("captchaRecaptchaV2", !invisible);
|
||||
mav.addObject("captchaRecaptchaV3", invisible);
|
||||
mav.addObject("captchaSiteKey", captcha.siteKey()); // PUBLIC key only — the secret never leaves the server
|
||||
mav.addObject("captchaWidgetClass", CaptchaVerifier.widgetClass(captcha.provider()));
|
||||
mav.addObject("captchaScriptUrl", CaptchaVerifier.scriptUrl(captcha.provider(), captcha.siteKey()));
|
||||
mav.addObject("captchaTokenField", CaptchaVerifier.tokenParam(captcha.provider()));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,224 @@
|
||||
package mx.quest.protection;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.URI;
|
||||
import java.net.URLEncoder;
|
||||
import java.net.http.HttpClient;
|
||||
import java.net.http.HttpRequest;
|
||||
import java.net.http.HttpResponse;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.Duration;
|
||||
import java.util.Locale;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
/**
|
||||
* Verifies an external CAPTCHA token server-side against the provider's {@code siteverify} endpoint, using the
|
||||
* scope's own secret. It is the second, request-aware half of the login form deterrent (after the honeypot):
|
||||
* {@link LoginFormPolicyGuard} calls it on a login POST when the scope's {@link ProtectionSettings.Captcha} is
|
||||
* {@link ProtectionSettings.Captcha#active() active}.
|
||||
*
|
||||
* <p>The supported provider is <b>Google reCAPTCHA</b> in both modes — <b>v2</b> (the visible checkbox) and
|
||||
* <b>v3</b> (invisible, score-based). Both share one {@code siteverify} shape: an
|
||||
* {@code application/x-www-form-urlencoded} POST of {@code secret}/{@code response}(/{@code remoteip}) to
|
||||
* {@value #RECAPTCHA_URL}, answered by a JSON body carrying a boolean {@code success}. Only <b>v3</b> additionally
|
||||
* returns a 0..1 risk {@code score}, which this verifier requires to meet the configured
|
||||
* {@link ProtectionSettings.Captcha#scoreThreshold() threshold}; v2 treats {@code success:true} as a pass.
|
||||
*
|
||||
* <p><b>One provider by design.</b> Cloudflare Turnstile and hCaptcha were dropped in 0.4.0: a single provider
|
||||
* keeps the kernel CSP's {@code script-src}/{@code frame-src}/{@code connect-src} allowlist minimal and static
|
||||
* ({@code www.google.com www.gstatic.com}) with nothing that never loads. The provider-shaped static helpers
|
||||
* ({@link #tokenParam}, {@link #widgetClass}, {@link #scriptUrl}, {@link #isInvisible}) are kept as a thin seam so
|
||||
* a future provider can return as an override-plugin without reshaping the call sites.
|
||||
*
|
||||
* <p><b>Two deliberate failure stances</b> keep the deterrent from ever locking out a legitimate user while still
|
||||
* rejecting a real bot:
|
||||
* <ul>
|
||||
* <li><b>Fail on a missing/rejected token.</b> A blank token (the widget never ran, or the field was stripped)
|
||||
* and a {@code success:false} response both return {@code false} — the challenge was <em>not</em> proven.</li>
|
||||
* <li><b>Fail <u>open</u> on a transport error.</b> If the provider cannot be reached (network fault, timeout,
|
||||
* non-2xx status, unparseable body), verification returns {@code true} with a warning — a provider outage
|
||||
* must not lock every user out. The always-on honeypot and per-IP lockout still apply.</li>
|
||||
* </ul>
|
||||
*
|
||||
* <p>The provider HTTP call is injected as an {@link Exchange} seam so the request-building and response-parsing
|
||||
* (including the v3 score gate and the fail-open path) are unit-testable without touching the network; the
|
||||
* production seam is a short-timeout JDK {@link HttpClient}. This class is stateless and thread-safe.
|
||||
*/
|
||||
public class CaptchaVerifier {
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(CaptchaVerifier.class);
|
||||
|
||||
/** The Google reCAPTCHA {@code siteverify} endpoint — shared by both v2 and v3. */
|
||||
static final String RECAPTCHA_URL = "https://www.google.com/recaptcha/api/siteverify";
|
||||
|
||||
/** The reCAPTCHA v3 (invisible, score-based) provider id. */
|
||||
static final String RECAPTCHA_V3 = "recaptcha-v3";
|
||||
|
||||
/** The default provider — reCAPTCHA v2 (checkbox). Any blank/unknown/legacy value normalizes to this. */
|
||||
static final String DEFAULT_PROVIDER = "recaptcha-v2";
|
||||
|
||||
private final Exchange exchange;
|
||||
|
||||
/** Production verifier: a JDK {@link HttpClient} with a short connect/read timeout as the {@link Exchange}. */
|
||||
public CaptchaVerifier() {
|
||||
this(defaultExchange());
|
||||
}
|
||||
|
||||
/**
|
||||
* @param exchange the HTTP seam that performs the {@code siteverify} POST — injectable so tests exercise the
|
||||
* request-building, response-parsing and fail-open behaviour without a real network call
|
||||
*/
|
||||
public CaptchaVerifier(Exchange exchange) {
|
||||
this.exchange = exchange;
|
||||
}
|
||||
|
||||
/**
|
||||
* The request parameter the reCAPTCHA widget posts its solved token under ({@code g-recaptcha-response} — the
|
||||
* same for v2 and v3). Shared by the guard (which reads this parameter from the login POST) and the login-view
|
||||
* contributor (which names the widget's hidden field), so the two can never drift.
|
||||
*
|
||||
* @param provider the configured provider id; retained for call-site stability (both reCAPTCHA modes use the
|
||||
* same field, so the value does not change the result today)
|
||||
*/
|
||||
public static String tokenParam(String provider) {
|
||||
return "g-recaptcha-response";
|
||||
}
|
||||
|
||||
/**
|
||||
* The provider's widget CSS class the client script scans for to auto-render the challenge; empty for
|
||||
* reCAPTCHA v3 (invisible — no rendered widget div). Shared by the login-view contributor and the site-form
|
||||
* {@code CaptchaService} so the two render identically.
|
||||
*/
|
||||
public static String widgetClass(String provider) {
|
||||
return isInvisible(provider) ? "" : "g-recaptcha";
|
||||
}
|
||||
|
||||
/**
|
||||
* The provider's widget script {@code src}. reCAPTCHA v3 needs the site key spliced into {@code ?render=} so
|
||||
* the invisible flow can execute for that key on submit; v2 loads the script keyless and reads the key from
|
||||
* the widget div's {@code data-sitekey}.
|
||||
*/
|
||||
public static String scriptUrl(String provider, String siteKey) {
|
||||
return isInvisible(provider)
|
||||
? "https://www.google.com/recaptcha/api.js?render=" + enc(siteKey == null ? "" : siteKey)
|
||||
: "https://www.google.com/recaptcha/api.js";
|
||||
}
|
||||
|
||||
/** Whether the provider is the invisible reCAPTCHA v3 (needs a submit-time execute rather than a visible widget). */
|
||||
public static boolean isInvisible(String provider) {
|
||||
return RECAPTCHA_V3.equals(normalizeProvider(provider));
|
||||
}
|
||||
|
||||
/**
|
||||
* Verifies {@code token} for the given captcha {@code config}, calling reCAPTCHA's {@code siteverify}
|
||||
* endpoint through the injected {@link Exchange}.
|
||||
*
|
||||
* @param config the scope's captcha policy (provider, secret, score threshold); the public site key is not
|
||||
* used here — verification is entirely secret-side
|
||||
* @param token the solved token the widget posted back (the {@link #tokenParam(String)} request parameter)
|
||||
* @param remoteIp the gated client IP to pass as the optional {@code remoteip} hint, or {@code null}/blank to
|
||||
* omit it
|
||||
* @return {@code true} if reCAPTCHA confirmed the challenge (and, for v3, the score met the threshold), OR if
|
||||
* the provider could not be reached (fail-open); {@code false} if the token is missing or rejected
|
||||
*/
|
||||
public boolean verify(ProtectionSettings.Captcha config, String token, String remoteIp) {
|
||||
if (token == null || token.isBlank()) {
|
||||
// No token proven — the widget never ran or the field was stripped. Not verified.
|
||||
return false;
|
||||
}
|
||||
String provider = normalizeProvider(config.provider());
|
||||
String body = "secret=" + enc(config.secretKey())
|
||||
+ "&response=" + enc(token)
|
||||
+ (remoteIp != null && !remoteIp.isBlank() ? "&remoteip=" + enc(remoteIp) : "");
|
||||
String responseBody;
|
||||
try {
|
||||
Exchange.Response resp = exchange.post(RECAPTCHA_URL, body);
|
||||
if (resp == null || resp.statusCode() / 100 != 2) {
|
||||
log.warn("reCAPTCHA provider '{}' returned HTTP {} — failing open.",
|
||||
provider, resp == null ? "no response" : resp.statusCode());
|
||||
return true; // fail-open: a provider outage never locks everyone out
|
||||
}
|
||||
responseBody = resp.body();
|
||||
} catch (IOException | RuntimeException e) {
|
||||
log.warn("reCAPTCHA verification could not reach the provider ({}) — failing open.", e.toString());
|
||||
return true; // fail-open on any transport fault
|
||||
}
|
||||
|
||||
if (!SiteVerifyResponse.success(responseBody)) {
|
||||
return false; // provider actively rejected the token
|
||||
}
|
||||
if (RECAPTCHA_V3.equals(provider)) {
|
||||
double score = SiteVerifyResponse.score(responseBody);
|
||||
double threshold = config.scoreThreshold();
|
||||
if (score < threshold) {
|
||||
log.info("reCAPTCHA v3 score {} below threshold {} — rejecting.", score, threshold);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Normalizes any stored provider id to one of the two supported reCAPTCHA modes: {@link #RECAPTCHA_V3} when it
|
||||
* names v3, else {@link #DEFAULT_PROVIDER} ({@code recaptcha-v2}). A legacy value from a dropped provider
|
||||
* (Turnstile / hCaptcha) therefore migrates to v2 — the site keeps working after upgrade, though its operator
|
||||
* must supply a reCAPTCHA key for the challenge to actually pass. Blank/null also maps to v2.
|
||||
*/
|
||||
private static String normalizeProvider(String provider) {
|
||||
if (provider != null && RECAPTCHA_V3.equals(provider.trim().toLowerCase(Locale.ROOT))) {
|
||||
return RECAPTCHA_V3;
|
||||
}
|
||||
return DEFAULT_PROVIDER;
|
||||
}
|
||||
|
||||
private static String enc(String v) {
|
||||
return URLEncoder.encode(v == null ? "" : v, StandardCharsets.UTF_8);
|
||||
}
|
||||
|
||||
private static Exchange defaultExchange() {
|
||||
HttpClient http = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(5)).build();
|
||||
return (url, body) -> {
|
||||
HttpRequest req = HttpRequest.newBuilder(URI.create(url))
|
||||
.timeout(Duration.ofSeconds(5))
|
||||
.header("Content-Type", "application/x-www-form-urlencoded")
|
||||
.POST(HttpRequest.BodyPublishers.ofString(body, StandardCharsets.UTF_8))
|
||||
.build();
|
||||
try {
|
||||
HttpResponse<String> resp = http.send(req, HttpResponse.BodyHandlers.ofString());
|
||||
return new Exchange.Response(resp.statusCode(), resp.body());
|
||||
} catch (InterruptedException e) {
|
||||
// Restore the interrupt flag and surface as an IOException so the verifier fails open like any
|
||||
// other transport fault (a provider hiccup must never lock everyone out).
|
||||
Thread.currentThread().interrupt();
|
||||
throw new IOException("interrupted while verifying CAPTCHA", e);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* The injectable HTTP seam — a single form POST to reCAPTCHA's {@code siteverify} endpoint. Real deployments
|
||||
* use the JDK {@link HttpClient} exchange ({@link #defaultExchange()}); tests supply a stub that records the
|
||||
* URL/body and returns a canned {@link Response} (or throws) to exercise every branch without a network.
|
||||
*/
|
||||
@FunctionalInterface
|
||||
public interface Exchange {
|
||||
|
||||
/**
|
||||
* POSTs {@code formBody} ({@code application/x-www-form-urlencoded}) to {@code url}.
|
||||
*
|
||||
* @return the provider's response (status + body)
|
||||
* @throws IOException if the request cannot be completed (the verifier treats this as fail-open)
|
||||
*/
|
||||
Response post(String url, String formBody) throws IOException;
|
||||
|
||||
/**
|
||||
* A minimal HTTP response view — only the status code and textual body the verifier needs.
|
||||
*
|
||||
* @param statusCode the HTTP status code
|
||||
* @param body the response body (the provider's {@code siteverify} JSON)
|
||||
*/
|
||||
record Response(int statusCode, String body) {
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
package mx.quest.protection;
|
||||
|
||||
import mx.quest.runway.console.AssetVersion;
|
||||
import mx.quest.runway.security.ProtectionScope;
|
||||
import mx.quest.runway.spi.CaptchaService;
|
||||
import mx.quest.runway.spi.model.CaptchaWidget;
|
||||
|
||||
/**
|
||||
* The protection plugin's {@link CaptchaService} implementation — the reusable site-form CAPTCHA seam, backed by
|
||||
* each site's own per-site CAPTCHA settings (the same {@link ProtectionConfigStore} + {@link CaptchaVerifier} that
|
||||
* guard the login form). Registered {@code @Primary} so it wins by-type injection over the kernel's permissive
|
||||
* {@code NoCaptchaService} default wherever this essential plugin is present.
|
||||
*
|
||||
* <p>{@link #widgetForSite(String)} resolves the site scope and, when its challenge is
|
||||
* {@link ProtectionSettings.Captcha#active() active}, returns a self-contained widget: the visible
|
||||
* <b>reCAPTCHA v2</b> renders a challenge div the provider script auto-fills into a hidden field the form
|
||||
* submits; the invisible <b>reCAPTCHA v3</b> renders a hidden token field plus a small submit-time execute
|
||||
* script. Only the <b>public</b> site key is ever embedded — the secret is read solely server-side by
|
||||
* {@link CaptchaVerifier} in {@link #verify}. An inactive site yields {@link CaptchaWidget#inactive()} and
|
||||
* {@code verify} accepts unconditionally, so a form is never blocked by a CAPTCHA it did not configure.
|
||||
*/
|
||||
public class CaptchaWidgetService implements CaptchaService {
|
||||
|
||||
/** The kernel-served reCAPTCHA v3 client (shared with the operator login pages). */
|
||||
private static final String V3_CLIENT = "/__assets/captcha-v3.js";
|
||||
|
||||
private final ProtectionConfigStore configStore;
|
||||
private final CaptchaVerifier verifier;
|
||||
/** The kernel's v3 client URL, carrying the {@code ?v=} asset token when one was supplied. */
|
||||
private final String v3ClientUrl;
|
||||
|
||||
/**
|
||||
* Without an asset version: the v3 client is referenced unversioned, which the kernel serves {@code no-cache}
|
||||
* (always revalidated) — correct, only less cache-efficient. Kept for callers built before the token existed.
|
||||
*/
|
||||
public CaptchaWidgetService(ProtectionConfigStore configStore, CaptchaVerifier verifier) {
|
||||
this(configStore, verifier, null);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param assetVersion the kernel's asset token, appended as {@code ?v=} to the {@code /__assets/captcha-v3.js}
|
||||
* reference so an upgrade is never shadowed by a day-cached old client; {@code null} leaves
|
||||
* it unversioned
|
||||
*/
|
||||
public CaptchaWidgetService(ProtectionConfigStore configStore, CaptchaVerifier verifier,
|
||||
AssetVersion assetVersion) {
|
||||
this.configStore = configStore;
|
||||
this.verifier = verifier;
|
||||
this.v3ClientUrl = assetVersion == null ? V3_CLIENT : assetVersion.url(V3_CLIENT);
|
||||
}
|
||||
|
||||
@Override
|
||||
public CaptchaWidget widgetForSite(String siteId) {
|
||||
ProtectionSettings.Captcha captcha = captchaFor(siteId);
|
||||
if (!captcha.active()) {
|
||||
return CaptchaWidget.inactive();
|
||||
}
|
||||
String provider = captcha.provider();
|
||||
return new CaptchaWidget(true, CaptchaVerifier.tokenParam(provider), renderHtml(captcha, provider, v3ClientUrl));
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean verify(String siteId, String token, String clientIp) {
|
||||
ProtectionSettings.Captcha captcha = captchaFor(siteId);
|
||||
if (!captcha.active()) {
|
||||
return true; // no challenge configured for this site — nothing to prove
|
||||
}
|
||||
return verifier.verify(captcha, token, clientIp);
|
||||
}
|
||||
|
||||
private ProtectionSettings.Captcha captchaFor(String siteId) {
|
||||
return configStore.resolve(ProtectionScope.forSite(siteId)).captcha();
|
||||
}
|
||||
|
||||
/** The self-contained widget markup for an active challenge — div/hidden field + provider script. */
|
||||
private static String renderHtml(ProtectionSettings.Captcha captcha, String provider, String v3ClientUrl) {
|
||||
String siteKey = attr(captcha.siteKey());
|
||||
String script = attr(CaptchaVerifier.scriptUrl(provider, captcha.siteKey()));
|
||||
if (CaptchaVerifier.isInvisible(provider)) {
|
||||
// reCAPTCHA v3: invisible — a hidden token field + a submit-time execute for every form carrying one.
|
||||
String field = attr(CaptchaVerifier.tokenParam(provider));
|
||||
return "<input type=\"hidden\" class=\"rw-captcha-v3\" name=\"" + field + "\" data-sitekey=\"" + siteKey
|
||||
+ "\">"
|
||||
+ "<script src=\"" + script + "\" async defer></script>"
|
||||
// The v3 client is served once from the kernel at /__assets/captcha-v3.js (shared with the
|
||||
// operator login pages) — an inline <script> here would violate the tightened script-src.
|
||||
+ "<script src=\"" + attr(v3ClientUrl) + "\" async defer></script>";
|
||||
}
|
||||
// Visible providers auto-render into <div class="<widgetClass>" data-sitekey="…"> and post a hidden field.
|
||||
return "<div class=\"" + attr(CaptchaVerifier.widgetClass(provider)) + " rw-captcha\" data-sitekey=\""
|
||||
+ siteKey + "\"></div>"
|
||||
+ "<script src=\"" + script + "\" async defer></script>";
|
||||
}
|
||||
|
||||
/** Minimal attribute escaping for the operator-configured values embedded in the widget markup. */
|
||||
private static String attr(String value) {
|
||||
if (value == null) {
|
||||
return "";
|
||||
}
|
||||
return value.replace("&", "&").replace("\"", """).replace("<", "<").replace(">", ">");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,150 @@
|
||||
package mx.quest.protection;
|
||||
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import java.time.Instant;
|
||||
import java.time.ZoneId;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import mx.quest.runway.spi.service.ConsoleScreen;
|
||||
import mx.quest.runway.web.ClientIp;
|
||||
import org.springframework.beans.factory.annotation.Qualifier;
|
||||
import org.springframework.context.MessageSource;
|
||||
import org.springframework.context.i18n.LocaleContextHolder;
|
||||
import org.springframework.security.access.prepost.PreAuthorize;
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.ui.Model;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
|
||||
|
||||
/**
|
||||
* The application-realm <b>DoS activity</b> screen ({@code /__app/dos}) — the operator's live view of the abuse
|
||||
* floor: the busiest <b>rate-limit offenders</b> (IP + recent-429 count, from the {@link TokenBucketRateLimiter})
|
||||
* and the current {@link IpBlocklist} (each entry's IP, reason, manual/auto source and expiry), with an
|
||||
* <b>Unblock</b> action per entry and a small form to <b>Block</b> an IP/CIDR manually.
|
||||
*
|
||||
* <p>App-level platform concern — never a per-tenant surface. Gated by the plugin's own {@code protection|settings}
|
||||
* control point (app realm; the app master/wildcard admin always passes), exactly like the app Protection screen.
|
||||
* Renders inside the kernel {@code op-layout} shell as a {@link ConsoleScreen} (the SPI's shell seam), supplying only
|
||||
* its {@code contentTemplate} + {@code pageTitleKey}.
|
||||
*
|
||||
* <p><b>Safety rail.</b> A manual block refuses the operator's own gated IP and any allowlisted/loopback address
|
||||
* (rejected with a clear message) — {@link IpBlocklist#block} enforces the allowlist rule too, so the screen can
|
||||
* never lock the operator out of the console. A manual block persists; an unblock removes it.
|
||||
*/
|
||||
@Controller
|
||||
@ConsoleScreen
|
||||
public class DosController {
|
||||
|
||||
/** Displayed-timestamp format for a block's expiry (local zone), matching the listing-table date convention. */
|
||||
private static final DateTimeFormatter TS =
|
||||
DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm").withZone(ZoneId.systemDefault());
|
||||
|
||||
private final TokenBucketRateLimiter limiter;
|
||||
private final IpBlocklist blocklist;
|
||||
private final MessageSource messages;
|
||||
|
||||
public DosController(TokenBucketRateLimiter limiter, IpBlocklist blocklist,
|
||||
@Qualifier("operatorAwareMessageSource") MessageSource messages) {
|
||||
this.limiter = limiter;
|
||||
this.blocklist = blocklist;
|
||||
this.messages = messages;
|
||||
}
|
||||
|
||||
@GetMapping("/__app/dos")
|
||||
@PreAuthorize("@authz.may('protection|settings')")
|
||||
public String view(Model model) {
|
||||
List<OffenderRow> offenders = new ArrayList<>();
|
||||
for (TokenBucketRateLimiter.Offender o : limiter.topOffenders(50)) {
|
||||
offenders.add(new OffenderRow(o.ip(), o.requests(), o.throttled(), blocklist.isBlocked(o.ip())));
|
||||
}
|
||||
List<BlockRow> blocks = new ArrayList<>();
|
||||
for (IpBlocklist.Entry b : blocklist.list()) {
|
||||
String until = b.indefinite()
|
||||
? message("dos.block.indefinite", "indefinite")
|
||||
: TS.format(Instant.ofEpochSecond(b.untilEpochSeconds()));
|
||||
String source = b.manual()
|
||||
? message("dos.source.manual", "manual")
|
||||
: message("dos.source.auto", "auto");
|
||||
blocks.add(new BlockRow(b.ip(), b.reason() == null ? "" : b.reason(), source, until, b.manual()));
|
||||
}
|
||||
// list() prunes lapsed entries, so the history below is current only because it ran first.
|
||||
List<EndedRow> ended = new ArrayList<>();
|
||||
for (IpBlocklist.Lapsed e : blocklist.recentlyEnded()) {
|
||||
ended.add(new EndedRow(e.ip(), e.reason() == null ? "" : e.reason(),
|
||||
e.manual() ? message("dos.source.manual", "manual") : message("dos.source.auto", "auto"),
|
||||
TS.format(Instant.ofEpochSecond(e.endedAt()))));
|
||||
}
|
||||
|
||||
model.addAttribute("offenders", offenders);
|
||||
model.addAttribute("blocks", blocks);
|
||||
model.addAttribute("ended", ended);
|
||||
model.addAttribute(ConsoleScreen.CONTENT_TEMPLATE, "__plugin__/protection/app-dos");
|
||||
model.addAttribute(ConsoleScreen.PAGE_TITLE_KEY, "dos.screen.title");
|
||||
return ConsoleScreen.LAYOUT_VIEW;
|
||||
}
|
||||
|
||||
@PostMapping("/__app/dos/block")
|
||||
@PreAuthorize("@authz.may('protection|settings')")
|
||||
public String block(@RequestParam(required = false) String ip,
|
||||
@RequestParam(defaultValue = "900") long seconds,
|
||||
@RequestParam(required = false) String reason,
|
||||
HttpServletRequest request,
|
||||
RedirectAttributes redirect) {
|
||||
String target = ip == null ? "" : ip.trim();
|
||||
String self = ClientIp.of(request);
|
||||
if (target.isBlank()) {
|
||||
redirect.addFlashAttribute("error", message("dos.block.blank", "Enter an IP address or CIDR to block."));
|
||||
} else if (target.equals(self) || blocklist.isAllowlisted(target)) {
|
||||
redirect.addFlashAttribute("error",
|
||||
message("dos.block.refused", "Refusing to block your own address or an allowlisted one."));
|
||||
} else {
|
||||
String why = (reason == null || reason.isBlank())
|
||||
? message("dos.source.manual", "manual")
|
||||
: reason.trim();
|
||||
boolean applied = blocklist.block(target, seconds, why, true);
|
||||
if (applied) {
|
||||
redirect.addFlashAttribute("flash", message("dos.block.done", "Address blocked."));
|
||||
} else {
|
||||
// block() only refuses allowlisted/blank — already handled above; this is a defensive fallback.
|
||||
redirect.addFlashAttribute("error",
|
||||
message("dos.block.refused", "Refusing to block your own address or an allowlisted one."));
|
||||
}
|
||||
}
|
||||
return "redirect:/__app/dos";
|
||||
}
|
||||
|
||||
@PostMapping("/__app/dos/unblock")
|
||||
@PreAuthorize("@authz.may('protection|settings')")
|
||||
public String unblock(@RequestParam(required = false) String ip, RedirectAttributes redirect) {
|
||||
if (ip != null && !ip.isBlank()) {
|
||||
blocklist.unblock(ip.trim());
|
||||
redirect.addFlashAttribute("flash", message("dos.unblock.done", "Address unblocked."));
|
||||
}
|
||||
return "redirect:/__app/dos";
|
||||
}
|
||||
|
||||
private String message(String key, String fallback) {
|
||||
return messages.getMessage(key, null, fallback, LocaleContextHolder.getLocale());
|
||||
}
|
||||
|
||||
/** A rate-limit offender row for the screen: the IP, its total requests, its throttled (429) count, blocked?. */
|
||||
public record OffenderRow(String ip, long requests, long throttled, boolean blocked) {
|
||||
}
|
||||
|
||||
/** A blocklist row for the screen: the IP/CIDR, reason, source (manual/auto), expiry text, and manual flag. */
|
||||
/**
|
||||
* A block that is no longer in force: what it was, and when it ended.
|
||||
*
|
||||
* <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?" arrives to an empty blocklist and no way to tell. The evidence
|
||||
* deleted itself at exactly the rate that makes it hardest to catch.
|
||||
*/
|
||||
public record EndedRow(String ip, String reason, String source, String endedAt) {
|
||||
}
|
||||
|
||||
public record BlockRow(String ip, String reason, String source, String until, boolean manual) {
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,400 @@
|
||||
package mx.quest.protection;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.InetAddress;
|
||||
import java.nio.file.Path;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Comparator;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import mx.quest.runway.storage.StorageLayout;
|
||||
import mx.quest.runway.storage.YamlStore;
|
||||
import mx.quest.runway.web.CidrSet;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
/**
|
||||
* The mutable set of currently-blocked IPs and CIDRs consulted on <b>every</b> request by the DoS floor
|
||||
* ({@link RateLimitEdgeGuard}), plus the auto-escalation target of {@link TokenBucketRateLimiter}. It is the
|
||||
* platform-realm abuse blocklist (never per-tenant): a directly-reachable abuser is turned away before the
|
||||
* security chain.
|
||||
*
|
||||
* <h2>Manual vs. auto blocks — two lifecycles</h2>
|
||||
* <ul>
|
||||
* <li><b>Manual</b> blocks (an operator's deliberate ban from the {@code /__app/dos} screen) are
|
||||
* <b>persisted</b> to {@code external/blocklist.yml} so they survive a restart. Only manual blocks are
|
||||
* ever written; the file is rewritten on every manual change (block/unblock/prune of a manual entry).</li>
|
||||
* <li><b>Auto</b> blocks (a rate-limit breach escalated by {@link TokenBucketRateLimiter}) are
|
||||
* <b>in-memory only</b> — ephemeral by design: they expire by their own timer and are re-earned by a
|
||||
* still-abusive IP after a restart, so a transient flood never leaves a stale ban on disk.</li>
|
||||
* </ul>
|
||||
*
|
||||
* <h2>Allowlist / loopback — never blockable</h2>
|
||||
* Loopback ({@code 127.0.0.0/8}, {@code ::1}) and the configured allowlist CIDRs are <b>always allowlisted</b>:
|
||||
* {@link #isAllowlisted(String)} short-circuits {@link #isBlocked(String)} (an allowlisted IP is never reported
|
||||
* blocked even if an entry somehow names it), and {@link #block} refuses an allowlisted target outright. This is
|
||||
* the safety rail against auto-blocking a health probe, a trusted proxy, or the operator's own loopback.
|
||||
*
|
||||
* <h2>Hot-path cost</h2>
|
||||
* {@link #isBlocked(String)} is O(1) for the common exact-IP case (a single {@link ConcurrentHashMap} lookup and
|
||||
* a lazy expiry prune of just that entry — never a full scan), plus a membership test against a small
|
||||
* {@link CidrSet} rebuilt only when a CIDR-form entry is added/removed (rare). The allowlist check is likewise a
|
||||
* cheap loopback test + small {@link CidrSet} lookup. Fail-<b>open</b>: any fault in the check path returns "not
|
||||
* blocked" so a blocklist bug can never turn away legitimate traffic — the rate-limit floor still applies.
|
||||
*
|
||||
* <p>Thread-safe (a lock-free map on the hot path; manual persistence serialized through {@link YamlStore}).
|
||||
*/
|
||||
public final class IpBlocklist {
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(IpBlocklist.class);
|
||||
|
||||
private final Path file;
|
||||
private final YamlStore yaml;
|
||||
private final CidrSet allowlist;
|
||||
|
||||
/** All active blocks (manual + auto), keyed by the exact IP/CIDR string. Lock-free on the read hot path. */
|
||||
private final ConcurrentHashMap<String, Entry> blocks = new ConcurrentHashMap<>();
|
||||
|
||||
/** The CIDR-form blocked entries only, rebuilt on mutation (rare); an exact IP is matched by the map above. */
|
||||
private volatile CidrSet cidrBlocks = CidrSet.of(List.of());
|
||||
|
||||
/** Injectable epoch-seconds clock so expiry is deterministically testable. */
|
||||
private final java.util.function.LongSupplier nowSeconds;
|
||||
|
||||
/**
|
||||
* @param layout the kernel storage layout (yields {@code external/blocklist.yml})
|
||||
* @param yaml the shared YAML store (atomic, per-file-serialized writes)
|
||||
* @param allowlist the configured trusted CIDRs — never blockable (loopback is always added on top)
|
||||
*/
|
||||
public IpBlocklist(StorageLayout layout, YamlStore yaml, CidrSet allowlist) {
|
||||
this(layout.blocklistFile(), yaml, allowlist, () -> System.currentTimeMillis() / 1000L);
|
||||
}
|
||||
|
||||
/** Full constructor with an injectable clock, for tests. */
|
||||
IpBlocklist(Path file, YamlStore yaml, CidrSet allowlist, java.util.function.LongSupplier nowSeconds) {
|
||||
this.file = file;
|
||||
this.yaml = yaml;
|
||||
this.allowlist = allowlist != null ? allowlist : CidrSet.of(List.of());
|
||||
this.nowSeconds = nowSeconds;
|
||||
loadManual();
|
||||
rebuildCidrIndex();
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether {@code ip} is on the never-block allowlist: a loopback address ({@code 127.0.0.0/8} / {@code ::1})
|
||||
* or a member of the configured allowlist CIDRs. Fail-safe — a malformed literal is simply not allowlisted.
|
||||
*/
|
||||
public boolean isAllowlisted(String ip) {
|
||||
if (ip == null || ip.isBlank()) {
|
||||
return false;
|
||||
}
|
||||
if (isLoopback(ip)) {
|
||||
return true;
|
||||
}
|
||||
return allowlist.contains(ip);
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether {@code ip} is currently blocked. O(1) for an exact-IP hit (with a lazy prune if that one entry just
|
||||
* expired), then a membership test against the small CIDR index. An allowlisted IP is <b>never</b> blocked.
|
||||
* Fail-<b>open</b>: any fault returns {@code false} (the rate-limit floor still applies).
|
||||
*/
|
||||
public boolean isBlocked(String ip) {
|
||||
return blockKind(ip) != null;
|
||||
}
|
||||
|
||||
/**
|
||||
* The same decision as {@link #isBlocked}, but reporting <b>which kind</b> of block matched — or
|
||||
* {@code null} when the address is not blocked.
|
||||
*
|
||||
* <p>Exists because a bare {@code 403} is not diagnosable. An operator seeing a rejection needs to know
|
||||
* whether <i>they</i> banned the address or whether the system escalated it after repeated throttling:
|
||||
* those look identical on the wire and call for opposite responses. The returned token is short and closed
|
||||
* ({@code blocklist-manual}, {@code blocklist-auto}, {@code blocklist-cidr}) because it becomes both a log
|
||||
* field and a metric tag.
|
||||
*
|
||||
* <p>{@code blocklist-cidr} does not distinguish manual from auto: the CIDR index answers membership only,
|
||||
* and widening it to carry entries would add work to the hot path for a case that is rare and already
|
||||
* greppable in {@code blocklist.yml}. Stated here rather than silently conflated.
|
||||
*
|
||||
* <p>{@link #isBlocked} delegates to this so the two can never disagree — the fail-open contract, the
|
||||
* allowlist precedence and the lazy prune all live in one place.
|
||||
*/
|
||||
public String blockKind(String ip) {
|
||||
Match match = match(ip);
|
||||
return match == null ? null : match.kind();
|
||||
}
|
||||
|
||||
/**
|
||||
* A matched block: which kind it is, and how long it still has to run.
|
||||
*
|
||||
* @param kind {@code blocklist-manual}, {@code blocklist-auto} or {@code blocklist-cidr}
|
||||
* @param remainingSeconds seconds until the block lifts, or {@code 0} when it is indefinite
|
||||
*/
|
||||
public record Match(String kind, long remainingSeconds) {
|
||||
|
||||
/** Whether this block was escalated by the rate limiter rather than decided by an operator. */
|
||||
public boolean autoEscalated() {
|
||||
return "blocklist-auto".equals(kind);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* {@link #blockKind} plus the block's <b>remaining duration</b> — everything the edge needs to answer.
|
||||
*
|
||||
* <p>The duration is what turns a rejection into a usable signal. An auto-block is the rate limiter
|
||||
* escalating, so it can honestly say "come back in N seconds"; an operator ban cannot, and should not
|
||||
* pretend to. Reading the remaining time here rather than at the call site keeps it consistent with the
|
||||
* expiry decision made three lines above it — computing it separately would let the two disagree at a
|
||||
* block's final second, which is precisely when it matters.
|
||||
*/
|
||||
public Match match(String ip) {
|
||||
if (ip == null || ip.isBlank()) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
if (isAllowlisted(ip)) {
|
||||
return null;
|
||||
}
|
||||
long now = nowSeconds.getAsLong();
|
||||
Entry exact = blocks.get(ip);
|
||||
if (exact != null) {
|
||||
if (exact.isExpired(now)) {
|
||||
remove(ip); // lazy prune of just this entry — no scan on the hot path
|
||||
} else {
|
||||
long remaining = exact.indefinite() ? 0 : Math.max(1, exact.untilEpochSeconds() - now);
|
||||
return new Match(exact.manual() ? "blocklist-manual" : "blocklist-auto", remaining);
|
||||
}
|
||||
}
|
||||
return cidrBlocks.contains(ip) ? new Match("blocklist-cidr", 0) : null;
|
||||
} catch (RuntimeException failOpen) {
|
||||
log.warn("blocklist check failed for {} — failing open (rate-limit floor still applies): {}",
|
||||
ip, failOpen.toString());
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Blocks {@code ipOrCidr} for {@code seconds} (a value {@code <= 0} means an indefinite block). An
|
||||
* <b>allowlisted</b> target is refused (returns {@code false}) — loopback and trusted CIDRs are unblockable.
|
||||
* A <b>manual</b> block is persisted to {@code blocklist.yml}; an <b>auto</b> block stays in memory only.
|
||||
*
|
||||
* @param ipOrCidr the IP or CIDR to ban (trimmed)
|
||||
* @param seconds the ban duration in seconds ({@code <= 0} ⇒ indefinite)
|
||||
* @param reason a short human-readable reason (shown on the DoS screen)
|
||||
* @param manual {@code true} for an operator block (persisted), {@code false} for an auto-escalated one
|
||||
* @return {@code true} if the block was applied, {@code false} if the target was refused (allowlisted/blank)
|
||||
*/
|
||||
public boolean block(String ipOrCidr, long seconds, String reason, boolean manual) {
|
||||
if (ipOrCidr == null || ipOrCidr.isBlank()) {
|
||||
return false;
|
||||
}
|
||||
String key = ipOrCidr.trim();
|
||||
if (isAllowlisted(key)) {
|
||||
return false; // never block loopback or an allowlisted CIDR (safety rail)
|
||||
}
|
||||
long until = seconds <= 0 ? 0L : nowSeconds.getAsLong() + seconds;
|
||||
blocks.put(key, new Entry(key, reason == null ? "" : reason, until, manual));
|
||||
if (isCidr(key)) {
|
||||
rebuildCidrIndex();
|
||||
}
|
||||
if (manual) {
|
||||
persistManual();
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/** Removes {@code ipOrCidr} from the blocklist (rewriting the file if a manual entry was removed). */
|
||||
public void unblock(String ipOrCidr) {
|
||||
if (ipOrCidr == null) {
|
||||
return;
|
||||
}
|
||||
remove(ipOrCidr.trim());
|
||||
}
|
||||
|
||||
/**
|
||||
* The active blocks, expired entries pruned, ordered by expiry (indefinite first, then latest expiry). A
|
||||
* snapshot copy — safe to render without holding any lock.
|
||||
*/
|
||||
public List<Entry> list() {
|
||||
long now = nowSeconds.getAsLong();
|
||||
// Prune expired entries first (this may rewrite the file if a manual entry lapsed).
|
||||
List<String> expired = new ArrayList<>();
|
||||
for (Entry e : blocks.values()) {
|
||||
if (e.isExpired(now)) {
|
||||
expired.add(e.ip());
|
||||
}
|
||||
}
|
||||
expired.forEach(this::remove);
|
||||
List<Entry> active = new ArrayList<>(blocks.values());
|
||||
// Indefinite (until == 0) sorts first; otherwise newest expiry first.
|
||||
active.sort(Comparator.comparingLong((Entry e) -> e.indefinite() ? Long.MAX_VALUE : e.untilEpochSeconds())
|
||||
.reversed());
|
||||
return active;
|
||||
}
|
||||
|
||||
private void remove(String key) {
|
||||
Entry prev = blocks.remove(key);
|
||||
if (prev != null) {
|
||||
recordLapsed(prev);
|
||||
}
|
||||
if (isCidr(key)) {
|
||||
rebuildCidrIndex();
|
||||
}
|
||||
if (prev != null && prev.manual()) {
|
||||
persistManual();
|
||||
}
|
||||
}
|
||||
|
||||
private void rebuildCidrIndex() {
|
||||
cidrBlocks = CidrSet.of(blocks.keySet().stream().filter(IpBlocklist::isCidr).toList());
|
||||
}
|
||||
|
||||
// ---------- persistence (manual blocks only) --------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Seeds the in-memory set from the persisted manual blocks at startup. A missing/malformed file yields an
|
||||
* empty set (fail-soft — a corrupt blocklist must never block boot); already-expired persisted entries are
|
||||
* dropped.
|
||||
*/
|
||||
private void loadManual() {
|
||||
StoredBlocklist stored;
|
||||
try {
|
||||
stored = yaml.read(file, StoredBlocklist.class).orElse(null);
|
||||
} catch (IOException | RuntimeException e) {
|
||||
log.warn("could not read {} — starting with no persisted blocks: {}", file, e.toString());
|
||||
return;
|
||||
}
|
||||
if (stored == null || stored.getEntries() == null) {
|
||||
return;
|
||||
}
|
||||
long now = nowSeconds.getAsLong();
|
||||
for (StoredBlocklist.StoredEntry s : stored.getEntries()) {
|
||||
if (s == null || s.getIp() == null || s.getIp().isBlank()) {
|
||||
continue;
|
||||
}
|
||||
Entry e = new Entry(s.getIp().trim(), s.getReason() == null ? "" : s.getReason(),
|
||||
s.getUntilEpochSeconds(), true); // everything on disk is manual by construction
|
||||
if (!e.isExpired(now)) {
|
||||
blocks.put(e.ip(), e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Rewrites {@code blocklist.yml} with the current manual blocks (auto blocks are never persisted). */
|
||||
private void persistManual() {
|
||||
List<StoredBlocklist.StoredEntry> manual = new ArrayList<>();
|
||||
for (Entry e : blocks.values()) {
|
||||
if (e.manual()) {
|
||||
manual.add(new StoredBlocklist.StoredEntry(e.ip(), e.reason(), e.untilEpochSeconds()));
|
||||
}
|
||||
}
|
||||
try {
|
||||
yaml.write(file, new StoredBlocklist(manual));
|
||||
} catch (IOException | RuntimeException e) {
|
||||
// A persistence failure must not break the live in-memory block; log and carry on.
|
||||
log.warn("could not persist manual blocks to {}: {}", file, e.toString());
|
||||
}
|
||||
}
|
||||
|
||||
// ---------- helpers ---------------------------------------------------------------------------------
|
||||
|
||||
private static boolean isCidr(String key) {
|
||||
return key != null && key.indexOf('/') >= 0;
|
||||
}
|
||||
|
||||
/** Whether {@code ip} is a loopback literal ({@code 127.0.0.0/8} or {@code ::1}); DNS-free, fail-safe. */
|
||||
private static boolean isLoopback(String ip) {
|
||||
String text = stripZone(ip);
|
||||
if (text.isEmpty()) {
|
||||
return false;
|
||||
}
|
||||
try {
|
||||
return InetAddress.ofLiteral(text).isLoopbackAddress(); // literal only — never resolves DNS
|
||||
} catch (RuntimeException notALiteral) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private static String stripZone(String ip) {
|
||||
String text = ip.trim();
|
||||
int pct = text.indexOf('%');
|
||||
return pct < 0 ? text : text.substring(0, pct);
|
||||
}
|
||||
|
||||
/**
|
||||
* One active block. {@code untilEpochSeconds == 0} is an indefinite block; {@code manual} distinguishes a
|
||||
* persisted operator ban from an ephemeral auto-escalated one.
|
||||
*
|
||||
* @param ip the blocked IP or CIDR
|
||||
* @param reason a short human-readable reason
|
||||
* @param untilEpochSeconds the epoch-second the block lapses ({@code 0} ⇒ indefinite)
|
||||
* @param manual {@code true} for a persisted operator block, {@code false} for an auto block
|
||||
*/
|
||||
public record Entry(String ip, String reason, long untilEpochSeconds, boolean manual) {
|
||||
|
||||
/** Whether this block has lapsed at {@code nowEpochSeconds} (an indefinite block never expires). */
|
||||
public boolean isExpired(long nowEpochSeconds) {
|
||||
return untilEpochSeconds != 0 && untilEpochSeconds <= nowEpochSeconds;
|
||||
}
|
||||
|
||||
/** Whether this is an indefinite block (no expiry). */
|
||||
public boolean indefinite() {
|
||||
return untilEpochSeconds == 0;
|
||||
}
|
||||
}
|
||||
|
||||
// --- history of blocks that have ended ------------------------------------------------------------
|
||||
|
||||
/** How many ended blocks are kept for the operator screen. Bounded: this is a diagnostic, not an audit log. */
|
||||
private static final int HISTORY_LIMIT = 100;
|
||||
|
||||
/** Newest-first ring of blocks that have ended. Guarded by itself; only ever touched off the hot path. */
|
||||
private final java.util.Deque<Lapsed> history = new java.util.ArrayDeque<>();
|
||||
|
||||
/**
|
||||
* A block that is no longer in force — expired on its own, or lifted by an operator.
|
||||
*
|
||||
* @param ip the address or CIDR that was blocked
|
||||
* @param reason the reason recorded when it was applied
|
||||
* @param manual whether an operator applied it (as opposed to the limiter escalating)
|
||||
* @param endedAt epoch seconds when it stopped being enforced
|
||||
*/
|
||||
public record Lapsed(String ip, String reason, boolean manual, long endedAt) {
|
||||
}
|
||||
|
||||
/**
|
||||
* Remembers a block that has just ended, so it leaves a trace on the operator screen.
|
||||
*
|
||||
* <h2>Why this exists</h2>
|
||||
* An auto-block lasts fifteen minutes by default. An operator investigating "the site was slow around
|
||||
* three o'clock" arrives long after, sees an empty blocklist, and has no way to tell whether the guard
|
||||
* acted at all — the evidence deleted itself at the exact rate that makes it hardest to catch. The
|
||||
* rejection counter says a rejection happened; only this says <b>who</b> and <b>why</b>.
|
||||
*
|
||||
* <p><b>In memory, bounded, per node, and lost on restart</b> — deliberately. Persisting it would turn a
|
||||
* flood into unbounded disk writes at precisely the moment the guard is trying to be cheap, and would
|
||||
* store attacker-supplied addresses indefinitely. This is a diagnostic that answers "what happened
|
||||
* recently", not an audit trail; the {@code runway.protect} log is where a durable record lives.
|
||||
*/
|
||||
private void recordLapsed(Entry ended) {
|
||||
synchronized (history) {
|
||||
history.addFirst(new Lapsed(ended.ip(), ended.reason(), ended.manual(), nowSeconds.getAsLong()));
|
||||
while (history.size() > HISTORY_LIMIT) {
|
||||
history.removeLast();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Blocks that have ended since this node started, newest first (at most {@value #HISTORY_LIMIT}).
|
||||
*
|
||||
* <p>Call {@link #list()} first if you want the history current: expiry is lazy, so a block that has run
|
||||
* out is recorded as ended at the moment something looks, not at the moment its timer ran down.
|
||||
*/
|
||||
public List<Lapsed> recentlyEnded() {
|
||||
synchronized (history) {
|
||||
return List.copyOf(history);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
package mx.quest.protection;
|
||||
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import mx.quest.runway.security.LoginFormGuard;
|
||||
import mx.quest.runway.security.LoginFormVerdict;
|
||||
import mx.quest.runway.security.ProtectionScope;
|
||||
import mx.quest.runway.web.ClientIp;
|
||||
|
||||
/**
|
||||
* The plugin's {@code @Primary} {@link LoginFormGuard} — the request-aware login deterrent that arms the kernel's
|
||||
* form-guard seam with two policy checks, in order, over the scope's resolved {@link ProtectionSettings}:
|
||||
*
|
||||
* <ol>
|
||||
* <li><b>Honeypot.</b> When enabled, a non-blank {@link LoginFormGuard#HONEYPOT_FIELD} trap field is a
|
||||
* form-filling bot — rejected with {@link LoginFormVerdict.Reason#HONEYPOT} (which the
|
||||
* {@code LoginProtectionFilter} maps to the generic {@code ?error} flag, so the bot cannot tell the trap
|
||||
* tripped).</li>
|
||||
* <li><b>CAPTCHA.</b> When the scope's {@link ProtectionSettings.Captcha} is
|
||||
* {@link ProtectionSettings.Captcha#active() active} (enabled with both keys present), the provider's token
|
||||
* — the {@link CaptchaVerifier#tokenParam(String) per-provider request parameter} — is verified server-side
|
||||
* via {@link CaptchaVerifier}. A missing or provider-rejected token is rejected with
|
||||
* {@link LoginFormVerdict.Reason#CAPTCHA} (mapped to a distinguishable {@code ?captcha} flag, so a
|
||||
* legitimate user who fails the challenge sees a specific message). The challenge runs on <em>every</em>
|
||||
* login POST while active — the operator opts in per scope; the honeypot and per-IP lockout still apply
|
||||
* alongside it.</li>
|
||||
* </ol>
|
||||
*
|
||||
* <p>Registered as {@code @Primary} in {@link ProtectionConfig}, it wins by-type injection over the kernel's
|
||||
* {@link mx.quest.runway.security.PermissiveLoginFormGuard} default. The scope's config is resolved through
|
||||
* {@link ProtectionConfigStore} (the app store for an {@code APPLICATION} scope, the per-site store for a
|
||||
* {@code TENANT} scope); the store decrypts the captcha {@code secretKey} it hands back, so the verifier receives
|
||||
* plaintext and the secret never leaves the server.
|
||||
*
|
||||
* <p><b>Trusted-device skip (login form only).</b> When a <b>login</b> request carries a valid trusted-device
|
||||
* cookie for this scope ({@link TrustedDeviceService#isTrusted}), the CAPTCHA check is skipped — the "remember this
|
||||
* device" opt-in that lets a device which already logged in successfully avoid the challenge for a while. The skip
|
||||
* is scoped to the login paths only: the password-recovery REQUEST form (also guarded here) keeps its CAPTCHA even
|
||||
* for a trusted device, so it stays a full reset-flood deterrent. The honeypot still runs on both (a bot filling
|
||||
* the trap is dropped regardless), and the skip only ever removes the CAPTCHA, never authentication or the per-IP
|
||||
* lockout.
|
||||
*
|
||||
* <p><b>Fail-safe.</b> {@link ProtectionConfigStore#resolve} never throws (it degrades to defaults), the honeypot
|
||||
* check is a pure string test, and {@link CaptchaVerifier} <em>fails open</em> on a provider transport error — so
|
||||
* a store fault, a misconfiguration, or a provider outage can never lock out a legitimate user. Only a
|
||||
* genuinely-missing or genuinely-rejected CAPTCHA token blocks a login while the challenge is active.
|
||||
*/
|
||||
public final class LoginFormPolicyGuard implements LoginFormGuard {
|
||||
|
||||
private final ProtectionConfigStore configStore;
|
||||
private final CaptchaVerifier captchaVerifier;
|
||||
private final TrustedDeviceService trustedDeviceService;
|
||||
|
||||
public LoginFormPolicyGuard(ProtectionConfigStore configStore, CaptchaVerifier captchaVerifier,
|
||||
TrustedDeviceService trustedDeviceService) {
|
||||
this.configStore = configStore;
|
||||
this.captchaVerifier = captchaVerifier;
|
||||
this.trustedDeviceService = trustedDeviceService;
|
||||
}
|
||||
|
||||
@Override
|
||||
public LoginFormVerdict check(HttpServletRequest request, ProtectionScope scope) {
|
||||
ProtectionSettings settings = configStore.resolve(scope);
|
||||
|
||||
if (settings.honeypotEnabled()) {
|
||||
String trap = request.getParameter(HONEYPOT_FIELD);
|
||||
if (trap != null && !trap.isBlank()) {
|
||||
return LoginFormVerdict.reject(LoginFormVerdict.Reason.HONEYPOT);
|
||||
}
|
||||
}
|
||||
|
||||
ProtectionSettings.Captcha captcha = settings.captcha();
|
||||
// A trusted device (one that logged in successfully and opted in) skips the CAPTCHA — but ONLY on the login
|
||||
// form, and nothing else. The forgot-password form always challenges (its CAPTCHA deters reset-flooding).
|
||||
if (captcha.active() && !(isLoginForm(request) && trustedDeviceService.isTrusted(request, scope))) {
|
||||
String token = request.getParameter(CaptchaVerifier.tokenParam(captcha.provider()));
|
||||
if (!captchaVerifier.verify(captcha, token, ClientIp.of(request))) {
|
||||
return LoginFormVerdict.reject(LoginFormVerdict.Reason.CAPTCHA);
|
||||
}
|
||||
}
|
||||
|
||||
return LoginFormVerdict.ok();
|
||||
}
|
||||
|
||||
/** Whether this is a login POST (not a password-recovery request) — the only place the trusted skip applies. */
|
||||
private static boolean isLoginForm(HttpServletRequest request) {
|
||||
String path = routedPath(request);
|
||||
return "/app/login".equals(path) || "/login".equals(path);
|
||||
}
|
||||
|
||||
/**
|
||||
* The decoded path the dispatcher routes on (servlet path + path info), so {@code /app/%6Cogin} is the login path
|
||||
* as Spring Security and MVC see it. Computed here rather than through a kernel helper so this plugin keeps
|
||||
* loading on an older kernel during a rollback.
|
||||
*/
|
||||
static String routedPath(HttpServletRequest request) {
|
||||
String servletPath = request.getServletPath();
|
||||
String pathInfo = request.getPathInfo();
|
||||
String path = (servletPath == null ? "" : servletPath) + (pathInfo == null ? "" : pathInfo);
|
||||
return path.isEmpty() ? String.valueOf(request.getRequestURI()) : path;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,227 @@
|
||||
package mx.quest.protection;
|
||||
|
||||
import mx.quest.runway.console.AssetVersion;
|
||||
import mx.quest.runway.crypto.SecretCipher;
|
||||
import mx.quest.runway.protect.EdgeGuard;
|
||||
import mx.quest.runway.security.LoginAttemptGate;
|
||||
import mx.quest.runway.security.LoginFormGuard;
|
||||
import mx.quest.runway.site.SiteResolver;
|
||||
import mx.quest.runway.spi.service.RequestContext;
|
||||
import mx.quest.runway.storage.StorageLayout;
|
||||
import mx.quest.runway.storage.YamlStore;
|
||||
import mx.quest.runway.web.CidrSet;
|
||||
import org.springframework.beans.factory.ObjectProvider;
|
||||
import org.springframework.beans.factory.annotation.Qualifier;
|
||||
import org.springframework.boot.context.properties.EnableConfigurationProperties;
|
||||
import org.springframework.context.MessageSource;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.context.annotation.Primary;
|
||||
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
|
||||
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
|
||||
|
||||
/**
|
||||
* The plugin's {@code mainClass} — registered into the kernel context by the plugin loader before refresh, so
|
||||
* its {@code @Primary} beans <b>win by-type injection</b> over the kernel's permissive defaults and arm the
|
||||
* security floor: {@code EdgeRejectFilter} now enforces the rate limit; {@code LoginProtectionFilter} now
|
||||
* enforces the per-IP lockout ({@link LoginAttemptGate}) <b>and</b> the request-aware honeypot/CAPTCHA form
|
||||
* guard ({@link LoginFormGuard}). It declares itself essential in {@code plugin.yml}; the kernel honors that only
|
||||
* because the id {@code protection} is on the security-floor allowlist.
|
||||
*
|
||||
* <p>It also registers a {@link CaptchaLoginViewContributor} interceptor (via the {@link WebMvcConfigurer} below)
|
||||
* that feeds the kernel's generic login-view captcha slot the public site key + provider flags when a scope's
|
||||
* captcha is active — so the login page renders the widget without any provider knowledge in the kernel.
|
||||
*
|
||||
* <p>The {@link ProtectionConfigStore} it wires reads app-scope thresholds from {@link ProtectionProperties} and
|
||||
* per-site config from {@code sites/<id>/plugins/protection.yml} (encrypting the captcha secret via the kernel's
|
||||
* {@link SecretCipher}); the login gate reads its thresholds from that store on every check, so config changes
|
||||
* apply without a restart.
|
||||
*/
|
||||
@Configuration(proxyBeanMethods = false)
|
||||
@EnableConfigurationProperties(ProtectionProperties.class)
|
||||
public class ProtectionConfig {
|
||||
|
||||
/**
|
||||
* The mutable IP blocklist (manual bans persisted to {@code external/blocklist.yml}; auto bans in-memory only).
|
||||
* Its allowlist is the configured trusted CIDRs plus loopback (always) — those are never blockable. Consulted
|
||||
* on every request by the edge guard and escalated into by the rate limiter; edited by the {@code /__app/dos}
|
||||
* screen.
|
||||
*/
|
||||
@Bean
|
||||
public IpBlocklist protectionIpBlocklist(ProtectionProperties properties, StorageLayout layout,
|
||||
YamlStore yamlStore) {
|
||||
return new IpBlocklist(layout, yamlStore, CidrSet.of(properties.getAllowlist()));
|
||||
}
|
||||
|
||||
/**
|
||||
* The per-IP token-bucket rate limiter with auto-escalation into the {@link IpBlocklist}. Exposed as its own
|
||||
* bean (not created inline in the guard) so the {@code /__app/dos} screen can read its {@code topOffenders}.
|
||||
*/
|
||||
@Bean
|
||||
public TokenBucketRateLimiter protectionRateLimiter(ProtectionProperties properties, IpBlocklist blocklist) {
|
||||
ProtectionProperties.RateLimit rateLimit = properties.getRateLimit();
|
||||
ProtectionProperties.AutoBlock ab = rateLimit.getAutoBlock();
|
||||
return new TokenBucketRateLimiter(
|
||||
rateLimit.getCapacity(), rateLimit.getRefillPerSecond(), 100_000, System::nanoTime,
|
||||
blocklist,
|
||||
new TokenBucketRateLimiter.AutoBlock(ab.isEnabled(), ab.getBreachThreshold(), ab.getWindowSeconds(),
|
||||
ab.getBlockSeconds()),
|
||||
System::currentTimeMillis);
|
||||
}
|
||||
|
||||
@Bean
|
||||
@Primary
|
||||
public EdgeGuard protectionEdgeGuard(ProtectionProperties properties, IpBlocklist blocklist,
|
||||
TokenBucketRateLimiter limiter) {
|
||||
return new RateLimitEdgeGuard(CidrSet.of(properties.getAllowlist()), blocklist, limiter);
|
||||
}
|
||||
|
||||
/**
|
||||
* The per-scope protection config engine (app-level {@link ProtectionProperties} + per-site
|
||||
* {@code protection.yml}). Injected by the honeypot guard and the login gate; also the store the
|
||||
* dedicated Protection screens edit.
|
||||
*/
|
||||
@Bean
|
||||
public ProtectionConfigStore protectionConfigStore(ProtectionProperties properties, StorageLayout layout,
|
||||
YamlStore yamlStore, SecretCipher secretCipher) {
|
||||
return new ProtectionConfigStore(properties, layout, yamlStore, secretCipher);
|
||||
}
|
||||
|
||||
@Bean
|
||||
@Primary
|
||||
public LoginAttemptGate protectionLoginGate(ProtectionConfigStore configStore) {
|
||||
// Thresholds come from the app-scope settings, read fresh on each check (config-driven, no restart needed).
|
||||
return new SlidingWindowLoginGate(configStore::appSettings, System::currentTimeMillis);
|
||||
}
|
||||
|
||||
/** Verifies a CAPTCHA token server-side against the provider's {@code siteverify} endpoint (fail-open on outage). */
|
||||
@Bean
|
||||
public CaptchaVerifier protectionCaptchaVerifier() {
|
||||
return new CaptchaVerifier();
|
||||
}
|
||||
|
||||
/**
|
||||
* Allowlists the CAPTCHA providers' domains in the kernel CSP (collected by type via {@code CspHostContributor}),
|
||||
* so a challenge's script/iframe/verification calls are permitted and a strict enforce-mode CSP can coexist
|
||||
* with a configured CAPTCHA. Kernel stays provider-agnostic.
|
||||
*/
|
||||
@Bean
|
||||
public mx.quest.runway.web.CspHostContributor protectionCaptchaCspContributor() {
|
||||
return new CaptchaCspContributor();
|
||||
}
|
||||
|
||||
/**
|
||||
* The reusable site-form CAPTCHA seam ({@link mx.quest.runway.spi.CaptchaService}), armed from each site's own
|
||||
* per-site CAPTCHA settings. {@code @Primary} so it wins by-type injection over the kernel's permissive
|
||||
* {@code NoCaptchaService} default — letting the contact form (and any plugin/page form) render + verify a
|
||||
* challenge exactly when the tenant has configured one, with no coupling to this plugin.
|
||||
*/
|
||||
@Bean
|
||||
@Primary
|
||||
public CaptchaWidgetService protectionCaptchaWidgetService(ProtectionConfigStore configStore,
|
||||
CaptchaVerifier captchaVerifier,
|
||||
ObjectProvider<AssetVersion> assetVersion) {
|
||||
// The kernel's asset token, so the widget's /__assets/captcha-v3.js reference is versioned like the kernel's
|
||||
// (absent only in a partial context, where the reference stays unversioned and is served no-cache).
|
||||
return new CaptchaWidgetService(configStore, captchaVerifier, assetVersion.getIfAvailable());
|
||||
}
|
||||
|
||||
/**
|
||||
* The "remember this device" policy — the {@code @Primary} {@link mx.quest.runway.security.TrustedDeviceIssuer}
|
||||
* that mints a signed trusted-device cookie on a successful login (opt-in) and the matching trust check the
|
||||
* login form guard + view contributor use to skip the CAPTCHA on that device. App-level feature flag; the
|
||||
* cookie is AES-GCM sealed with the kernel {@link SecretCipher} and scoped per realm/site. Wins by-type
|
||||
* injection over the kernel's no-op default; failure degrades safely to "CAPTCHA always shown".
|
||||
*/
|
||||
@Bean
|
||||
@Primary
|
||||
public TrustedDeviceService protectionTrustedDeviceService(ProtectionProperties properties,
|
||||
ProtectionConfigStore configStore,
|
||||
SecretCipher secretCipher) {
|
||||
return new TrustedDeviceService(properties, configStore, secretCipher);
|
||||
}
|
||||
|
||||
@Bean
|
||||
@Primary
|
||||
public LoginFormGuard protectionLoginFormGuard(ProtectionConfigStore configStore, CaptchaVerifier captchaVerifier,
|
||||
TrustedDeviceService trustedDeviceService) {
|
||||
return new LoginFormPolicyGuard(configStore, captchaVerifier, trustedDeviceService);
|
||||
}
|
||||
|
||||
/**
|
||||
* The app-realm rescue seam ({@link mx.quest.runway.spi.SiteLoginProtectionControl}) that lets an operator
|
||||
* switch a locked-out site's login CAPTCHA off from the Sites screen. {@code @Primary} so it wins by-type
|
||||
* injection over the kernel's no-op default; reads and rewrites the per-site config over the store above.
|
||||
*/
|
||||
@Bean
|
||||
@Primary
|
||||
public mx.quest.runway.spi.SiteLoginProtectionControl protectionSiteLoginControl(ProtectionConfigStore configStore) {
|
||||
return new ProtectionSiteLoginControl(configStore);
|
||||
}
|
||||
|
||||
/**
|
||||
* The login-view captcha contributor, registered as a {@link WebMvcConfigurer} so the kernel's MVC picks it up
|
||||
* from this plugin {@code @Configuration} (collected by type, like {@code PluginStaticResourceConfig}). It maps
|
||||
* the interceptor only to the two login-view GETs; every other request is untouched.
|
||||
*/
|
||||
@Bean
|
||||
public WebMvcConfigurer protectionCaptchaViewConfigurer(ProtectionConfigStore configStore,
|
||||
SiteResolver siteResolver,
|
||||
TrustedDeviceService trustedDeviceService) {
|
||||
CaptchaLoginViewContributor contributor =
|
||||
new CaptchaLoginViewContributor(configStore, siteResolver, trustedDeviceService);
|
||||
return new WebMvcConfigurer() {
|
||||
@Override
|
||||
public void addInterceptors(InterceptorRegistry registry) {
|
||||
// Both realms' login pages AND their password-recovery REQUEST pages (so a configured challenge
|
||||
// also renders on the forgot-password form).
|
||||
registry.addInterceptor(contributor)
|
||||
.addPathPatterns("/app/login", "/login", "/app/forgot-password", "/forgot-password");
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
// --- Dedicated custom Protection screens -----------------------------------------------
|
||||
// Full operator screens rendered inside the kernel op-layout shell: each screen controller carries the SPI's
|
||||
// @ConsoleScreen, so the kernel's ConsoleScreenAdvice fills the shell model (SPI 0.6.0; the plugin's own
|
||||
// ProtectionShellAdvice is gone). Registered as explicit @Beans (plugins wire by hand, never by component scan);
|
||||
// Spring MVC still detects the @Controller annotations on the returned classes and maps them like kernel ones.
|
||||
|
||||
/**
|
||||
* The save handler for the app-scope login policy — the POST behind the login-protection <b>panel</b> that
|
||||
* renders on the plugin's own settings page ({@code /__app/plugins/protection/settings}); edits the app scope.
|
||||
*/
|
||||
@Bean
|
||||
public AppProtectionController appProtectionController(ProtectionConfigStore configStore,
|
||||
@Qualifier("operatorAwareMessageSource") MessageSource messages) {
|
||||
return new AppProtectionController(configStore, messages);
|
||||
}
|
||||
|
||||
/**
|
||||
* The read-model the app login-protection panel ({@code templates/admin-app.html}) binds to via
|
||||
* {@code ${@appProtectionPanel.*}} — the kernel-owned plugin-settings page does not populate the plugin's model,
|
||||
* so the panel pulls the live app-scope settings through this bean. The bean name is the SpEL reference.
|
||||
*/
|
||||
@Bean
|
||||
public AppProtectionPanel appProtectionPanel(ProtectionConfigStore configStore) {
|
||||
return new AppProtectionPanel(configStore);
|
||||
}
|
||||
|
||||
/** The tenant-realm Protection screen ({@code /__admin/protection}); edits the bound site's per-site policy. */
|
||||
@Bean
|
||||
public SiteProtectionController siteProtectionController(RequestContext requestContext,
|
||||
ProtectionConfigStore configStore,
|
||||
@Qualifier("operatorAwareMessageSource") MessageSource messages) {
|
||||
return new SiteProtectionController(requestContext, configStore, messages);
|
||||
}
|
||||
|
||||
/**
|
||||
* The application-realm <b>DoS activity</b> screen ({@code /__app/dos}): live rate-limit offenders + the
|
||||
* mutable blocklist (block/unblock). App-level platform concern — never a per-tenant surface.
|
||||
*/
|
||||
@Bean
|
||||
public DosController dosController(TokenBucketRateLimiter limiter, IpBlocklist blocklist,
|
||||
@Qualifier("operatorAwareMessageSource") MessageSource messages) {
|
||||
return new DosController(limiter, blocklist, messages);
|
||||
}
|
||||
}
|
||||
+302
@@ -0,0 +1,302 @@
|
||||
package mx.quest.protection;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Path;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
import mx.quest.runway.crypto.SecretCipher;
|
||||
import mx.quest.runway.security.ProtectionScope;
|
||||
import mx.quest.runway.storage.StorageLayout;
|
||||
import mx.quest.runway.storage.YamlStore;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
/**
|
||||
* Resolves and persists a {@link ProtectionScope}'s {@link ProtectionSettings} — the plugin's per-scope config
|
||||
* engine backing the {@link LoginFormPolicyGuard} and the {@link SlidingWindowLoginGate} lockout, and the
|
||||
* dedicated app-level and per-site protection screens.
|
||||
*
|
||||
* <p>Two scopes, two backing stores:
|
||||
* <ul>
|
||||
* <li><b>Application</b> — held in a live in-memory snapshot ({@link #appSnapshot}), <b>seeded at construction</b>
|
||||
* from the plugin's own file {@code external/plugin-settings/protection-app.yml} if present (a previous save
|
||||
* is authoritative), else from the app-level {@link ProtectionProperties}
|
||||
* ({@code runway.plugin.protection.login.*}, so a fresh install honors the operator's config file /
|
||||
* plugin-settings). {@link #saveApp} replaces the snapshot <b>and</b> persists the file, so a change applies
|
||||
* <b>immediately</b>: the login gate and form guard read {@link #appSettings()} fresh on every check — no
|
||||
* restart. The captcha secret is stored {@code ENC(...)} in that file.</li>
|
||||
* <li><b>Per-site</b> — the tenant-owned file {@code sites/<id>/plugins/protection.yml}, so this
|
||||
* plugin-GENERATED tenant data travels in the site's backup (the self-containment rule). Read via
|
||||
* {@link YamlStore}; written by {@link #savePerSite}, which <b>encrypts the captcha secret</b>
|
||||
* ({@code ENC(...)}) with {@link SecretCipher} before it touches disk.</li>
|
||||
* </ul>
|
||||
*
|
||||
* <p><b>Fail-safe.</b> A missing file, an unresolvable site, a decryption/IO/parse fault — any of these degrades
|
||||
* to {@link ProtectionSettings#defaults()} and logs, never throwing out of {@link #resolve}: a store fault must
|
||||
* never lock every user out or 500 a login. The stored captcha secret is decrypted into the returned settings so
|
||||
* the {@link LoginFormPolicyGuard} receives plaintext at verification time and the secret never leaves the server.
|
||||
*/
|
||||
public class ProtectionConfigStore {
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(ProtectionConfigStore.class);
|
||||
|
||||
/** The plugin-owned app-scope config filename, alongside the per-plugin settings (survives upgrade/uninstall). */
|
||||
static final String APP_CONFIG_FILE = "protection-app.yml";
|
||||
|
||||
private final ProtectionProperties appProperties;
|
||||
private final StorageLayout layout;
|
||||
private final YamlStore yaml;
|
||||
private final SecretCipher cipher;
|
||||
|
||||
/**
|
||||
* The live app-scope settings. Seeded once at construction (file if present, else properties) and swapped
|
||||
* atomically by {@link #saveApp}, so {@link #appSettings()} — called fresh by the gate/guard on every check —
|
||||
* reflects a save with no restart. Holds the decrypted (plaintext-secret) form the verifier consumes.
|
||||
*/
|
||||
private final AtomicReference<ProtectionSettings> appSnapshot = new AtomicReference<>();
|
||||
|
||||
public ProtectionConfigStore(ProtectionProperties appProperties, StorageLayout layout, YamlStore yaml,
|
||||
SecretCipher cipher) {
|
||||
this.appProperties = appProperties;
|
||||
this.layout = layout;
|
||||
this.yaml = yaml;
|
||||
this.cipher = cipher;
|
||||
this.appSnapshot.set(seedAppSettings());
|
||||
}
|
||||
|
||||
/**
|
||||
* The effective settings governing {@code scope}: the live app snapshot for an {@code APPLICATION} scope,
|
||||
* the per-site file for a resolved {@code TENANT} scope, else {@link ProtectionSettings#defaults()}. Never
|
||||
* throws — every fault degrades to defaults (fail-safe).
|
||||
*/
|
||||
public ProtectionSettings resolve(ProtectionScope scope) {
|
||||
if (scope == null) {
|
||||
return ProtectionSettings.defaults();
|
||||
}
|
||||
return switch (scope.realm()) {
|
||||
case APPLICATION -> appSettings();
|
||||
case TENANT -> scope.resolvedSiteId().map(this::perSiteSettings).orElseGet(ProtectionSettings::defaults);
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* The live app-realm settings (the current in-memory snapshot, with the captcha secret as plaintext). Read
|
||||
* fresh by the login gate / form guard on every check, and by the app screen to pre-fill its form — so a
|
||||
* {@link #saveApp} takes effect on the very next login attempt without a restart. Never {@code null}.
|
||||
*/
|
||||
public ProtectionSettings appSettings() {
|
||||
ProtectionSettings current = appSnapshot.get();
|
||||
return current != null ? current : ProtectionSettings.defaults();
|
||||
}
|
||||
|
||||
/**
|
||||
* Replaces the app-scope settings and persists them to {@code external/plugin-settings/protection-app.yml},
|
||||
* encrypting the captcha secret first. The in-memory snapshot is swapped so the change applies immediately;
|
||||
* a blank secret is stored blank (no {@code ENC(...)}); a non-blank one requires an available
|
||||
* {@link SecretCipher} (else the save fails loudly rather than persisting a secret in the clear).
|
||||
*
|
||||
* @throws IOException if the file cannot be written
|
||||
* @throws IllegalStateException if a non-blank captcha secret is submitted but no encryption key is configured
|
||||
*/
|
||||
public void saveApp(ProtectionSettings settings) throws IOException {
|
||||
StoredProtection stored = toStored(settings);
|
||||
yaml.write(appConfigFile(), stored);
|
||||
// Swap the live snapshot to the freshly-saved settings (secret back as plaintext for the verifier).
|
||||
appSnapshot.set(stored.toSettings(this::decryptQuietly));
|
||||
log.info("saved app protection config ({} captcha secret)",
|
||||
stored.getCaptcha().getSecretKey().isBlank() ? "no" : "encrypted");
|
||||
}
|
||||
|
||||
/**
|
||||
* The per-site settings from {@code sites/<id>/plugins/protection.yml}, or {@link ProtectionSettings#defaults()}
|
||||
* when the file is absent or unreadable. The stored captcha secret ({@code ENC(...)}) is decrypted into the
|
||||
* returned record.
|
||||
*/
|
||||
public ProtectionSettings perSiteSettings(String siteId) {
|
||||
StoredSiteProtection stored = readPerSite(siteId).orElse(null);
|
||||
if (stored == null) {
|
||||
return ProtectionSettings.defaults();
|
||||
}
|
||||
return stored.toSettings(this::decryptQuietly);
|
||||
}
|
||||
|
||||
/**
|
||||
* Writes {@code settings} for a site, encrypting the captcha secret before it is persisted. A blank secret is
|
||||
* stored blank (no {@code ENC(...)}); a non-blank one requires an available {@link SecretCipher} (else the
|
||||
* save fails loudly rather than persisting a secret in the clear).
|
||||
*
|
||||
* @throws IOException if the file cannot be written
|
||||
* @throws IllegalStateException if a non-blank captcha secret is submitted but no encryption key is configured
|
||||
*/
|
||||
public void savePerSite(String siteId, ProtectionSettings settings) throws IOException {
|
||||
StoredSiteProtection stored = toStoredSite(settings);
|
||||
Path file = layout.sitePluginConfigFile(siteId, "protection"); // traversal-safe
|
||||
yaml.write(file, stored);
|
||||
log.info("saved per-site protection config for site '{}' ({} captcha secret)",
|
||||
siteId, stored.getCaptcha().getSecretKey().isBlank() ? "no" : "encrypted");
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether a site's login CAPTCHA is switched on — the stored enable flag (the keys may still be invalid). Reads
|
||||
* the raw stored file, so it needs no encryption key. Drives the app Sites screen's rescue affordance.
|
||||
*/
|
||||
public boolean siteCaptchaEnabled(String siteId) {
|
||||
return readPerSite(siteId).map(s -> s.getCaptcha() != null && s.getCaptcha().isEnabled()).orElse(false);
|
||||
}
|
||||
|
||||
/**
|
||||
* Force a site's login CAPTCHA off — an application-operator rescue for a tenant locked out of its console by a
|
||||
* broken CAPTCHA. Preserves the stored provider and keys (the secret is carried through in its {@code ENC(...)}
|
||||
* form, so no encryption key is required) and every other setting (the honeypot); a no-op when the site has no
|
||||
* protection config or its CAPTCHA is already off. Applies without a restart (the per-site config is read fresh
|
||||
* on the next login).
|
||||
*
|
||||
* @return {@code true} if a change was written, {@code false} if there was nothing to disable
|
||||
* @throws IOException if the file cannot be rewritten
|
||||
*/
|
||||
public boolean disableSiteCaptcha(String siteId) throws IOException {
|
||||
StoredSiteProtection stored = readPerSite(siteId).orElse(null);
|
||||
if (stored == null || stored.getCaptcha() == null || !stored.getCaptcha().isEnabled()) {
|
||||
return false;
|
||||
}
|
||||
StoredProtection.StoredCaptcha c = stored.getCaptcha();
|
||||
// Rebuild with enabled=false, carrying the ENC(...) secret through untouched — no decrypt/encrypt round-trip,
|
||||
// so a rescue works even when no encryption key is configured.
|
||||
stored.setCaptcha(new StoredProtection.StoredCaptcha(false, c.getProvider(), c.getSiteKey(),
|
||||
c.getSecretKey(), c.getScoreThreshold()));
|
||||
yaml.write(layout.sitePluginConfigFile(siteId, "protection"), stored); // traversal-safe
|
||||
log.info("app operator disabled login CAPTCHA for site '{}' (keys preserved)", siteId);
|
||||
return true;
|
||||
}
|
||||
|
||||
/** Whether the captcha secret can be stored (an encryption key is configured); false ⇒ the screen must warn. */
|
||||
public boolean secretStorable() {
|
||||
return cipher.isAvailable();
|
||||
}
|
||||
|
||||
/** The <b>app</b> on-disk shape (honeypot + per-IP lockout + captcha) — the app scope owns the lockout floor. */
|
||||
private StoredProtection toStored(ProtectionSettings settings) {
|
||||
return new StoredProtection(settings.honeypotEnabled(), settings.maxAttempts(),
|
||||
settings.windowSeconds(), settings.lockoutSeconds(), toStoredCaptcha(settings.captcha()));
|
||||
}
|
||||
|
||||
/**
|
||||
* The <b>per-site</b> on-disk shape — honeypot + captcha ONLY. The per-IP lockout is an application-scope
|
||||
* platform floor ({@link SlidingWindowLoginGate} reads the app settings), so a per-site value would never take
|
||||
* effect; it is deliberately not stored per-site (its screen no longer offers it).
|
||||
*/
|
||||
private StoredSiteProtection toStoredSite(ProtectionSettings settings) {
|
||||
return new StoredSiteProtection(settings.honeypotEnabled(), toStoredCaptcha(settings.captcha()));
|
||||
}
|
||||
|
||||
/**
|
||||
* Builds the on-disk captcha section, encrypting the secret (blank stays blank; a non-blank secret without an
|
||||
* available cipher fails loudly so a secret is never persisted in the clear). Shared by the app + per-site saves.
|
||||
*/
|
||||
private StoredProtection.StoredCaptcha toStoredCaptcha(ProtectionSettings.Captcha c) {
|
||||
String storedSecret = "";
|
||||
if (c.secretKey() != null && !c.secretKey().isBlank()) {
|
||||
if (!cipher.isAvailable()) {
|
||||
throw new IllegalStateException("cannot store a captcha secret: no encryption key is configured "
|
||||
+ "(runway.security.secret-key)");
|
||||
}
|
||||
storedSecret = cipher.encrypt(c.secretKey());
|
||||
}
|
||||
return new StoredProtection.StoredCaptcha(c.enabled(), c.provider(), c.siteKey(), storedSecret,
|
||||
c.scoreThreshold());
|
||||
}
|
||||
|
||||
/**
|
||||
* The startup seed for the app snapshot: the saved app-config file if present (a prior {@link #saveApp} is
|
||||
* authoritative), else the settings derived from {@link ProtectionProperties}. Never throws — a broken file
|
||||
* or a derivation fault degrades to the properties/defaults, so the plugin always boots with a working floor.
|
||||
*/
|
||||
private ProtectionSettings seedAppSettings() {
|
||||
try {
|
||||
Optional<StoredProtection> saved = yaml.read(appConfigFile(), StoredProtection.class);
|
||||
if (saved.isPresent()) {
|
||||
warnIfLoginPropertiesAreIgnored();
|
||||
return saved.get().toSettings(this::decryptQuietly);
|
||||
}
|
||||
} catch (IOException | RuntimeException e) {
|
||||
log.warn("could not read app protection config {} — seeding from properties: {}",
|
||||
APP_CONFIG_FILE, e.toString());
|
||||
}
|
||||
return appSettingsFromProperties();
|
||||
}
|
||||
|
||||
/**
|
||||
* The {@code runway.plugin.protection.login.*} properties only seed a fresh install: once the login-protection
|
||||
* panel has saved {@code protection-app.yml}, that file is what applies. Says so at startup when they are set
|
||||
* to anything but their defaults, so a value typed into {@code application.yml} is never silently ignored.
|
||||
*/
|
||||
private void warnIfLoginPropertiesAreIgnored() {
|
||||
try {
|
||||
if (!appSettingsFromProperties(appProperties).equals(appSettingsFromProperties(new ProtectionProperties()))) {
|
||||
log.warn("runway.plugin.protection.login.* is set, but {} (saved from the console's login-protection "
|
||||
+ "panel) applies: those properties only seed a fresh install. Change the values on the "
|
||||
+ "panel, or remove the properties.", APP_CONFIG_FILE);
|
||||
}
|
||||
} catch (RuntimeException e) {
|
||||
log.debug("could not compare the login properties with their defaults: {}", e.toString());
|
||||
}
|
||||
}
|
||||
|
||||
/** The app-scope settings derived from the bound {@link ProtectionProperties} (its captcha secret decrypted). */
|
||||
private ProtectionSettings appSettingsFromProperties() {
|
||||
return appSettingsFromProperties(appProperties);
|
||||
}
|
||||
|
||||
private ProtectionSettings appSettingsFromProperties(ProtectionProperties properties) {
|
||||
try {
|
||||
ProtectionProperties.Login login = properties.getLogin();
|
||||
ProtectionProperties.Captcha c = login.getCaptcha();
|
||||
// The app-level secret binds as its stored (possibly ENC(...)) string; decrypt it to the plaintext the
|
||||
// CaptchaVerifier uses. Decryption is null/plaintext-tolerant, so a hand-written plaintext key still works.
|
||||
String secret = decryptQuietly(c.getSecretKey());
|
||||
ProtectionSettings.Captcha captcha = new ProtectionSettings.Captcha(
|
||||
c.isEnabled(), c.getProvider(), c.getSiteKey(), secret, c.getScoreThreshold());
|
||||
return new ProtectionSettings(login.isHoneypotEnabled(), login.getMaxAttempts(),
|
||||
(int) login.getWindowSeconds(), (int) login.getLockoutSeconds(), captcha);
|
||||
} catch (RuntimeException e) {
|
||||
log.warn("could not derive app protection settings from properties — using defaults: {}", e.toString());
|
||||
return ProtectionSettings.defaults();
|
||||
}
|
||||
}
|
||||
|
||||
/** The plugin-owned app-scope config file, under the UI-owned settings dir (outside the install dir). */
|
||||
private Path appConfigFile() {
|
||||
return layout.pluginSettings().resolve(APP_CONFIG_FILE);
|
||||
}
|
||||
|
||||
private Optional<StoredSiteProtection> readPerSite(String siteId) {
|
||||
Path file;
|
||||
try {
|
||||
file = layout.sitePluginConfigFile(siteId, "protection"); // traversal-safe; throws on an unsafe id
|
||||
} catch (RuntimeException unsafeId) {
|
||||
log.warn("unsafe site id for protection config, using defaults: {}", unsafeId.toString());
|
||||
return Optional.empty();
|
||||
}
|
||||
try {
|
||||
return yaml.read(file, StoredSiteProtection.class);
|
||||
} catch (IOException | RuntimeException e) {
|
||||
// A hand-corrupted file must not 500 every login for the site — degrade to defaults and warn.
|
||||
log.warn("could not read per-site protection config {} — using defaults: {}", file, e.toString());
|
||||
return Optional.empty();
|
||||
}
|
||||
}
|
||||
|
||||
/** Decrypts a stored (possibly {@code ENC(...)}) value to plaintext; on any fault returns it unchanged. */
|
||||
private String decryptQuietly(String value) {
|
||||
if (value == null || value.isBlank()) {
|
||||
return "";
|
||||
}
|
||||
try {
|
||||
return cipher.decrypt(value);
|
||||
} catch (RuntimeException e) {
|
||||
log.warn("could not decrypt a stored protection secret — treating captcha as unconfigured: {}",
|
||||
e.toString());
|
||||
return "";
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
package mx.quest.protection;
|
||||
|
||||
import java.util.List;
|
||||
import org.springframework.ui.Model;
|
||||
|
||||
/**
|
||||
* Shared form logic for the two dedicated protection screens ({@link AppProtectionController} and
|
||||
* {@link SiteProtectionController}): it maps posted fields onto a {@link ProtectionSettings} (preserving the
|
||||
* stored captcha secret when the field is left blank) and populates the view model for the GET render (masking
|
||||
* the secret so it is never sent to the client). Keeping it in one place means the app and per-site screens can
|
||||
* never drift on the secret-preserve-on-blank rule.
|
||||
*/
|
||||
final class ProtectionForm {
|
||||
|
||||
/**
|
||||
* The captcha modes offered by the screens' provider select — the two Google reCAPTCHA modes
|
||||
* {@link CaptchaVerifier} supports: {@code recaptcha-v2} (visible checkbox) and {@code recaptcha-v3}
|
||||
* (invisible, score-based). Turnstile and hCaptcha were dropped in 0.4.0 (see {@link CaptchaCspContributor}).
|
||||
*/
|
||||
static final List<String> PROVIDERS = List.of("recaptcha-v2", "recaptcha-v3");
|
||||
|
||||
private ProtectionForm() {
|
||||
}
|
||||
|
||||
/**
|
||||
* Builds the new settings from the posted fields, layered over {@code current} so a <b>blank</b> secret field
|
||||
* <b>keeps</b> the currently-stored secret (only a non-blank value replaces it). Thresholds are passed through
|
||||
* as-is; {@link ProtectionSettings}'s canonical constructor floors any non-positive value to a sane default,
|
||||
* so a save can never persist a lock-everyone-out config. The provider is normalized to a known value.
|
||||
*
|
||||
* @param current the settings currently in force (its captcha secret is the fallback for a blank field)
|
||||
* @param honeypotEnabled the honeypot switch
|
||||
* @param maxAttempts failed logins in the window that trip the lockout (floored if {@code ≤ 0})
|
||||
* @param windowSeconds the sliding failure window (floored if {@code ≤ 0})
|
||||
* @param lockoutSeconds the lockout duration (floored if {@code ≤ 0})
|
||||
* @param captchaEnabled whether the CAPTCHA challenge is required
|
||||
* @param provider the reCAPTCHA mode (blank/unknown/legacy ⇒ recaptcha-v2)
|
||||
* @param siteKey the public site key (rendered into the widget)
|
||||
* @param secretKey the new secret, or blank to KEEP the stored one
|
||||
* @param scoreThreshold the reCAPTCHA v3 minimum score
|
||||
* @return the merged, normalized settings ready to persist
|
||||
*/
|
||||
static ProtectionSettings merge(ProtectionSettings current, boolean honeypotEnabled, int maxAttempts,
|
||||
int windowSeconds, int lockoutSeconds, boolean captchaEnabled, String provider,
|
||||
String siteKey, String secretKey, double scoreThreshold) {
|
||||
// Blank secret field => keep the existing stored secret (never overwrite a configured secret with blank).
|
||||
String resolvedSecret = (secretKey == null || secretKey.isBlank())
|
||||
? current.captcha().secretKey()
|
||||
: secretKey.strip();
|
||||
ProtectionSettings.Captcha captcha = new ProtectionSettings.Captcha(
|
||||
captchaEnabled, normalizeProvider(provider), trimToEmpty(siteKey), resolvedSecret, scoreThreshold);
|
||||
return new ProtectionSettings(honeypotEnabled, maxAttempts, windowSeconds, lockoutSeconds, captcha);
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds the view-model attributes the screen templates read. The captcha secret is exposed <b>only</b> as a
|
||||
* boolean {@code captchaSecretConfigured} — never the plaintext or the {@code ENC(...)} blob — so a secret is
|
||||
* never rendered into an input. {@code captchaSecretStorable} drives the "no encryption key" hint.
|
||||
*/
|
||||
static void populate(Model model, ProtectionSettings settings, boolean secretStorable) {
|
||||
model.addAttribute("settings", settings);
|
||||
model.addAttribute("providers", PROVIDERS);
|
||||
// Secret masking: the template shows "configured"/placeholder, and a blank submit keeps the stored value.
|
||||
model.addAttribute("captchaSecretConfigured",
|
||||
settings.captcha().secretKey() != null && !settings.captcha().secretKey().isBlank());
|
||||
model.addAttribute("captchaSecretStorable", secretStorable);
|
||||
}
|
||||
|
||||
private static String normalizeProvider(String provider) {
|
||||
if (provider == null) {
|
||||
return "recaptcha-v2";
|
||||
}
|
||||
String p = provider.strip().toLowerCase(java.util.Locale.ROOT);
|
||||
return PROVIDERS.contains(p) ? p : "recaptcha-v2";
|
||||
}
|
||||
|
||||
private static String trimToEmpty(String value) {
|
||||
return value == null ? "" : value.strip();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,263 @@
|
||||
package mx.quest.protection;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
|
||||
/**
|
||||
* The plugin's app-level settings, bound from {@code runway.plugin.protection.*} (the kernel loads
|
||||
* {@code external/plugin-settings/protection.yml} as a property source). These are <b>platform</b>
|
||||
* concerns (abuse thresholds, IP lists) — app-level, never per-tenant.
|
||||
*/
|
||||
@ConfigurationProperties("runway.plugin.protection")
|
||||
public class ProtectionProperties {
|
||||
|
||||
private RateLimit rateLimit = new RateLimit();
|
||||
private List<String> allowlist = new ArrayList<>();
|
||||
private Login login = new Login();
|
||||
private RememberDevice rememberDevice = new RememberDevice();
|
||||
|
||||
public RateLimit getRateLimit() {
|
||||
return rateLimit;
|
||||
}
|
||||
|
||||
public void setRateLimit(RateLimit rateLimit) {
|
||||
this.rateLimit = rateLimit;
|
||||
}
|
||||
|
||||
public List<String> getAllowlist() {
|
||||
return allowlist;
|
||||
}
|
||||
|
||||
public void setAllowlist(List<String> allowlist) {
|
||||
this.allowlist = allowlist;
|
||||
}
|
||||
|
||||
public Login getLogin() {
|
||||
return login;
|
||||
}
|
||||
|
||||
public void setLogin(Login login) {
|
||||
this.login = login;
|
||||
}
|
||||
|
||||
public RememberDevice getRememberDevice() {
|
||||
return rememberDevice;
|
||||
}
|
||||
|
||||
public void setRememberDevice(RememberDevice rememberDevice) {
|
||||
this.rememberDevice = rememberDevice;
|
||||
}
|
||||
|
||||
/**
|
||||
* Per-IP token-bucket settings: {@code capacity} (burst) refilled at {@code refillPerSecond}, plus the
|
||||
* {@link AutoBlock} escalation that turns a repeat throttler into a temporary blocklist entry.
|
||||
*/
|
||||
public static class RateLimit {
|
||||
private int capacity = 120;
|
||||
private double refillPerSecond = 2.0;
|
||||
private AutoBlock autoBlock = new AutoBlock();
|
||||
|
||||
public int getCapacity() {
|
||||
return capacity;
|
||||
}
|
||||
|
||||
public void setCapacity(int capacity) {
|
||||
this.capacity = capacity;
|
||||
}
|
||||
|
||||
public double getRefillPerSecond() {
|
||||
return refillPerSecond;
|
||||
}
|
||||
|
||||
public void setRefillPerSecond(double refillPerSecond) {
|
||||
this.refillPerSecond = refillPerSecond;
|
||||
}
|
||||
|
||||
public AutoBlock getAutoBlock() {
|
||||
return autoBlock;
|
||||
}
|
||||
|
||||
public void setAutoBlock(AutoBlock autoBlock) {
|
||||
this.autoBlock = autoBlock;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Auto-escalation of a repeat rate-limit offender into a temporary (auto) blocklist entry: an IP throttled
|
||||
* {@code breachThreshold} times within {@code windowSeconds} is auto-blocked for {@code blockSeconds}. Defaults
|
||||
* are 60 breaches / 60 s → 900 s block. An auto block is <b>never</b> persisted — it expires by its
|
||||
* own timer and is re-earned by a still-abusive IP after a restart.
|
||||
*/
|
||||
public static class AutoBlock {
|
||||
private boolean enabled = true;
|
||||
private int breachThreshold = 60;
|
||||
private long windowSeconds = 60;
|
||||
private long blockSeconds = 900;
|
||||
|
||||
public boolean isEnabled() {
|
||||
return enabled;
|
||||
}
|
||||
|
||||
public void setEnabled(boolean enabled) {
|
||||
this.enabled = enabled;
|
||||
}
|
||||
|
||||
public int getBreachThreshold() {
|
||||
return breachThreshold;
|
||||
}
|
||||
|
||||
public void setBreachThreshold(int breachThreshold) {
|
||||
this.breachThreshold = breachThreshold;
|
||||
}
|
||||
|
||||
public long getWindowSeconds() {
|
||||
return windowSeconds;
|
||||
}
|
||||
|
||||
public void setWindowSeconds(long windowSeconds) {
|
||||
this.windowSeconds = windowSeconds;
|
||||
}
|
||||
|
||||
public long getBlockSeconds() {
|
||||
return blockSeconds;
|
||||
}
|
||||
|
||||
public void setBlockSeconds(long blockSeconds) {
|
||||
this.blockSeconds = blockSeconds;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Brute-force lockout + form-deterrent settings for the <b>application</b> realm (the operator login). This is
|
||||
* the app-scope source of truth {@link ProtectionConfigStore} exposes as a {@link ProtectionSettings}; the
|
||||
* per-site equivalent lives in {@code sites/<id>/plugins/protection.yml}.
|
||||
*/
|
||||
public static class Login {
|
||||
private boolean honeypotEnabled = true;
|
||||
private int maxAttempts = ProtectionSettings.DEFAULT_MAX_ATTEMPTS;
|
||||
private long windowSeconds = ProtectionSettings.DEFAULT_WINDOW_SECONDS;
|
||||
private long lockoutSeconds = ProtectionSettings.DEFAULT_LOCKOUT_SECONDS;
|
||||
private Captcha captcha = new Captcha();
|
||||
|
||||
public boolean isHoneypotEnabled() {
|
||||
return honeypotEnabled;
|
||||
}
|
||||
|
||||
public void setHoneypotEnabled(boolean honeypotEnabled) {
|
||||
this.honeypotEnabled = honeypotEnabled;
|
||||
}
|
||||
|
||||
public int getMaxAttempts() {
|
||||
return maxAttempts;
|
||||
}
|
||||
|
||||
public void setMaxAttempts(int maxAttempts) {
|
||||
this.maxAttempts = maxAttempts;
|
||||
}
|
||||
|
||||
public long getWindowSeconds() {
|
||||
return windowSeconds;
|
||||
}
|
||||
|
||||
public void setWindowSeconds(long windowSeconds) {
|
||||
this.windowSeconds = windowSeconds;
|
||||
}
|
||||
|
||||
public long getLockoutSeconds() {
|
||||
return lockoutSeconds;
|
||||
}
|
||||
|
||||
public void setLockoutSeconds(long lockoutSeconds) {
|
||||
this.lockoutSeconds = lockoutSeconds;
|
||||
}
|
||||
|
||||
public Captcha getCaptcha() {
|
||||
return captcha;
|
||||
}
|
||||
|
||||
public void setCaptcha(Captcha captcha) {
|
||||
this.captcha = captcha;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* "Remember this device" — lets a device that has logged in successfully (solving the CAPTCHA once) skip the
|
||||
* login CAPTCHA for {@code days} days, via a signed, per-realm/per-site, host-only cookie. Platform-security
|
||||
* floor concern, so it is app-level (never per-tenant): one toggle governs both realms. It only weakens the
|
||||
* CAPTCHA — never authentication — and only for a device that already proved valid credentials; the per-IP
|
||||
* lockout still applies to every attempt. Disabled ({@code enabled=false}) ⇒ the CAPTCHA is always shown.
|
||||
*/
|
||||
public static class RememberDevice {
|
||||
private boolean enabled = true;
|
||||
private int days = 30;
|
||||
|
||||
public boolean isEnabled() {
|
||||
return enabled;
|
||||
}
|
||||
|
||||
public void setEnabled(boolean enabled) {
|
||||
this.enabled = enabled;
|
||||
}
|
||||
|
||||
public int getDays() {
|
||||
return days;
|
||||
}
|
||||
|
||||
public void setDays(int days) {
|
||||
this.days = days;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* App-realm CAPTCHA settings. The {@code secretKey} binds as the raw {@code ENC(...)} form (a
|
||||
* {@code secret}-typed setting, decrypted with {@code SecretCipher} at verification time).
|
||||
*/
|
||||
public static class Captcha {
|
||||
private boolean enabled = false;
|
||||
private String provider = "recaptcha-v2";
|
||||
private String siteKey = "";
|
||||
private String secretKey = "";
|
||||
private double scoreThreshold = 0.5;
|
||||
|
||||
public boolean isEnabled() {
|
||||
return enabled;
|
||||
}
|
||||
|
||||
public void setEnabled(boolean enabled) {
|
||||
this.enabled = enabled;
|
||||
}
|
||||
|
||||
public String getProvider() {
|
||||
return provider;
|
||||
}
|
||||
|
||||
public void setProvider(String provider) {
|
||||
this.provider = provider;
|
||||
}
|
||||
|
||||
public String getSiteKey() {
|
||||
return siteKey;
|
||||
}
|
||||
|
||||
public void setSiteKey(String siteKey) {
|
||||
this.siteKey = siteKey;
|
||||
}
|
||||
|
||||
public String getSecretKey() {
|
||||
return secretKey;
|
||||
}
|
||||
|
||||
public void setSecretKey(String secretKey) {
|
||||
this.secretKey = secretKey;
|
||||
}
|
||||
|
||||
public double getScoreThreshold() {
|
||||
return scoreThreshold;
|
||||
}
|
||||
|
||||
public void setScoreThreshold(double scoreThreshold) {
|
||||
this.scoreThreshold = scoreThreshold;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
package mx.quest.protection;
|
||||
|
||||
/**
|
||||
* A scope's login-protection policy — the settings the plugin's {@link LoginFormPolicyGuard} and
|
||||
* {@link SlidingWindowLoginGate} read to govern one realm/site's login. Persisted and resolved per scope by
|
||||
* {@link ProtectionConfigStore}: app-wide for the operator login, per-site for a tenant login.
|
||||
*
|
||||
* <p>Two always-on layers plus an opt-in third:
|
||||
* <ol>
|
||||
* <li><b>Honeypot</b> ({@code honeypotEnabled}) — a hidden trap field a human never fills; a non-blank value
|
||||
* marks the request as a bot.</li>
|
||||
* <li><b>Per-IP lockout</b> ({@code maxAttempts} within {@code windowSeconds} → locked {@code lockoutSeconds}).</li>
|
||||
* <li><b>External CAPTCHA</b> ({@link Captcha}) — a per-scope challenge verified server-side by
|
||||
* {@link LoginFormPolicyGuard} via {@link CaptchaVerifier} when {@link Captcha#active() active}.</li>
|
||||
* </ol>
|
||||
*
|
||||
* <p>Immutable and self-describing; the captcha {@code secretKey} is stored encrypted ({@code ENC(...)}) by the
|
||||
* store and decrypted into the resolved settings so only the verifier — never a template or the client — sees it.
|
||||
* {@link #defaults()} is the fail-safe baseline used whenever no config file exists or one cannot be read.
|
||||
*
|
||||
* @param honeypotEnabled whether the hidden trap field is enforced
|
||||
* @param maxAttempts failed logins within the window that trip the lockout
|
||||
* @param windowSeconds the sliding window over which failures accumulate
|
||||
* @param lockoutSeconds how long an IP stays locked once the threshold is reached
|
||||
* @param captcha the (opt-in) CAPTCHA policy; never {@code null} (use {@link Captcha#disabled()})
|
||||
*/
|
||||
public record ProtectionSettings(
|
||||
boolean honeypotEnabled,
|
||||
int maxAttempts,
|
||||
int windowSeconds,
|
||||
int lockoutSeconds,
|
||||
Captcha captcha) {
|
||||
|
||||
/**
|
||||
* The one lockout default, used by a fresh install ({@link ProtectionProperties.Login}), by a saved file that
|
||||
* omits a key ({@link StoredProtection}), by a non-positive value, and by {@link #defaults()}. Until 1.0.0 a
|
||||
* fresh install used 5 failures in 300 s while the other three used 10 in 900 s.
|
||||
*/
|
||||
public static final int DEFAULT_MAX_ATTEMPTS = 5;
|
||||
/** See {@link #DEFAULT_MAX_ATTEMPTS}. */
|
||||
public static final int DEFAULT_WINDOW_SECONDS = 300;
|
||||
/** See {@link #DEFAULT_MAX_ATTEMPTS}. */
|
||||
public static final int DEFAULT_LOCKOUT_SECONDS = 900;
|
||||
|
||||
/** Normalizes: a non-null captcha and positive thresholds (a hand-edited non-positive value falls back). */
|
||||
public ProtectionSettings {
|
||||
if (captcha == null) {
|
||||
captcha = Captcha.disabled();
|
||||
}
|
||||
if (maxAttempts <= 0) {
|
||||
maxAttempts = DEFAULT_MAX_ATTEMPTS;
|
||||
}
|
||||
if (windowSeconds <= 0) {
|
||||
windowSeconds = DEFAULT_WINDOW_SECONDS;
|
||||
}
|
||||
if (lockoutSeconds <= 0) {
|
||||
lockoutSeconds = DEFAULT_LOCKOUT_SECONDS;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The opt-in external CAPTCHA policy. The {@code secretKey} is sensitive and stored encrypted; it is read
|
||||
* server-side only, by {@link CaptchaVerifier} at challenge-verification time — never rendered into a view.
|
||||
*
|
||||
* @param enabled whether a CAPTCHA challenge is required on the login form
|
||||
* @param provider the reCAPTCHA mode ({@code recaptcha-v2} or {@code recaptcha-v3}); defaults to v2
|
||||
* @param siteKey the public site key rendered into the challenge widget
|
||||
* @param secretKey the private key used server-side to verify a response (stored {@code ENC(...)})
|
||||
* @param scoreThreshold the minimum acceptable score for the score-based v3 mode (0.0–1.0)
|
||||
*/
|
||||
public record Captcha(boolean enabled, String provider, String siteKey, String secretKey, double scoreThreshold) {
|
||||
|
||||
/** A disabled CAPTCHA with the default reCAPTCHA mode (v2) and score threshold. */
|
||||
public static Captcha disabled() {
|
||||
return new Captcha(false, "recaptcha-v2", "", "", 0.5);
|
||||
}
|
||||
|
||||
/** Whether the challenge is enabled AND both keys are present (only then is a challenge actually issued). */
|
||||
public boolean active() {
|
||||
return enabled && siteKey != null && !siteKey.isBlank() && secretKey != null && !secretKey.isBlank();
|
||||
}
|
||||
}
|
||||
|
||||
/** The fail-safe baseline: honeypot on, captcha off, 5 failures in 5 min → 15 min lockout. */
|
||||
public static ProtectionSettings defaults() {
|
||||
return new ProtectionSettings(true, DEFAULT_MAX_ATTEMPTS, DEFAULT_WINDOW_SECONDS, DEFAULT_LOCKOUT_SECONDS,
|
||||
Captcha.disabled());
|
||||
}
|
||||
}
|
||||
+35
@@ -0,0 +1,35 @@
|
||||
package mx.quest.protection;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.UncheckedIOException;
|
||||
import mx.quest.runway.spi.SiteLoginProtectionControl;
|
||||
|
||||
/**
|
||||
* The essential protection plugin's implementation of the app-realm {@link SiteLoginProtectionControl} rescue seam:
|
||||
* it reports and disables a site's login CAPTCHA over the {@link ProtectionConfigStore} it already owns. Registered
|
||||
* {@code @Primary} in {@link ProtectionConfig}, so it wins by-type injection over the kernel's no-op default — the
|
||||
* app Sites screen can rescue a tenant locked out by a broken CAPTCHA without knowing anything about this plugin.
|
||||
*/
|
||||
public class ProtectionSiteLoginControl implements SiteLoginProtectionControl {
|
||||
|
||||
private final ProtectionConfigStore store;
|
||||
|
||||
public ProtectionSiteLoginControl(ProtectionConfigStore store) {
|
||||
this.store = store;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean captchaEnabled(String siteId) {
|
||||
return store.siteCaptchaEnabled(siteId);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void disableCaptcha(String siteId) {
|
||||
try {
|
||||
store.disableSiteCaptcha(siteId);
|
||||
} catch (IOException e) {
|
||||
// Surface as unchecked so the app controller's catch renders an error flash rather than a 500.
|
||||
throw new UncheckedIOException("could not disable login CAPTCHA for site '" + siteId + "'", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
package mx.quest.protection;
|
||||
|
||||
import java.util.Set;
|
||||
import mx.quest.runway.protect.EdgeGuard;
|
||||
import mx.quest.runway.protect.EdgeRequest;
|
||||
import mx.quest.runway.protect.EdgeVerdict;
|
||||
import mx.quest.runway.protect.RejectionOutcome;
|
||||
import mx.quest.runway.web.CidrSet;
|
||||
|
||||
/**
|
||||
* The DoS/abuse policy filling the kernel's {@link EdgeGuard} seam, evaluated on every request before the security
|
||||
* chain:
|
||||
* <ol>
|
||||
* <li>a static <b>allowlist</b> (the configured trusted CIDRs — e.g. a monitoring probe) passes immediately.
|
||||
* Loopback is <b>not</b> on it unless the operator lists it: it is never blockable (the blocklist refuses
|
||||
* it), but it is rate-limited like any client — behind a same-host proxy every request can arrive from
|
||||
* loopback, and an implicit exemption would turn the limit off for everyone;</li>
|
||||
* <li>the mutable {@link IpBlocklist} (manual operator bans, persisted; auto-escalated bans, ephemeral) rejects
|
||||
* — {@code 429} with the remaining time for an auto-escalation, {@code 403} for an operator ban —
|
||||
* checked <b>before</b> the token bucket, so a banned IP never even consumes a token;</li>
|
||||
* <li>otherwise a per-IP {@link TokenBucketRateLimiter} admits the request or throttles it {@code 429} with a
|
||||
* short {@code Retry-After} — a throttle feeds the limiter's auto-escalation, which may add an auto block.</li>
|
||||
* </ol>
|
||||
*
|
||||
* <p>O(1) per request (a small CIDR-set check, a map lookup in the blocklist, and a token-bucket update).
|
||||
* Fail-<b>safe</b>: the blocklist check fails open on error (it never turns away legitimate traffic — the rate
|
||||
* limit still applies), and the static allowlist / loopback are never blockable in the first place (loopback's
|
||||
* throttles therefore never escalate into an auto-block).
|
||||
*/
|
||||
public final class RateLimitEdgeGuard implements EdgeGuard {
|
||||
|
||||
private final CidrSet allowlist;
|
||||
private final IpBlocklist blocklist;
|
||||
private final TokenBucketRateLimiter limiter;
|
||||
|
||||
public RateLimitEdgeGuard(CidrSet allowlist, IpBlocklist blocklist, TokenBucketRateLimiter limiter) {
|
||||
this.allowlist = allowlist;
|
||||
this.blocklist = blocklist;
|
||||
this.limiter = limiter;
|
||||
}
|
||||
|
||||
@Override
|
||||
public EdgeVerdict check(EdgeRequest request) {
|
||||
String ip = request.clientIp();
|
||||
if (allowlist.contains(ip)) {
|
||||
return EdgeVerdict.pass();
|
||||
}
|
||||
|
||||
// ONE lookup, and it reports WHICH kind of block matched — an operator ban and an auto-escalation are
|
||||
// indistinguishable on the wire but call for opposite responses.
|
||||
//
|
||||
// An auto-block IS "too many requests": the rate limiter escalating, not a decision about who may
|
||||
// read the site. Answering 403 with no Retry-After told a crawler it was forbidden, plausibly
|
||||
// permanently, for what is in fact a fifteen-minute time-out — and a crawler that concludes it is
|
||||
// banned stops coming back, which is how pages quietly leave an index. 429 + the real remaining time
|
||||
// says exactly what is true and exactly when to return.
|
||||
//
|
||||
// Manual and CIDR blocks keep 403: an operator ban genuinely is "forbidden", and there is no honest
|
||||
// retry time to offer. An auto-block always has an end (the limiter clamps block-seconds to at least 1);
|
||||
// should one ever arrive without an expiry it falls back to 403 for the same reason — better to say
|
||||
// nothing than to invent a number.
|
||||
IpBlocklist.Match block = blocklist.match(ip);
|
||||
if (block != null) {
|
||||
if (block.autoEscalated() && block.remainingSeconds() > 0) {
|
||||
return EdgeVerdict.reject(429, (int) Math.min(Integer.MAX_VALUE, block.remainingSeconds()),
|
||||
block.kind());
|
||||
}
|
||||
return EdgeVerdict.reject(403, block.kind());
|
||||
}
|
||||
if (!limiter.tryAcquire(ip)) {
|
||||
return EdgeVerdict.reject(429, 1, "rate-limit");
|
||||
}
|
||||
return EdgeVerdict.pass();
|
||||
}
|
||||
|
||||
/**
|
||||
* The five rejections this guard can actually answer with, so all five counters exist at zero from
|
||||
* startup rather than appearing on first use (see {@code EdgeGuard#declaredOutcomes}).
|
||||
*
|
||||
* <p>Enumerated as pairs, not as a status set crossed with a reason set: {@code blocklist-auto} appears
|
||||
* under <b>both</b> statuses because an auto-block normally carries a remaining time and answers
|
||||
* {@code 429}; the {@code 403} pair is the defensive fallback for one without an expiry, which the limiter
|
||||
* never creates today (it clamps block-seconds to at least 1) but a blocklist entry could. Whereas
|
||||
* a {@code 429} tagged {@code blocklist-manual} is unreachable by construction, and registering it would
|
||||
* publish a permanent zero asserting something no code path can produce.
|
||||
*/
|
||||
@Override
|
||||
public Set<RejectionOutcome> declaredOutcomes() {
|
||||
return 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"));
|
||||
}
|
||||
}
|
||||
+100
@@ -0,0 +1,100 @@
|
||||
package mx.quest.protection;
|
||||
|
||||
import java.io.IOException;
|
||||
import mx.quest.runway.spi.service.ConsoleScreen;
|
||||
import mx.quest.runway.spi.service.RequestContext;
|
||||
import org.springframework.beans.factory.annotation.Qualifier;
|
||||
import org.springframework.context.MessageSource;
|
||||
import org.springframework.context.i18n.LocaleContextHolder;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.security.access.prepost.PreAuthorize;
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.ui.Model;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
import org.springframework.web.server.ResponseStatusException;
|
||||
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
|
||||
|
||||
/**
|
||||
* The tenant-realm <b>Protection</b> screen ({@code /__admin/protection}) — a dedicated custom editor for the
|
||||
* <b>bound site's</b> per-site login-protection policy, stored in {@code sites/<id>/plugins/protection.yml}: the
|
||||
* honeypot switch and the external CAPTCHA (provider, public site key, secret, v3 score threshold).
|
||||
*
|
||||
* <p><b>The per-IP lockout is deliberately NOT here.</b> The lockout ({@link SlidingWindowLoginGate}) reads the
|
||||
* <b>application-scope</b> thresholds and is keyed by IP platform-wide, so a per-site value would never take effect;
|
||||
* offering it per-site was misleading, so the screen (and {@link StoredSiteProtection}) omit it. Per-site protection
|
||||
* is honeypot + CAPTCHA only; the app screen owns the lockout floor.
|
||||
*
|
||||
* <p><b>Isolation.</b> The tenancy is taken from {@link RequestContext#site()} (the host-resolved bound site),
|
||||
* <b>never</b> a path or query parameter, so this screen can only ever read and write the tenant of the request —
|
||||
* site A's screen can never touch site B's config. Gated by the kernel {@code CONFIGURE_SITE} permission (mirrors
|
||||
* the SEO / Icons tenant screens); the plugin's app-scope config is untouched from here.
|
||||
*
|
||||
* <p>Secret masking, blank-preserves-the-secret and immediate apply are the same as the app screen (shared
|
||||
* {@link ProtectionForm} logic). It renders inside {@code op-layout} as a {@link ConsoleScreen}.
|
||||
*/
|
||||
@Controller
|
||||
@ConsoleScreen
|
||||
public class SiteProtectionController {
|
||||
|
||||
private final RequestContext requestContext;
|
||||
private final ProtectionConfigStore store;
|
||||
private final MessageSource messages;
|
||||
|
||||
public SiteProtectionController(RequestContext requestContext, ProtectionConfigStore store,
|
||||
@Qualifier("operatorAwareMessageSource") MessageSource messages) {
|
||||
this.requestContext = requestContext;
|
||||
this.store = store;
|
||||
this.messages = messages;
|
||||
}
|
||||
|
||||
@GetMapping("/__admin/protection")
|
||||
@PreAuthorize("@authz.may('CONFIGURE_SITE')")
|
||||
public String form(Model model) {
|
||||
ProtectionForm.populate(model, store.perSiteSettings(currentSiteId()), store.secretStorable());
|
||||
model.addAttribute(ConsoleScreen.CONTENT_TEMPLATE, "__plugin__/protection/site-protection");
|
||||
model.addAttribute(ConsoleScreen.PAGE_TITLE_KEY, "protection.screen.site.title");
|
||||
return ConsoleScreen.LAYOUT_VIEW;
|
||||
}
|
||||
|
||||
@PostMapping("/__admin/protection")
|
||||
@PreAuthorize("@authz.may('CONFIGURE_SITE')")
|
||||
public String save(@RequestParam(name = "honeypotEnabled", defaultValue = "false") boolean honeypotEnabled,
|
||||
@RequestParam(name = "captchaEnabled", defaultValue = "false") boolean captchaEnabled,
|
||||
@RequestParam(required = false) String provider,
|
||||
@RequestParam(required = false) String siteKey,
|
||||
@RequestParam(required = false) String secretKey,
|
||||
@RequestParam(defaultValue = "0.5") double scoreThreshold,
|
||||
RedirectAttributes redirect) {
|
||||
String siteId = currentSiteId();
|
||||
ProtectionSettings current = store.perSiteSettings(siteId);
|
||||
try {
|
||||
// The per-IP lockout is app-scope (not editable per-site): its thresholds are passed as 0 — the canonical
|
||||
// constructor defaults them and savePerSite drops them from the site file. Only honeypot + captcha persist.
|
||||
ProtectionSettings updated = ProtectionForm.merge(current, honeypotEnabled, 0, 0, 0,
|
||||
captchaEnabled, provider, siteKey, secretKey, scoreThreshold);
|
||||
store.savePerSite(siteId, updated);
|
||||
redirect.addFlashAttribute("flash", message("protection.screen.saved", "Protection settings saved."));
|
||||
} catch (IllegalStateException noKey) {
|
||||
redirect.addFlashAttribute("error",
|
||||
message("protection.screen.noCipher", "Cannot store the captcha secret: no encryption key is "
|
||||
+ "configured (runway.security.secret-key)."));
|
||||
} catch (IOException e) {
|
||||
redirect.addFlashAttribute("error",
|
||||
message("protection.screen.failed", "Could not save protection settings."));
|
||||
}
|
||||
return "redirect:/__admin/protection";
|
||||
}
|
||||
|
||||
/** The bound tenancy's id, from the host resolution — never a request parameter (isolation). */
|
||||
private String currentSiteId() {
|
||||
return requestContext.site()
|
||||
.orElseThrow(() -> new ResponseStatusException(HttpStatus.BAD_REQUEST, "no bound tenancy"))
|
||||
.id();
|
||||
}
|
||||
|
||||
private String message(String key, String fallback) {
|
||||
return messages.getMessage(key, null, fallback, LocaleContextHolder.getLocale());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
package mx.quest.protection;
|
||||
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
/**
|
||||
* A tiny, dependency-free reader for the two fields the CAPTCHA {@code siteverify} JSON carries that
|
||||
* {@link CaptchaVerifier} actually consumes: the boolean {@code success} and (reCAPTCHA v3 only) the numeric
|
||||
* {@code score}. reCAPTCHA returns a flat top-level JSON object with these keys, so a targeted field scan is both
|
||||
* sufficient and safer than binding a full model — it never fails on an unexpected extra field and pulls no JSON
|
||||
* library into the thin plugin jar.
|
||||
*
|
||||
* <p>Non-strict on purpose: a body that is missing, blank, or malformed yields {@code success == false} and
|
||||
* {@code score == 0.0} (a rejection, not an exception) — the verifier's transport-level fail-open is decided
|
||||
* before this reader is reached, so here a body we cannot make sense of is treated as "not verified", which is
|
||||
* the safe outcome for a *present* (2xx) response. The patterns are anchored to the {@code "success"} /
|
||||
* {@code "score"} keys so a boolean/number elsewhere in the payload cannot be mistaken for them.
|
||||
*/
|
||||
final class SiteVerifyResponse {
|
||||
|
||||
// "success" : true — tolerant of whitespace around the colon; value must be the literal true/false token.
|
||||
private static final Pattern SUCCESS =
|
||||
Pattern.compile("\"success\"\\s*:\\s*(true|false)", Pattern.CASE_INSENSITIVE);
|
||||
|
||||
// "score" : 0.7 — a JSON number (optional sign, decimals, exponent).
|
||||
private static final Pattern SCORE =
|
||||
Pattern.compile("\"score\"\\s*:\\s*(-?\\d+(?:\\.\\d+)?(?:[eE][-+]?\\d+)?)");
|
||||
|
||||
private SiteVerifyResponse() {
|
||||
}
|
||||
|
||||
/** Whether the response's {@code success} field is present and {@code true}; false for any other body. */
|
||||
static boolean success(String body) {
|
||||
if (body == null || body.isBlank()) {
|
||||
return false;
|
||||
}
|
||||
Matcher m = SUCCESS.matcher(body);
|
||||
return m.find() && "true".equalsIgnoreCase(m.group(1));
|
||||
}
|
||||
|
||||
/** The response's {@code score} (reCAPTCHA v3), or {@code 0.0} when absent/unparseable (a safe floor). */
|
||||
static double score(String body) {
|
||||
if (body == null || body.isBlank()) {
|
||||
return 0.0;
|
||||
}
|
||||
Matcher m = SCORE.matcher(body);
|
||||
if (!m.find()) {
|
||||
return 0.0;
|
||||
}
|
||||
try {
|
||||
return Double.parseDouble(m.group(1));
|
||||
} catch (NumberFormatException e) {
|
||||
return 0.0;
|
||||
}
|
||||
}
|
||||
}
|
||||
+112
@@ -0,0 +1,112 @@
|
||||
package mx.quest.protection;
|
||||
|
||||
import java.util.ArrayDeque;
|
||||
import java.util.Deque;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.function.LongSupplier;
|
||||
import java.util.function.Supplier;
|
||||
import mx.quest.runway.security.LoginAttemptGate;
|
||||
|
||||
/**
|
||||
* The brute-force lockout policy: per-IP, count failed logins within a sliding {@code windowMillis}; once
|
||||
* {@code maxAttempts} fall inside the window the IP is locked for {@code lockoutMillis}. A success clears the
|
||||
* IP. Implements the kernel's {@link LoginAttemptGate} seam, so {@code LoginProtectionFilter} blocks a locked
|
||||
* IP before authentication. Thread-safe; the clock is injectable for deterministic tests.
|
||||
*
|
||||
* <p><b>Config-driven, read fresh per call.</b> The three thresholds are pulled from a {@link Supplier} of the
|
||||
* current {@link ProtectionSettings} (backed by {@link ProtectionConfigStore}) on every failure and lock check,
|
||||
* <b>not</b> frozen at construction — so an operator (or the Protection screens) changing the app-level protection
|
||||
* config takes effect without a restart. The seam is IP-only (it has no per-request scope), so the gate uses the
|
||||
* <b>application-scope</b> settings for its thresholds; per-site login deterrents that need the request live in
|
||||
* the request-aware {@link LoginFormPolicyGuard}. A bad/absent config degrades to the settings' own defaults (fail-safe;
|
||||
* {@link ProtectionSettings} normalizes non-positive values), so the lockout never disappears or misbehaves.
|
||||
*/
|
||||
public final class SlidingWindowLoginGate implements LoginAttemptGate {
|
||||
|
||||
private static final int DEFAULT_MAX_IPS = 100_000;
|
||||
|
||||
private final Supplier<ProtectionSettings> settings;
|
||||
private final int maxIps;
|
||||
private final LongSupplier nowMillis;
|
||||
private final ConcurrentHashMap<String, Attempts> byIp = new ConcurrentHashMap<>();
|
||||
|
||||
public SlidingWindowLoginGate(Supplier<ProtectionSettings> settings, LongSupplier nowMillis) {
|
||||
this(settings, DEFAULT_MAX_IPS, nowMillis);
|
||||
}
|
||||
|
||||
public SlidingWindowLoginGate(Supplier<ProtectionSettings> settings, int maxIps, LongSupplier nowMillis) {
|
||||
this.settings = settings;
|
||||
this.maxIps = Math.max(1, maxIps);
|
||||
this.nowMillis = nowMillis;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isLocked(String clientIp) {
|
||||
Attempts attempts = byIp.get(clientIp);
|
||||
return attempts != null && attempts.lockedUntil() > nowMillis.getAsLong();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void recordFailure(String clientIp) {
|
||||
ProtectionSettings current = current();
|
||||
int maxAttempts = current.maxAttempts();
|
||||
long windowMillis = current.windowSeconds() * 1000L;
|
||||
long lockoutMillis = current.lockoutSeconds() * 1000L;
|
||||
|
||||
long now = nowMillis.getAsLong();
|
||||
if (byIp.size() >= maxIps && !byIp.containsKey(clientIp)) {
|
||||
// bound memory against a many-IP login flood: reclaim entries with no in-window failures and no
|
||||
// active lockout; if still at the cap, clear (a crude floor — better than unbounded heap growth).
|
||||
byIp.entrySet().removeIf(entry -> entry.getValue().isDead(now, windowMillis));
|
||||
if (byIp.size() >= maxIps) {
|
||||
byIp.clear();
|
||||
}
|
||||
}
|
||||
byIp.computeIfAbsent(clientIp, k -> new Attempts()).onFailure(now, windowMillis, maxAttempts, lockoutMillis);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void recordSuccess(String clientIp) {
|
||||
byIp.remove(clientIp);
|
||||
}
|
||||
|
||||
/** The current app-scope thresholds; a null/failing supplier degrades to the settings defaults (fail-safe). */
|
||||
private ProtectionSettings current() {
|
||||
if (settings == null) {
|
||||
return ProtectionSettings.defaults();
|
||||
}
|
||||
try {
|
||||
ProtectionSettings resolved = settings.get();
|
||||
return resolved != null ? resolved : ProtectionSettings.defaults();
|
||||
} catch (RuntimeException e) {
|
||||
return ProtectionSettings.defaults();
|
||||
}
|
||||
}
|
||||
|
||||
private static final class Attempts {
|
||||
private final Deque<Long> failures = new ArrayDeque<>();
|
||||
private long lockedUntil;
|
||||
|
||||
synchronized void onFailure(long now, long windowMillis, int maxAttempts, long lockoutMillis) {
|
||||
while (!failures.isEmpty() && failures.peekFirst() < now - windowMillis) {
|
||||
failures.pollFirst(); // drop failures older than the window
|
||||
}
|
||||
failures.addLast(now);
|
||||
if (failures.size() >= maxAttempts) {
|
||||
lockedUntil = now + lockoutMillis;
|
||||
}
|
||||
}
|
||||
|
||||
synchronized long lockedUntil() {
|
||||
return lockedUntil;
|
||||
}
|
||||
|
||||
/** Whether this entry can be reclaimed: no failures left in the window and no active lockout. */
|
||||
synchronized boolean isDead(long now, long windowMillis) {
|
||||
while (!failures.isEmpty() && failures.peekFirst() < now - windowMillis) {
|
||||
failures.pollFirst();
|
||||
}
|
||||
return failures.isEmpty() && lockedUntil <= now;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
package mx.quest.protection;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* The on-disk YAML shape of the manual IP blocklist ({@code external/blocklist.yml}) — a single container holding
|
||||
* the list of persisted operator blocks. Only <b>manual</b> blocks are stored (auto-escalated blocks are ephemeral
|
||||
* and never written); {@link IpBlocklist} rewrites this whole file on every manual change.
|
||||
*
|
||||
* <p>Mutable classes with no-arg constructors (not records) so Jackson can bind a partial/hand-edited file
|
||||
* field-by-field, defaulting any omitted field — {@link IpBlocklist} then normalizes (dropping already-expired
|
||||
* and blank-IP entries) on load.
|
||||
*/
|
||||
public class StoredBlocklist {
|
||||
|
||||
private List<StoredEntry> entries = new ArrayList<>();
|
||||
|
||||
public StoredBlocklist() {
|
||||
}
|
||||
|
||||
public StoredBlocklist(List<StoredEntry> entries) {
|
||||
this.entries = entries != null ? entries : new ArrayList<>();
|
||||
}
|
||||
|
||||
public List<StoredEntry> getEntries() {
|
||||
return entries;
|
||||
}
|
||||
|
||||
public void setEntries(List<StoredEntry> entries) {
|
||||
this.entries = entries;
|
||||
}
|
||||
|
||||
/**
|
||||
* One persisted manual block. {@code untilEpochSeconds == 0} means an indefinite block. There is no
|
||||
* {@code manual} field — everything in this file is manual by construction.
|
||||
*/
|
||||
public static class StoredEntry {
|
||||
private String ip = "";
|
||||
private String reason = "";
|
||||
private long untilEpochSeconds;
|
||||
|
||||
public StoredEntry() {
|
||||
}
|
||||
|
||||
public StoredEntry(String ip, String reason, long untilEpochSeconds) {
|
||||
this.ip = ip;
|
||||
this.reason = reason;
|
||||
this.untilEpochSeconds = untilEpochSeconds;
|
||||
}
|
||||
|
||||
public String getIp() {
|
||||
return ip;
|
||||
}
|
||||
|
||||
public void setIp(String ip) {
|
||||
this.ip = ip;
|
||||
}
|
||||
|
||||
public String getReason() {
|
||||
return reason;
|
||||
}
|
||||
|
||||
public void setReason(String reason) {
|
||||
this.reason = reason;
|
||||
}
|
||||
|
||||
public long getUntilEpochSeconds() {
|
||||
return untilEpochSeconds;
|
||||
}
|
||||
|
||||
public void setUntilEpochSeconds(long untilEpochSeconds) {
|
||||
this.untilEpochSeconds = untilEpochSeconds;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,141 @@
|
||||
package mx.quest.protection;
|
||||
|
||||
import java.util.function.UnaryOperator;
|
||||
|
||||
/**
|
||||
* The on-disk YAML shape of a site's protection config ({@code sites/<id>/plugins/protection.yml}). It mirrors
|
||||
* {@link ProtectionSettings} but keeps the captcha secret in its <b>stored</b> form ({@code ENC(...)}); the
|
||||
* conversion to a usable {@link ProtectionSettings} decrypts it via the supplied function. A mutable class with a
|
||||
* no-arg constructor (not a record) so Jackson can bind a partial/hand-edited file field-by-field, defaulting any
|
||||
* omitted field — the store then normalizes through {@link ProtectionSettings}'s canonical constructor.
|
||||
*/
|
||||
public class StoredProtection {
|
||||
|
||||
private boolean honeypotEnabled = true;
|
||||
private int maxAttempts = ProtectionSettings.DEFAULT_MAX_ATTEMPTS;
|
||||
private int windowSeconds = ProtectionSettings.DEFAULT_WINDOW_SECONDS;
|
||||
private int lockoutSeconds = ProtectionSettings.DEFAULT_LOCKOUT_SECONDS;
|
||||
private StoredCaptcha captcha = new StoredCaptcha();
|
||||
|
||||
public StoredProtection() {
|
||||
}
|
||||
|
||||
public StoredProtection(boolean honeypotEnabled, int maxAttempts, int windowSeconds, int lockoutSeconds,
|
||||
StoredCaptcha captcha) {
|
||||
this.honeypotEnabled = honeypotEnabled;
|
||||
this.maxAttempts = maxAttempts;
|
||||
this.windowSeconds = windowSeconds;
|
||||
this.lockoutSeconds = lockoutSeconds;
|
||||
this.captcha = captcha != null ? captcha : new StoredCaptcha();
|
||||
}
|
||||
|
||||
/** Converts to the usable settings, decrypting the stored captcha secret with {@code decrypt}. */
|
||||
public ProtectionSettings toSettings(UnaryOperator<String> decrypt) {
|
||||
StoredCaptcha c = captcha != null ? captcha : new StoredCaptcha();
|
||||
ProtectionSettings.Captcha resolved = new ProtectionSettings.Captcha(
|
||||
c.isEnabled(), c.getProvider(), c.getSiteKey(), decrypt.apply(c.getSecretKey()),
|
||||
c.getScoreThreshold());
|
||||
return new ProtectionSettings(honeypotEnabled, maxAttempts, windowSeconds, lockoutSeconds, resolved);
|
||||
}
|
||||
|
||||
public boolean isHoneypotEnabled() {
|
||||
return honeypotEnabled;
|
||||
}
|
||||
|
||||
public void setHoneypotEnabled(boolean honeypotEnabled) {
|
||||
this.honeypotEnabled = honeypotEnabled;
|
||||
}
|
||||
|
||||
public int getMaxAttempts() {
|
||||
return maxAttempts;
|
||||
}
|
||||
|
||||
public void setMaxAttempts(int maxAttempts) {
|
||||
this.maxAttempts = maxAttempts;
|
||||
}
|
||||
|
||||
public int getWindowSeconds() {
|
||||
return windowSeconds;
|
||||
}
|
||||
|
||||
public void setWindowSeconds(int windowSeconds) {
|
||||
this.windowSeconds = windowSeconds;
|
||||
}
|
||||
|
||||
public int getLockoutSeconds() {
|
||||
return lockoutSeconds;
|
||||
}
|
||||
|
||||
public void setLockoutSeconds(int lockoutSeconds) {
|
||||
this.lockoutSeconds = lockoutSeconds;
|
||||
}
|
||||
|
||||
public StoredCaptcha getCaptcha() {
|
||||
return captcha;
|
||||
}
|
||||
|
||||
public void setCaptcha(StoredCaptcha captcha) {
|
||||
this.captcha = captcha;
|
||||
}
|
||||
|
||||
/** The on-disk captcha section; {@code secretKey} is the stored {@code ENC(...)} ciphertext. */
|
||||
public static class StoredCaptcha {
|
||||
private boolean enabled = false;
|
||||
private String provider = "recaptcha-v2";
|
||||
private String siteKey = "";
|
||||
private String secretKey = "";
|
||||
private double scoreThreshold = 0.5;
|
||||
|
||||
public boolean isEnabled() {
|
||||
return enabled;
|
||||
}
|
||||
|
||||
public void setEnabled(boolean enabled) {
|
||||
this.enabled = enabled;
|
||||
}
|
||||
|
||||
public String getProvider() {
|
||||
return provider;
|
||||
}
|
||||
|
||||
public void setProvider(String provider) {
|
||||
this.provider = provider;
|
||||
}
|
||||
|
||||
public String getSiteKey() {
|
||||
return siteKey;
|
||||
}
|
||||
|
||||
public void setSiteKey(String siteKey) {
|
||||
this.siteKey = siteKey;
|
||||
}
|
||||
|
||||
public String getSecretKey() {
|
||||
return secretKey;
|
||||
}
|
||||
|
||||
public void setSecretKey(String secretKey) {
|
||||
this.secretKey = secretKey;
|
||||
}
|
||||
|
||||
public double getScoreThreshold() {
|
||||
return scoreThreshold;
|
||||
}
|
||||
|
||||
public void setScoreThreshold(double scoreThreshold) {
|
||||
this.scoreThreshold = scoreThreshold;
|
||||
}
|
||||
|
||||
public StoredCaptcha() {
|
||||
}
|
||||
|
||||
public StoredCaptcha(boolean enabled, String provider, String siteKey, String secretKey,
|
||||
double scoreThreshold) {
|
||||
this.enabled = enabled;
|
||||
this.provider = provider;
|
||||
this.siteKey = siteKey;
|
||||
this.secretKey = secretKey;
|
||||
this.scoreThreshold = scoreThreshold;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
package mx.quest.protection;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
|
||||
import java.util.function.UnaryOperator;
|
||||
|
||||
/**
|
||||
* The on-disk YAML shape of a <b>site's</b> protection config ({@code sites/<id>/plugins/protection.yml}) — the
|
||||
* honeypot switch and the CAPTCHA section <b>only</b>. The per-IP lockout thresholds (max attempts / window /
|
||||
* lockout) are deliberately <b>not</b> here: the lockout is an <b>application-scope platform floor</b>
|
||||
* ({@link SlidingWindowLoginGate} reads the app settings and is keyed by IP platform-wide), so a per-site value
|
||||
* would never take effect — exposing it per-site was misleading. This mirrors the honeypot/CAPTCHA half of
|
||||
* {@link StoredProtection}, keeping the captcha secret in its stored {@code ENC(...)} form.
|
||||
*
|
||||
* <p>{@code @JsonIgnoreProperties(ignoreUnknown = true)} so a pre-existing per-site file that still carries the
|
||||
* (now-inert) {@code maxAttempts}/{@code windowSeconds}/{@code lockoutSeconds} keys loads cleanly; the next
|
||||
* {@code savePerSite} rewrites the file without them, so the stale keys drop out on first edit. A mutable class with
|
||||
* a no-arg constructor (not a record) so Jackson can bind a partial/hand-edited file field-by-field.
|
||||
*/
|
||||
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||
public class StoredSiteProtection {
|
||||
|
||||
private boolean honeypotEnabled = true;
|
||||
private StoredProtection.StoredCaptcha captcha = new StoredProtection.StoredCaptcha();
|
||||
|
||||
public StoredSiteProtection() {
|
||||
}
|
||||
|
||||
public StoredSiteProtection(boolean honeypotEnabled, StoredProtection.StoredCaptcha captcha) {
|
||||
this.honeypotEnabled = honeypotEnabled;
|
||||
this.captcha = captcha != null ? captcha : new StoredProtection.StoredCaptcha();
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts to usable settings, decrypting the stored captcha secret with {@code decrypt}. The lockout thresholds
|
||||
* are passed as {@code 0}, which {@link ProtectionSettings}'s canonical constructor floors to its defaults — they
|
||||
* are inert for a site (the app-scope gate governs the lockout), so the value is never read.
|
||||
*/
|
||||
public ProtectionSettings toSettings(UnaryOperator<String> decrypt) {
|
||||
StoredProtection.StoredCaptcha c = captcha != null ? captcha : new StoredProtection.StoredCaptcha();
|
||||
ProtectionSettings.Captcha resolved = new ProtectionSettings.Captcha(
|
||||
c.isEnabled(), c.getProvider(), c.getSiteKey(), decrypt.apply(c.getSecretKey()), c.getScoreThreshold());
|
||||
return new ProtectionSettings(honeypotEnabled, 0, 0, 0, resolved);
|
||||
}
|
||||
|
||||
public boolean isHoneypotEnabled() {
|
||||
return honeypotEnabled;
|
||||
}
|
||||
|
||||
public void setHoneypotEnabled(boolean honeypotEnabled) {
|
||||
this.honeypotEnabled = honeypotEnabled;
|
||||
}
|
||||
|
||||
public StoredProtection.StoredCaptcha getCaptcha() {
|
||||
return captcha;
|
||||
}
|
||||
|
||||
public void setCaptcha(StoredProtection.StoredCaptcha captcha) {
|
||||
this.captcha = captcha;
|
||||
}
|
||||
}
|
||||
+180
@@ -0,0 +1,180 @@
|
||||
package mx.quest.protection;
|
||||
|
||||
import java.util.ArrayDeque;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Comparator;
|
||||
import java.util.Deque;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.function.LongSupplier;
|
||||
|
||||
/**
|
||||
* A per-key (per-IP) token-bucket rate limiter with <b>auto-escalation</b>: each key gets a bucket of
|
||||
* {@code capacity} tokens that refills at {@code refillPerSecond}; a request consumes one token and is throttled
|
||||
* (rejected) when the bucket is empty. When a key accumulates {@code breachThreshold} throttled requests within
|
||||
* {@code windowSeconds}, it is handed to the {@link IpBlocklist} for a temporary <b>auto</b> block
|
||||
* ({@code blockSeconds}) — an ephemeral, in-memory ban that a still-abusive IP re-earns after a restart.
|
||||
*
|
||||
* <p>Bounded: once {@code maxKeys} distinct keys are tracked the table is cleared (a crude but memory-safe bound —
|
||||
* a flood across many IPs briefly resets buckets and offender stats rather than exhausting heap; the rich eviction
|
||||
* policy is a later refinement). Thread-safe (a lock-free map on the hot path; one short {@code synchronized} block
|
||||
* per bucket). The clock is injectable so the behaviour is deterministically testable.
|
||||
*
|
||||
* <h2>Offenders</h2>
|
||||
* Each bucket also tallies its total requests, its throttled (429) count and its last-seen time; {@link
|
||||
* #topOffenders(int)} returns the busiest rate-limited IPs (by throttled count) for the operator's
|
||||
* {@code /__app/dos} screen.
|
||||
*
|
||||
* <p><b>On the bound's precision:</b> the size-check and the {@code computeIfAbsent} in {@link #tryAcquire} are not
|
||||
* one atomic step, so under heavy concurrency the table may briefly hold up to ~thread-count entries beyond
|
||||
* {@code maxKeys} before the next call clears it. This is intentional: the map stays lock-free on the request hot
|
||||
* path and the overage is tiny and self-correcting, so memory is still effectively bounded.
|
||||
*/
|
||||
public final class TokenBucketRateLimiter {
|
||||
|
||||
private final int capacity;
|
||||
private final double refillPerSecond;
|
||||
private final int maxKeys;
|
||||
private final LongSupplier nanoTime;
|
||||
|
||||
// --- auto-escalation (all zero/absent ⇒ escalation is off; the rate-limit floor still applies) ---
|
||||
private final boolean autoBlockEnabled;
|
||||
private final int breachThreshold;
|
||||
private final long breachWindowMillis;
|
||||
private final long blockSeconds;
|
||||
private final IpBlocklist blocklist;
|
||||
private final LongSupplier milliTime;
|
||||
|
||||
private final ConcurrentHashMap<String, Bucket> buckets = new ConcurrentHashMap<>();
|
||||
|
||||
/**
|
||||
* A plain rate limiter with <b>no</b> auto-escalation (the pre-1d floor: throttle only). Kept so the guard and
|
||||
* tests can exercise the token bucket in isolation.
|
||||
*/
|
||||
public TokenBucketRateLimiter(int capacity, double refillPerSecond, int maxKeys, LongSupplier nanoTime) {
|
||||
this(capacity, refillPerSecond, maxKeys, nanoTime, null, new AutoBlock(false, 0, 0, 0), () -> 0L);
|
||||
}
|
||||
|
||||
/**
|
||||
* The full limiter with auto-escalation into {@code blocklist}. When {@code autoBlock.enabled()} and a key
|
||||
* breaches {@code breachThreshold} times within {@code windowSeconds}, it is auto-blocked for
|
||||
* {@code blockSeconds}. Passing a {@code null} blocklist or a disabled {@link AutoBlock} turns escalation off.
|
||||
*
|
||||
* @param nanoTime the monotonic nanosecond clock (token refill)
|
||||
* @param blocklist the escalation target (may be {@code null} to disable escalation)
|
||||
* @param autoBlock the escalation thresholds
|
||||
* @param milliTime the wall-clock millisecond clock (breach window + last-seen)
|
||||
*/
|
||||
public TokenBucketRateLimiter(int capacity, double refillPerSecond, int maxKeys, LongSupplier nanoTime,
|
||||
IpBlocklist blocklist, AutoBlock autoBlock, LongSupplier milliTime) {
|
||||
this.capacity = Math.max(1, capacity);
|
||||
this.refillPerSecond = Math.max(0.0, refillPerSecond);
|
||||
this.maxKeys = Math.max(1, maxKeys);
|
||||
this.nanoTime = nanoTime;
|
||||
this.blocklist = blocklist;
|
||||
this.autoBlockEnabled = autoBlock != null && autoBlock.enabled() && blocklist != null;
|
||||
this.breachThreshold = autoBlock != null ? Math.max(1, autoBlock.breachThreshold()) : 1;
|
||||
this.breachWindowMillis = autoBlock != null ? Math.max(1, autoBlock.windowSeconds()) * 1000L : 1000L;
|
||||
this.blockSeconds = autoBlock != null ? Math.max(1, autoBlock.blockSeconds()) : 1;
|
||||
this.milliTime = milliTime;
|
||||
}
|
||||
|
||||
/**
|
||||
* Consumes a token for {@code key}; returns {@code true} if one was available (allowed), else {@code false}
|
||||
* (throttled). A throttle feeds the auto-escalation window; the {@code breachThreshold}-th throttle within the
|
||||
* window hands {@code key} to the blocklist for a temporary auto block.
|
||||
*/
|
||||
public boolean tryAcquire(String key) {
|
||||
if (buckets.size() > maxKeys) {
|
||||
buckets.clear();
|
||||
}
|
||||
long now = nanoTime.getAsLong();
|
||||
long nowMillis = milliTime.getAsLong();
|
||||
Bucket bucket = buckets.computeIfAbsent(key, k -> new Bucket(capacity, now));
|
||||
boolean autoBlock;
|
||||
boolean allowed;
|
||||
synchronized (bucket) {
|
||||
allowed = bucket.tryAcquire(refillPerSecond, capacity, now, nowMillis);
|
||||
autoBlock = !allowed && autoBlockEnabled && bucket.recordBreach(nowMillis, breachWindowMillis, breachThreshold);
|
||||
}
|
||||
if (autoBlock) {
|
||||
// Outside the bucket lock: the blocklist has its own synchronization and may touch disk (never for auto).
|
||||
blocklist.block(key, blockSeconds, "auto: rate-limit", false);
|
||||
}
|
||||
return allowed;
|
||||
}
|
||||
|
||||
/**
|
||||
* The busiest rate-limited IPs — those with at least one throttled request — ordered by throttled count
|
||||
* (descending), capped at {@code limit}. A snapshot; safe to render.
|
||||
*/
|
||||
public List<Offender> topOffenders(int limit) {
|
||||
List<Offender> out = new ArrayList<>();
|
||||
buckets.forEach((ip, bucket) -> {
|
||||
synchronized (bucket) {
|
||||
if (bucket.throttled > 0) {
|
||||
out.add(new Offender(ip, bucket.requests, bucket.throttled, bucket.lastSeenMillis));
|
||||
}
|
||||
}
|
||||
});
|
||||
out.sort(Comparator.comparingLong(Offender::throttled).reversed());
|
||||
return out.size() > limit ? new ArrayList<>(out.subList(0, Math.max(0, limit))) : out;
|
||||
}
|
||||
|
||||
/**
|
||||
* The auto-escalation thresholds: an IP {@code breachThreshold} times throttled within {@code windowSeconds} is
|
||||
* auto-blocked for {@code blockSeconds}. {@code enabled == false} keeps the throttle floor without escalation.
|
||||
*/
|
||||
public record AutoBlock(boolean enabled, int breachThreshold, long windowSeconds, long blockSeconds) {
|
||||
}
|
||||
|
||||
/** A snapshot row for the offenders panel: the IP, its total requests, its throttled count, its last-seen ms. */
|
||||
public record Offender(String ip, long requests, long throttled, long lastSeenMillis) {
|
||||
}
|
||||
|
||||
private static final class Bucket {
|
||||
private double tokens;
|
||||
private long lastNanos;
|
||||
private long requests;
|
||||
private long throttled;
|
||||
private long lastSeenMillis;
|
||||
private final Deque<Long> breaches = new ArrayDeque<>(); // epoch millis of recent throttles, within window
|
||||
|
||||
Bucket(int capacity, long now) {
|
||||
this.tokens = capacity;
|
||||
this.lastNanos = now;
|
||||
}
|
||||
|
||||
boolean tryAcquire(double refillPerSecond, int capacity, long now, long nowMillis) {
|
||||
double elapsedSeconds = Math.max(0.0, (now - lastNanos) / 1_000_000_000.0);
|
||||
tokens = Math.min(capacity, tokens + elapsedSeconds * refillPerSecond);
|
||||
lastNanos = now;
|
||||
requests++;
|
||||
lastSeenMillis = nowMillis;
|
||||
if (tokens >= 1.0) {
|
||||
tokens -= 1.0;
|
||||
return true;
|
||||
}
|
||||
throttled++;
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Records a throttle at {@code nowMillis} into the sliding breach window and reports whether the count has
|
||||
* reached {@code threshold} (in which case the window is cleared so one block is emitted per breach-burst).
|
||||
* Must be called under this bucket's monitor.
|
||||
*/
|
||||
boolean recordBreach(long nowMillis, long windowMillis, int threshold) {
|
||||
long cutoff = nowMillis - windowMillis;
|
||||
while (!breaches.isEmpty() && breaches.peekFirst() < cutoff) {
|
||||
breaches.pollFirst();
|
||||
}
|
||||
breaches.addLast(nowMillis);
|
||||
if (breaches.size() >= threshold) {
|
||||
breaches.clear();
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,172 @@
|
||||
package mx.quest.protection;
|
||||
|
||||
import jakarta.servlet.http.Cookie;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import java.time.Duration;
|
||||
import mx.quest.runway.crypto.SecretCipher;
|
||||
import mx.quest.runway.security.ProtectionScope;
|
||||
import mx.quest.runway.security.TrustedDeviceIssuer;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.http.ResponseCookie;
|
||||
|
||||
/**
|
||||
* The plugin's "remember this device" policy — the {@code @Primary} {@link TrustedDeviceIssuer} that mints a
|
||||
* signed trusted-device cookie on a successful login (when the user opted in), plus the matching
|
||||
* {@link #isTrusted(HttpServletRequest, ProtectionScope) trust check} the login form guard and the login-view
|
||||
* contributor consult to SKIP the CAPTCHA on a trusted device. It is the opt-in convenience that answers "CAPTCHA
|
||||
* on every login is annoying" without removing the deterrent for anyone who hasn't proven themselves.
|
||||
*
|
||||
* <h2>Why it doesn't weaken security</h2>
|
||||
* <ul>
|
||||
* <li><b>Issued only after a successful login.</b> A cookie is minted at login-success time (see
|
||||
* {@link TrustedDeviceSuccessHandler}) and only when the scope's CAPTCHA is active — which means the CAPTCHA
|
||||
* was solved on that very login. A brute-forcing bot never authenticates, so it never earns a cookie.</li>
|
||||
* <li><b>Skips only the CAPTCHA, never authentication.</b> Credentials are still required on every login, and
|
||||
* the per-IP brute-force lockout ({@code SlidingWindowLoginGate}) still applies to every attempt.</li>
|
||||
* <li><b>Tamper-proof + scoped.</b> The cookie is AES-256-GCM sealed via the kernel {@link SecretCipher} (the
|
||||
* GCM auth tag is the integrity guarantee — a modified cookie fails to decrypt) and carries its realm + site
|
||||
* + expiry, re-checked against the resolved scope on every read. A cookie for site A can never skip site B's
|
||||
* CAPTCHA (host-only cookie + per-site name + payload binding — three independent scopings), and an app
|
||||
* cookie can never skip a tenant CAPTCHA or vice-versa.</li>
|
||||
* <li><b>Fail-safe.</b> A missing key, a forged/plaintext value, a tampered ciphertext, a wrong scope, or an
|
||||
* expired stamp all resolve to "not trusted" ⇒ the CAPTCHA is shown. The feature can only ever cause "more
|
||||
* CAPTCHA", never "less than intended".</li>
|
||||
* </ul>
|
||||
*
|
||||
* <p>Device-scoped (not user-scoped) by necessity: the login GET renders the CAPTCHA before any username is
|
||||
* entered, so the skip decision cannot depend on identity. This matches the common "remember this device" model
|
||||
* and is safe here because the cookie only skips a challenge, never a credential check. Stateless (the payload
|
||||
* lives in the cookie, not a server store), so it needs no cluster-replicated state; the trade-off is that an
|
||||
* outstanding cookie can only be invalidated by its own expiry or by rotating the master key.
|
||||
*
|
||||
* <p>Note (deliberate non-hardening): the cookie is sealed with {@link SecretCipher} under the same master key as
|
||||
* other stored secrets, with no crypto AAD/domain separation. This is not exploitable — a ciphertext from another
|
||||
* context (e.g. a stored SMTP password) would have to decrypt to exactly {@code REALM|siteId|<future-epoch>} to be
|
||||
* trusted, which it never will, and its contents are never attacker-chosen or readable — so the payload-format
|
||||
* re-check provides logical domain separation. AAD binding would add cryptographic domain separation but would
|
||||
* require widening the {@code SecretCipher} seam; the format check is sufficient here.
|
||||
*/
|
||||
public final class TrustedDeviceService implements TrustedDeviceIssuer {
|
||||
|
||||
/** The login-form field set when the user ticks "remember this device". Presence = opted in. */
|
||||
static final String REMEMBER_PARAM = "remember-device";
|
||||
/** Cookie name prefix; the app realm uses {@code runway_td_app}, a tenant uses {@code runway_td_site_<siteId>}. */
|
||||
private static final String COOKIE_PREFIX = "runway_td_";
|
||||
private static final int MIN_DAYS = 1;
|
||||
private static final int MAX_DAYS = 365;
|
||||
|
||||
private final ProtectionProperties properties;
|
||||
private final ProtectionConfigStore configStore;
|
||||
private final SecretCipher cipher;
|
||||
|
||||
public TrustedDeviceService(ProtectionProperties properties, ProtectionConfigStore configStore,
|
||||
SecretCipher cipher) {
|
||||
this.properties = properties;
|
||||
this.configStore = configStore;
|
||||
this.cipher = cipher;
|
||||
}
|
||||
|
||||
/** Whether the feature is usable at all: enabled by config AND a master key is configured to sign the cookie. */
|
||||
public boolean isEnabled() {
|
||||
return properties.getRememberDevice().isEnabled() && cipher.isAvailable();
|
||||
}
|
||||
|
||||
/** The configured trust window, clamped to a sane range. */
|
||||
public int rememberDays() {
|
||||
int days = properties.getRememberDevice().getDays();
|
||||
return Math.max(MIN_DAYS, Math.min(MAX_DAYS, days));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void rememberIfRequested(HttpServletRequest request, HttpServletResponse response, ProtectionScope scope) {
|
||||
if (!isEnabled() || unscopedTenant(scope)) {
|
||||
return;
|
||||
}
|
||||
if (request.getParameter(REMEMBER_PARAM) == null) {
|
||||
return; // the "remember this device" box was not ticked
|
||||
}
|
||||
// Only mint a cookie when the scope actually has a CAPTCHA to skip — otherwise it would do nothing.
|
||||
if (!configStore.resolve(scope).captcha().active()) {
|
||||
return;
|
||||
}
|
||||
long expiry = System.currentTimeMillis() + (long) rememberDays() * 86_400_000L;
|
||||
String sealed;
|
||||
try {
|
||||
sealed = cipher.encrypt(scope.realm().name() + '|' + siteIdOf(scope) + '|' + expiry);
|
||||
} catch (RuntimeException e) {
|
||||
return; // cipher fault — degrade to no cookie (CAPTCHA stays shown)
|
||||
}
|
||||
ResponseCookie cookie = ResponseCookie.from(cookieName(scope), sealed)
|
||||
.path("/")
|
||||
.httpOnly(true)
|
||||
.secure(request.isSecure())
|
||||
.sameSite("Lax")
|
||||
.maxAge(Duration.ofDays(rememberDays()))
|
||||
.build();
|
||||
response.addHeader(HttpHeaders.SET_COOKIE, cookie.toString());
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether THIS request carries a valid trusted-device cookie for {@code scope} (so the CAPTCHA may be skipped).
|
||||
* Fail-safe: any absence/forgery/tamper/scope-mismatch/expiry returns {@code false} (CAPTCHA shown).
|
||||
*/
|
||||
public boolean isTrusted(HttpServletRequest request, ProtectionScope scope) {
|
||||
if (!isEnabled() || unscopedTenant(scope)) {
|
||||
return false;
|
||||
}
|
||||
String raw = readCookie(request, cookieName(scope));
|
||||
// Reject a value that is not our sealed ENC(...) form: SecretCipher.decrypt passes a non-tagged value
|
||||
// through unchanged, so without this a client could forge a plaintext "APPLICATION||<future>" cookie.
|
||||
if (raw == null || !cipher.isEncrypted(raw)) {
|
||||
return false;
|
||||
}
|
||||
String payload;
|
||||
try {
|
||||
payload = cipher.decrypt(raw); // GCM auth failure on any tamper ⇒ throws
|
||||
} catch (RuntimeException e) {
|
||||
return false;
|
||||
}
|
||||
String[] parts = payload.split("\\|", 3);
|
||||
if (parts.length != 3
|
||||
|| !parts[0].equals(scope.realm().name())
|
||||
|| !parts[1].equals(siteIdOf(scope))) {
|
||||
return false;
|
||||
}
|
||||
try {
|
||||
return Long.parseLong(parts[2]) > System.currentTimeMillis();
|
||||
} catch (NumberFormatException e) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/** A tenant scope with no resolved site can't be keyed safely — decline to issue/trust. */
|
||||
private static boolean unscopedTenant(ProtectionScope scope) {
|
||||
return scope.realm() == ProtectionScope.Realm.TENANT && scope.resolvedSiteId().isEmpty();
|
||||
}
|
||||
|
||||
private static String siteIdOf(ProtectionScope scope) {
|
||||
return scope.siteId() == null ? "" : scope.siteId();
|
||||
}
|
||||
|
||||
private static String cookieName(ProtectionScope scope) {
|
||||
// Disjoint namespaces: the app realm is the fixed "app"; a tenant is "site_<id>". A site id cannot be
|
||||
// "app" after the "site_" prefix, so a tenant whose id is literally "app" can no longer collide with the
|
||||
// app-realm cookie on a shared host (they'd otherwise overwrite each other — a cross-realm papercut, though
|
||||
// the payload realm binding already prevents any actual cross-realm trust).
|
||||
return COOKIE_PREFIX + (scope.realm() == ProtectionScope.Realm.APPLICATION ? "app" : "site_" + scope.siteId());
|
||||
}
|
||||
|
||||
private static String readCookie(HttpServletRequest request, String name) {
|
||||
Cookie[] cookies = request.getCookies();
|
||||
if (cookies == null) {
|
||||
return null;
|
||||
}
|
||||
for (Cookie cookie : cookies) {
|
||||
if (name.equals(cookie.getName())) {
|
||||
return cookie.getValue();
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
+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");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
<!-- App-realm Essential Protection panel — rendered BELOW the generic (rate-limit) settings form on
|
||||
/__app/plugins/protection/settings, and ONLY there (a realm-scoped admin-app fragment: the app plugin-settings
|
||||
page keys off this file, never the tenant-oriented admin.html, so app-level login config never leaks into a
|
||||
tenant console). Bare fragment; binding in admin-app.th.xml via ${@appProtectionPanel.*}. Immediate apply — the
|
||||
form POSTs to /__app/protection and the login gate/form guard read the new values on the next login, no restart. -->
|
||||
<div class="card mt-3" id="pr-panel">
|
||||
<div class="card-header"><h3 class="card-title" id="pr-heading">Login protection</h3></div>
|
||||
<div class="card-body">
|
||||
<div class="text-secondary mb-3" id="pr-intro-text">These settings govern the operator login. Changes apply
|
||||
immediately — the next login attempt is evaluated against them, with no restart.</div>
|
||||
|
||||
<div class="alert alert-warning" id="pr-nocipher" role="alert">
|
||||
<span id="pr-nocipher-text">No encryption key is configured, so a captcha secret cannot be stored.
|
||||
Configure runway.security.secret-key to enable it.</span>
|
||||
</div>
|
||||
|
||||
<form method="post" action="/__app/protection">
|
||||
<input id="pr-csrf" type="hidden" name="_csrf" value="">
|
||||
|
||||
<h4 class="mt-1 mb-2" id="pr-l-honeypot-card">Deterrents</h4>
|
||||
<label class="form-check form-switch mb-1">
|
||||
<input id="pr-honeypot" class="form-check-input" type="checkbox" name="honeypotEnabled" value="true">
|
||||
<span class="form-check-label" id="pr-honeypot-lbl">Enable the hidden honeypot field</span>
|
||||
</label>
|
||||
<small class="form-hint d-block mb-4" id="pr-honeypot-hint">A trap field a human never fills; a bot that
|
||||
fills it is rejected.</small>
|
||||
|
||||
<h4 class="mb-2" id="pr-l-lockout-card">Per-IP lockout</h4>
|
||||
<div class="mb-3">
|
||||
<label class="form-label" id="pr-l-attempts" for="pr-attempts">Max attempts</label>
|
||||
<input class="form-control" id="pr-attempts" name="maxAttempts" type="number" min="1" value="">
|
||||
<small class="form-hint" id="pr-h-attempts">Failed logins within the window before the IP is locked.</small>
|
||||
</div>
|
||||
<div class="mb-3">
|
||||
<label class="form-label" id="pr-l-window" for="pr-window">Window (seconds)</label>
|
||||
<input class="form-control" id="pr-window" name="windowSeconds" type="number" min="1" value="">
|
||||
<small class="form-hint" id="pr-h-window">The sliding window over which failures accumulate.</small>
|
||||
</div>
|
||||
<div class="mb-4">
|
||||
<label class="form-label" id="pr-l-lockout" for="pr-lockout">Lockout (seconds)</label>
|
||||
<input class="form-control" id="pr-lockout" name="lockoutSeconds" type="number" min="1" value="">
|
||||
<small class="form-hint" id="pr-h-lockout">How long an IP stays locked once the threshold is reached.</small>
|
||||
</div>
|
||||
|
||||
<h4 class="mb-2" id="pr-l-captcha-card">External CAPTCHA</h4>
|
||||
<label class="form-check form-switch mb-3">
|
||||
<input id="pr-captcha" class="form-check-input" type="checkbox" name="captchaEnabled" value="true">
|
||||
<span class="form-check-label" id="pr-captcha-lbl">Require a CAPTCHA challenge</span>
|
||||
</label>
|
||||
<div class="mb-3">
|
||||
<label class="form-label" id="pr-l-provider" for="pr-provider">Provider</label>
|
||||
<select id="pr-provider" name="provider" class="form-select">
|
||||
<option id="pr-provider-opt" value="">provider</option>
|
||||
</select>
|
||||
</div>
|
||||
<div class="mb-3">
|
||||
<label class="form-label" id="pr-l-siteKey" for="pr-siteKey">Site key (public)</label>
|
||||
<input class="form-control" id="pr-siteKey" name="siteKey" type="text" value="">
|
||||
<small class="form-hint" id="pr-h-siteKey">The public site key rendered into the challenge widget.</small>
|
||||
</div>
|
||||
<div class="mb-3">
|
||||
<label class="form-label" id="pr-l-secretKey" for="pr-secretKey">Secret key</label>
|
||||
<input class="form-control" id="pr-secretKey" name="secretKey" type="password" value="" autocomplete="off">
|
||||
<small class="form-hint" id="pr-h-secretKey">Verified server-side, stored encrypted. Leave blank to
|
||||
keep the current secret.</small>
|
||||
</div>
|
||||
<div class="mb-4">
|
||||
<label class="form-label" id="pr-l-score" for="pr-score">Score threshold (reCAPTCHA v3)</label>
|
||||
<input class="form-control" id="pr-score" name="scoreThreshold" type="number" min="0" max="1"
|
||||
step="0.05" value="">
|
||||
<small class="form-hint" id="pr-h-score">The minimum score a v3 response must meet (0.0–1.0).</small>
|
||||
</div>
|
||||
|
||||
<button type="submit" class="btn btn-primary" id="pr-save">Save</button>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
@@ -0,0 +1,57 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!--
|
||||
App-realm Essential Protection panel logic. This fragment renders on the KERNEL-owned plugin settings page
|
||||
(/__app/plugins/protection/settings), which does not populate the plugin's model — so every field pre-fills from
|
||||
the plugin's own bean via ${@appProtectionPanel.*} (not controller-set attributes). The captcha SECRET is never
|
||||
written into the input (value stays empty); a "configured" placeholder is shown, and a blank submit keeps it. The
|
||||
_csrf token comes from the enclosing page. ids are global selectors, so `/` vs `//` doesn't apply.
|
||||
-->
|
||||
<thlogic>
|
||||
<attr sel="#pr-heading" th:text="#{protection.screen.heading}"/>
|
||||
<attr sel="#pr-intro-text" th:text="#{protection.screen.app.intro}"/>
|
||||
|
||||
<!-- The "no encryption key" hint is REMOVED when a cipher is available (so the alert only shows when needed). -->
|
||||
<attr sel="#pr-nocipher" th:if="${!@appProtectionPanel.secretStorable()}"/>
|
||||
<attr sel="#pr-nocipher-text" th:text="#{protection.screen.noCipher}"/>
|
||||
|
||||
<attr sel="#pr-csrf"
|
||||
th:attr="name=${_csrf != null ? _csrf.parameterName : '_csrf'},value=${_csrf != null ? _csrf.token : ''}"/>
|
||||
|
||||
<attr sel="#pr-l-honeypot-card" th:text="#{protection.screen.deterrents}"/>
|
||||
<attr sel="#pr-honeypot" th:checked="${@appProtectionPanel.honeypotEnabled()}"/>
|
||||
<attr sel="#pr-honeypot-lbl" th:text="#{protection.screen.honeypot}"/>
|
||||
<attr sel="#pr-honeypot-hint" th:text="#{protection.screen.honeypot.hint}"/>
|
||||
|
||||
<attr sel="#pr-l-lockout-card" th:text="#{protection.screen.lockout}"/>
|
||||
<attr sel="#pr-l-attempts" th:text="#{protection.screen.attempts}"/>
|
||||
<attr sel="#pr-attempts" th:value="${@appProtectionPanel.maxAttempts()}"/>
|
||||
<attr sel="#pr-h-attempts" th:text="#{protection.screen.attempts.hint}"/>
|
||||
<attr sel="#pr-l-window" th:text="#{protection.screen.window}"/>
|
||||
<attr sel="#pr-window" th:value="${@appProtectionPanel.windowSeconds()}"/>
|
||||
<attr sel="#pr-h-window" th:text="#{protection.screen.window.hint}"/>
|
||||
<attr sel="#pr-l-lockout" th:text="#{protection.screen.lockoutSecs}"/>
|
||||
<attr sel="#pr-lockout" th:value="${@appProtectionPanel.lockoutSeconds()}"/>
|
||||
<attr sel="#pr-h-lockout" th:text="#{protection.screen.lockoutSecs.hint}"/>
|
||||
|
||||
<attr sel="#pr-l-captcha-card" th:text="#{protection.screen.captcha}"/>
|
||||
<attr sel="#pr-captcha" th:checked="${@appProtectionPanel.captchaEnabled()}"/>
|
||||
<attr sel="#pr-captcha-lbl" th:text="#{protection.screen.captcha.enable}"/>
|
||||
<attr sel="#pr-l-provider" th:text="#{protection.screen.provider}"/>
|
||||
<attr sel="#pr-provider-opt" th:each="p : ${@appProtectionPanel.providers()}" th:value="${p}" th:id="${null}"
|
||||
th:text="#{'protection.screen.provider.' + ${p}}" th:selected="${p == @appProtectionPanel.provider()}"/>
|
||||
<attr sel="#pr-l-siteKey" th:text="#{protection.screen.siteKey}"/>
|
||||
<attr sel="#pr-siteKey" th:value="${@appProtectionPanel.siteKey()}"/>
|
||||
<attr sel="#pr-h-siteKey" th:text="#{protection.screen.siteKey.hint}"/>
|
||||
<attr sel="#pr-l-secretKey" th:text="#{protection.screen.secretKey}"/>
|
||||
<!-- The secret is MASKED: no value ever goes into the input. The placeholder tells the operator whether one is
|
||||
stored; leaving the field blank on submit keeps it. Dedicated th:placeholder (not th:attr — th:attr forbids
|
||||
@bean access in its restricted context, pitfall). -->
|
||||
<attr sel="#pr-secretKey"
|
||||
th:placeholder="${@appProtectionPanel.secretConfigured()} ? #{protection.screen.secretKey.set} : #{protection.screen.secretKey.unset}"/>
|
||||
<attr sel="#pr-h-secretKey" th:text="#{protection.screen.secretKey.hint}"/>
|
||||
<attr sel="#pr-l-score" th:text="#{protection.screen.score}"/>
|
||||
<attr sel="#pr-score" th:value="${@appProtectionPanel.scoreThreshold()}"/>
|
||||
<attr sel="#pr-h-score" th:text="#{protection.screen.score.hint}"/>
|
||||
|
||||
<attr sel="#pr-save" th:text="#{protection.screen.save}"/>
|
||||
</thlogic>
|
||||
@@ -0,0 +1,144 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head><meta charset="utf-8"><title>DoS activity</title></head>
|
||||
<body>
|
||||
<div id="content">
|
||||
<div class="page-header d-print-none mb-3">
|
||||
<div class="row align-items-center">
|
||||
<div class="col">
|
||||
<div class="page-pretitle" id="dos-pretitle">Application</div>
|
||||
<h2 class="page-title" id="dos-heading">DoS activity</h2>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="alert alert-info" id="dos-intro" role="alert">
|
||||
<div class="text-secondary" id="dos-intro-text">The platform-wide abuse floor. Offenders are IPs the
|
||||
rate limiter is throttling; blocked IPs are turned away before the login. Manual blocks survive a
|
||||
restart; auto blocks expire on their own.</div>
|
||||
</div>
|
||||
|
||||
<!-- Manual block form -->
|
||||
<div class="card mb-3">
|
||||
<div class="card-header"><h3 class="card-title" id="dos-l-block-card">Block an address</h3></div>
|
||||
<div class="card-body">
|
||||
<form method="post" action="/__app/dos/block">
|
||||
<input id="dos-block-csrf" type="hidden" name="_csrf" value="">
|
||||
<div class="row">
|
||||
<div class="col-md-4 mb-2">
|
||||
<label class="form-label" id="dos-l-ip" for="dos-ip">IP or CIDR</label>
|
||||
<input class="form-control" id="dos-ip" name="ip" type="text" placeholder="203.0.113.7" required>
|
||||
</div>
|
||||
<div class="col-md-4 mb-2">
|
||||
<label class="form-label" id="dos-l-reason" for="dos-reason">Reason</label>
|
||||
<input class="form-control" id="dos-reason" name="reason" type="text">
|
||||
</div>
|
||||
<div class="col-md-4 mb-2">
|
||||
<label class="form-label" id="dos-l-seconds" for="dos-seconds">Duration (seconds)</label>
|
||||
<input class="form-control" id="dos-seconds" name="seconds" type="number" min="0" value="900">
|
||||
<small class="form-hint" id="dos-h-seconds">0 blocks indefinitely.</small>
|
||||
</div>
|
||||
</div>
|
||||
<button type="submit" class="btn btn-danger" id="dos-block-submit">Block</button>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Current blocklist -->
|
||||
<div class="card mb-3">
|
||||
<div class="card-header"><h3 class="card-title" id="dos-l-blocks-card">Blocked addresses</h3></div>
|
||||
<div class="card-body">
|
||||
<p class="text-secondary" id="dos-blocks-empty">No addresses are currently blocked.</p>
|
||||
<div class="table-responsive">
|
||||
<table class="table" data-listing-table="runway.app.dos.blocks">
|
||||
<thead>
|
||||
<tr>
|
||||
<th scope="col" id="dos-th-b-ip">IP / CIDR</th>
|
||||
<th scope="col" id="dos-th-b-reason">Reason</th>
|
||||
<th scope="col" id="dos-th-b-source">Source</th>
|
||||
<th scope="col" id="dos-th-b-until">Expires</th>
|
||||
<th scope="col" id="dos-th-b-actions" data-nosort>Actions</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr id="block-row">
|
||||
<td class="br-ip">ip</td>
|
||||
<td class="br-reason">reason</td>
|
||||
<td class="br-source">source</td>
|
||||
<td class="br-until">until</td>
|
||||
<td>
|
||||
<form class="br-unblock-form" method="post" action="/__app/dos/unblock">
|
||||
<input class="br-unblock-csrf" type="hidden" name="_csrf" value="">
|
||||
<input class="br-unblock-ip" type="hidden" name="ip" value="">
|
||||
<button type="submit" class="btn btn-sm btn-outline-secondary br-unblock">Unblock</button>
|
||||
</form>
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Blocks that have ended -->
|
||||
<div class="card mb-3">
|
||||
<div class="card-header"><h3 class="card-title" id="dos-l-ended-card">Recently ended blocks</h3></div>
|
||||
<div class="card-body">
|
||||
<p class="text-secondary" id="dos-ended-hint">Blocks that have expired or been lifted since this
|
||||
server started. Kept in memory only (newest 100), so this list empties on restart — the
|
||||
<code>runway.protect</code> log is the durable record.</p>
|
||||
<p class="text-secondary" id="dos-ended-empty">No blocks have ended yet.</p>
|
||||
<div class="table-responsive">
|
||||
<table class="table" data-listing-table="runway.app.dos.ended">
|
||||
<thead>
|
||||
<tr>
|
||||
<th scope="col" id="dos-th-e-ip">IP / CIDR</th>
|
||||
<th scope="col" id="dos-th-e-reason">Reason</th>
|
||||
<th scope="col" id="dos-th-e-source">Source</th>
|
||||
<th scope="col" id="dos-th-e-ended">Ended</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr id="ended-row">
|
||||
<td class="er-ip">ip</td>
|
||||
<td class="er-reason">reason</td>
|
||||
<td class="er-source">source</td>
|
||||
<td class="er-ended">ended</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Rate-limit offenders -->
|
||||
<div class="card mb-3">
|
||||
<div class="card-header"><h3 class="card-title" id="dos-l-offenders-card">Rate-limit offenders</h3></div>
|
||||
<div class="card-body">
|
||||
<p class="text-secondary" id="dos-offenders-empty">No offenders yet — the rate limiter is not throttling
|
||||
anyone.</p>
|
||||
<div class="table-responsive">
|
||||
<table class="table" data-listing-table="runway.app.dos.offenders">
|
||||
<thead>
|
||||
<tr>
|
||||
<th scope="col" id="dos-th-o-ip">IP</th>
|
||||
<th scope="col" id="dos-th-o-requests">Requests</th>
|
||||
<th scope="col" id="dos-th-o-throttled">Throttled (429)</th>
|
||||
<th scope="col" id="dos-th-o-blocked">Blocked</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr id="offender-row">
|
||||
<td class="or-ip">ip</td>
|
||||
<td class="or-requests" data-sort="0">requests</td>
|
||||
<td class="or-throttled" data-sort="0">throttled</td>
|
||||
<td class="or-blocked">blocked</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,70 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!--
|
||||
App-realm DoS activity screen logic. The blocklist rows repeat over ${blocks} and the offender rows over
|
||||
${offenders}; each empty-state <p> is shown only when its list is empty (an empty list renders zero rows, so
|
||||
no dead row sits in the tbody). Nested cells inside a repeated <tr> are reached with `//` (a `/`
|
||||
child selector matches nothing once a cell wraps a control). id selectors are global; class selectors inside
|
||||
the loop are parent-scoped with `//` so the loop variable stays in scope.
|
||||
-->
|
||||
<thlogic>
|
||||
<attr sel="#dos-pretitle" th:text="#{op.realm.application}"/>
|
||||
<attr sel="#dos-heading" th:text="#{dos.screen.heading}"/>
|
||||
<attr sel="#dos-intro-text" th:text="#{dos.screen.intro}"/>
|
||||
|
||||
<!-- Manual block form -->
|
||||
<attr sel="#dos-l-block-card" th:text="#{dos.block.card}"/>
|
||||
<attr sel="#dos-block-csrf"
|
||||
th:attr="name=${_csrf != null ? _csrf.parameterName : '_csrf'},value=${_csrf != null ? _csrf.token : ''}"/>
|
||||
<attr sel="#dos-l-ip" th:text="#{dos.block.ip}"/>
|
||||
<attr sel="#dos-l-reason" th:text="#{dos.block.reason}"/>
|
||||
<attr sel="#dos-l-seconds" th:text="#{dos.block.seconds}"/>
|
||||
<attr sel="#dos-h-seconds" th:text="#{dos.block.seconds.hint}"/>
|
||||
<attr sel="#dos-block-submit" th:text="#{dos.block.submit}"/>
|
||||
|
||||
<!-- Blocklist table -->
|
||||
<attr sel="#dos-l-blocks-card" th:text="#{dos.blocks.card}"/>
|
||||
<attr sel="#dos-blocks-empty" th:if="${blocks.isEmpty()}" th:text="#{dos.blocks.empty}"/>
|
||||
<attr sel="#dos-th-b-ip" th:text="#{dos.col.ip}"/>
|
||||
<attr sel="#dos-th-b-reason" th:text="#{dos.col.reason}"/>
|
||||
<attr sel="#dos-th-b-source" th:text="#{dos.col.source}"/>
|
||||
<attr sel="#dos-th-b-until" th:text="#{dos.col.until}"/>
|
||||
<attr sel="#dos-th-b-actions" th:text="#{dos.col.actions}"/>
|
||||
|
||||
<attr sel="#block-row" th:each="b : ${blocks}" th:id="${null}"/>
|
||||
<attr sel="#block-row//.br-ip" th:text="${b.ip()}"/>
|
||||
<attr sel="#block-row//.br-reason" th:text="${b.reason()}"/>
|
||||
<attr sel="#block-row//.br-source" th:text="${b.source()}"/>
|
||||
<attr sel="#block-row//.br-until" th:text="${b.until()}"/>
|
||||
<attr sel="#block-row//.br-unblock-csrf"
|
||||
th:attr="name=${_csrf != null ? _csrf.parameterName : '_csrf'},value=${_csrf != null ? _csrf.token : ''}"/>
|
||||
<attr sel="#block-row//.br-unblock-ip" th:attr="value=${b.ip()}"/>
|
||||
<attr sel="#block-row//.br-unblock" th:text="#{dos.unblock}"/>
|
||||
|
||||
<!-- Offenders table -->
|
||||
<attr sel="#dos-l-ended-card" th:text="#{dos.ended.card}"/>
|
||||
<attr sel="#dos-ended-hint" th:text="#{dos.ended.hint}"/>
|
||||
<attr sel="#dos-ended-empty" th:if="${ended.isEmpty()}" th:text="#{dos.ended.empty}"/>
|
||||
<attr sel="#dos-th-e-ip" th:text="#{dos.th.ended.ip}"/>
|
||||
<attr sel="#dos-th-e-reason" th:text="#{dos.th.ended.reason}"/>
|
||||
<attr sel="#dos-th-e-source" th:text="#{dos.th.ended.source}"/>
|
||||
<attr sel="#dos-th-e-ended" th:text="#{dos.th.ended.ended}"/>
|
||||
<attr sel="#ended-row" th:each="e : ${ended}" th:id="${null}"/>
|
||||
<attr sel="#ended-row//.er-ip" th:text="${e.ip()}"/>
|
||||
<attr sel="#ended-row//.er-reason" th:text="${e.reason()}"/>
|
||||
<attr sel="#ended-row//.er-source" th:text="${e.source()}"/>
|
||||
<attr sel="#ended-row//.er-ended" th:text="${e.endedAt()}"/>
|
||||
|
||||
<attr sel="#dos-l-offenders-card" th:text="#{dos.offenders.card}"/>
|
||||
<attr sel="#dos-offenders-empty" th:if="${offenders.isEmpty()}" th:text="#{dos.offenders.empty}"/>
|
||||
<attr sel="#dos-th-o-ip" th:text="#{dos.col.ip}"/>
|
||||
<attr sel="#dos-th-o-requests" th:text="#{dos.col.requests}"/>
|
||||
<attr sel="#dos-th-o-throttled" th:text="#{dos.col.throttled}"/>
|
||||
<attr sel="#dos-th-o-blocked" th:text="#{dos.col.blocked}"/>
|
||||
|
||||
<attr sel="#offender-row" th:each="o : ${offenders}" th:id="${null}"/>
|
||||
<attr sel="#offender-row//.or-ip" th:text="${o.ip()}"/>
|
||||
<attr sel="#offender-row//.or-requests" th:text="${o.requests()}" th:attr="data-sort=${o.requests()}"/>
|
||||
<attr sel="#offender-row//.or-throttled" th:text="${o.throttled()}" th:attr="data-sort=${o.throttled()}"/>
|
||||
<attr sel="#offender-row//.or-blocked"
|
||||
th:text="${o.blocked()} ? #{dos.yes} : #{dos.no}"/>
|
||||
</thlogic>
|
||||
@@ -0,0 +1,77 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head><meta charset="utf-8"><title>Protection</title></head>
|
||||
<body>
|
||||
<div id="content">
|
||||
<div class="page-header d-print-none mb-3">
|
||||
<div class="row align-items-center">
|
||||
<div class="col">
|
||||
<div class="page-pretitle" id="pr-pretitle">Site</div>
|
||||
<h2 class="page-title" id="pr-heading">Login protection</h2>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="alert alert-info" id="pr-intro" role="alert">
|
||||
<div class="text-secondary" id="pr-intro-text">These settings govern this site's login. Changes apply
|
||||
immediately, and affect only this site.</div>
|
||||
</div>
|
||||
|
||||
<div class="alert alert-warning" id="pr-nocipher" role="alert">
|
||||
<span id="pr-nocipher-text">No encryption key is configured, so a captcha secret cannot be stored.
|
||||
Configure runway.security.secret-key to enable it.</span>
|
||||
</div>
|
||||
|
||||
<form method="post" action="/__admin/protection">
|
||||
<input id="pr-csrf" type="hidden" name="_csrf" value="">
|
||||
|
||||
<div class="card mb-3">
|
||||
<div class="card-header"><h3 class="card-title" id="pr-l-honeypot-card">Deterrents</h3></div>
|
||||
<div class="card-body">
|
||||
<label class="form-check form-switch">
|
||||
<input id="pr-honeypot" class="form-check-input" type="checkbox" name="honeypotEnabled" value="true">
|
||||
<span class="form-check-label" id="pr-honeypot-lbl">Enable the hidden honeypot field</span>
|
||||
</label>
|
||||
<small class="form-hint" id="pr-honeypot-hint">A trap field a human never fills; a bot that fills
|
||||
it is rejected.</small>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="card mb-3">
|
||||
<div class="card-header"><h3 class="card-title" id="pr-l-captcha-card">External CAPTCHA</h3></div>
|
||||
<div class="card-body">
|
||||
<label class="form-check form-switch mb-3">
|
||||
<input id="pr-captcha" class="form-check-input" type="checkbox" name="captchaEnabled" value="true">
|
||||
<span class="form-check-label" id="pr-captcha-lbl">Require a CAPTCHA challenge</span>
|
||||
</label>
|
||||
<div class="mb-3">
|
||||
<label class="form-label" id="pr-l-provider" for="pr-provider">Provider</label>
|
||||
<select id="pr-provider" name="provider" class="form-select">
|
||||
<option id="pr-provider-opt" value="">provider</option>
|
||||
</select>
|
||||
</div>
|
||||
<div class="mb-3">
|
||||
<label class="form-label" id="pr-l-siteKey" for="pr-siteKey">Site key (public)</label>
|
||||
<input class="form-control" id="pr-siteKey" name="siteKey" type="text" value="">
|
||||
<small class="form-hint" id="pr-h-siteKey">The public site key rendered into the challenge widget.</small>
|
||||
</div>
|
||||
<div class="mb-3">
|
||||
<label class="form-label" id="pr-l-secretKey" for="pr-secretKey">Secret key</label>
|
||||
<input class="form-control" id="pr-secretKey" name="secretKey" type="password" value="" autocomplete="off">
|
||||
<small class="form-hint" id="pr-h-secretKey">Verified server-side, stored encrypted. Leave blank
|
||||
to keep the current secret.</small>
|
||||
</div>
|
||||
<div class="mb-0">
|
||||
<label class="form-label" id="pr-l-score" for="pr-score">Score threshold (reCAPTCHA v3)</label>
|
||||
<input class="form-control" id="pr-score" name="scoreThreshold" type="number" min="0" max="1"
|
||||
step="0.05" value="">
|
||||
<small class="form-hint" id="pr-h-score">The minimum score a v3 response must meet (0.0–1.0).</small>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<button type="submit" class="btn btn-primary" id="pr-save">Save</button>
|
||||
</form>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,44 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!--
|
||||
Tenant-realm Protection screen logic — honeypot + CAPTCHA over the bound site's per-site ${settings} (a model
|
||||
variable, so its th:attr bindings are fine — the @bean-in-th:attr restriction does not apply here). The per-IP
|
||||
lockout is app-scope only, so it is not shown per-site. The captcha SECRET is never written into the input; a
|
||||
blank submit keeps the stored secret.
|
||||
-->
|
||||
<thlogic>
|
||||
<attr sel="#pr-pretitle" th:text="#{op.realm.tenant}"/>
|
||||
<attr sel="#pr-heading" th:text="#{protection.screen.heading}"/>
|
||||
<attr sel="#pr-intro-text" th:text="#{protection.screen.site.intro}"/>
|
||||
|
||||
<attr sel="#pr-nocipher" th:if="${!captchaSecretStorable}"/>
|
||||
<attr sel="#pr-nocipher-text" th:text="#{protection.screen.noCipher}"/>
|
||||
|
||||
<attr sel="#pr-csrf"
|
||||
th:attr="name=${_csrf != null ? _csrf.parameterName : '_csrf'},value=${_csrf != null ? _csrf.token : ''}"/>
|
||||
|
||||
<attr sel="#pr-l-honeypot-card" th:text="#{protection.screen.deterrents}"/>
|
||||
<attr sel="#pr-honeypot" th:checked="${settings.honeypotEnabled()}"/>
|
||||
<attr sel="#pr-honeypot-lbl" th:text="#{protection.screen.honeypot}"/>
|
||||
<attr sel="#pr-honeypot-hint" th:text="#{protection.screen.honeypot.hint}"/>
|
||||
|
||||
<!-- No per-IP lockout card here: the lockout is an application-scope floor (SlidingWindowLoginGate reads the app
|
||||
settings), so a per-site value would never take effect. Per-site protection is honeypot + CAPTCHA only. -->
|
||||
<attr sel="#pr-l-captcha-card" th:text="#{protection.screen.captcha}"/>
|
||||
<attr sel="#pr-captcha" th:checked="${settings.captcha().enabled()}"/>
|
||||
<attr sel="#pr-captcha-lbl" th:text="#{protection.screen.captcha.enable}"/>
|
||||
<attr sel="#pr-l-provider" th:text="#{protection.screen.provider}"/>
|
||||
<attr sel="#pr-provider-opt" th:each="p : ${providers}" th:value="${p}" th:id="${null}"
|
||||
th:text="#{'protection.screen.provider.' + ${p}}" th:selected="${p == settings.captcha().provider()}"/>
|
||||
<attr sel="#pr-l-siteKey" th:text="#{protection.screen.siteKey}"/>
|
||||
<attr sel="#pr-siteKey" th:attr="value=${settings.captcha().siteKey()}"/>
|
||||
<attr sel="#pr-h-siteKey" th:text="#{protection.screen.siteKey.hint}"/>
|
||||
<attr sel="#pr-l-secretKey" th:text="#{protection.screen.secretKey}"/>
|
||||
<attr sel="#pr-secretKey"
|
||||
th:attr="placeholder=${captchaSecretConfigured} ? #{protection.screen.secretKey.set} : #{protection.screen.secretKey.unset}"/>
|
||||
<attr sel="#pr-h-secretKey" th:text="#{protection.screen.secretKey.hint}"/>
|
||||
<attr sel="#pr-l-score" th:text="#{protection.screen.score}"/>
|
||||
<attr sel="#pr-score" th:attr="value=${settings.captcha().scoreThreshold()}"/>
|
||||
<attr sel="#pr-h-score" th:text="#{protection.screen.score.hint}"/>
|
||||
|
||||
<attr sel="#pr-save" th:text="#{protection.screen.save}"/>
|
||||
</thlogic>
|
||||
Reference in new issue
Block a user