Runway 1.1.0

This commit is contained in:
Runway committed 2026-10-29 09:22:38 -06:00
1 parent ce217fc952
commit 07d5bd7e9a
223 files changed
+21147 -255

No files matched your search

+1 -1
View File
@@ -7,7 +7,7 @@
<parent>
<groupId>mx.quest</groupId>
<artifactId>runway</artifactId>
<version>1.0.1</version>
<version>1.1.0</version>
</parent>
<artifactId>runway-app</artifactId>
@@ -19,6 +19,7 @@ import java.time.format.DateTimeFormatter;
import java.util.Comparator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Objects;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
@@ -259,6 +260,17 @@ public class BackupService {
* @throws IOException if the archive is not a valid Runway backup, is unreadable, or a zip entry escapes
*/
public void restore(String siteId, InputStream in) throws IOException {
restore(siteId, in, false);
}
/**
* Restores {@code siteId} from {@code in}, as {@link #restore(String, InputStream)}; with {@code keepRouting} the
* site keeps the hosts and base URL it has now instead of the archive's. How a site is reached is the platform's
* to set ({@code MANAGE_SITE_HOSTS}), so a site manager's restore never changes it: an archive is theirs to
* write, and the default site's base URL is where the console's reset links go when {@code runway.console.hosts}
* is unset.
*/
public void restore(String siteId, InputStream in, boolean keepRouting) throws IOException {
requireSafe(siteId);
ReentrantLock lock = lockFor(siteId);
// The write scope wraps the lock (HostWriteScope): plugin event callbacks for RESTORED run once the lock is
@@ -266,7 +278,7 @@ public class BackupService {
try (HostWriteScope scope = HostWriteScope.enter()) {
lock.lock();
try {
doRestore(siteId, in);
doRestore(siteId, in, keepRouting);
} finally {
lock.unlock();
}
@@ -282,9 +294,14 @@ public class BackupService {
return lock != null && lock.isHeldByCurrentThread();
}
private void doRestore(String siteId, InputStream in) throws IOException {
private void doRestore(String siteId, InputStream in, boolean keepRouting) throws IOException {
Site live = keepRouting ? sites.find(siteId).orElseThrow(() -> new IOException("no site " + siteId)) : null;
Staged staged = stageAndSwap(siteId, in);
releaseHostsClaimedElsewhere(siteId);
if (live != null) {
keepRouting(siteId, live);
} else {
releaseHostsClaimedElsewhere(siteId);
}
// The on-disk swap is what the caches track — evict + fan out RESTORED NOW, before the (failure-tolerant)
// participant imports, so a participant error can never leave stale caches serving the pre-restore site.
sites.evict(siteId);
@@ -294,6 +311,17 @@ public class BackupService {
log.info("restored site '{}' from backup", siteId);
}
/** Puts the hosts and base URL the site had before the restore back on the restored record. */
private void keepRouting(String siteId, Site live) throws IOException {
sites.evict(siteId);
Site restored = sites.find(siteId).orElseThrow(() -> new IOException("the restored site has no record"));
if (!restored.hosts().equals(live.hosts()) || !Objects.equals(restored.baseUrl(), live.baseUrl())) {
sites.save(restored.withHosts(live.hosts()).withBaseUrl(live.baseUrl()));
log.info("restored site '{}' keeps its hosts and base URL (the backup's were {} and {})", siteId,
restored.hosts(), restored.baseUrl());
}
}
/**
* A backup carries the hosts its site answered on when it was taken. Another site may have been given one of
* them since, and two sites must never answer on one host, so a restore keeps the hosts that are still free and
@@ -666,12 +694,17 @@ public class BackupService {
/** Restores a site from one of its stored backups. */
public void restoreStored(String siteId, String name) throws IOException {
restoreStored(siteId, name, false);
}
/** Restores a site from one of its stored backups; {@code keepRouting} as {@link #restore(String, InputStream, boolean)}. */
public void restoreStored(String siteId, String name, boolean keepRouting) throws IOException {
Path resolved = resolveBackup(siteId, name);
if (resolved == null || !Files.isRegularFile(resolved)) {
throw new IOException("no such backup: " + name);
}
try (InputStream in = Files.newInputStream(resolved)) {
restore(siteId, in);
restore(siteId, in, keepRouting);
}
}
@@ -1,13 +1,15 @@
package mx.quest.runway.console;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
/**
* The application-realm <b>About Runway</b> screen ({@code /__app/about}) — a read-only view of the running
* platform: the version, the curated effective configuration, and the runtime environment of the node serving
* the request. Rendered through the {@code op-layout} operator shell.
* platform: the version, the curated effective configuration, the runtime environment of the node serving
* the request, and that request as Runway sees it (the client address behind a proxy). Rendered through the
* {@code op-layout} operator shell.
*
* <p>Unlike the sibling <b>Platform settings</b> page ({@link AppSettingsController}), About mutates nothing and
* exposes no secret, so it carries <b>no platform-admin gate</b>: the {@code /__app/**} security chain already
@@ -24,12 +26,13 @@ public class AppAboutController {
}
@GetMapping("/__app/about")
public String about(Model model) {
public String about(Model model, HttpServletRequest request) {
model.addAttribute("appVersion", info.version());
model.addAttribute("buildTime", info.buildTime());
model.addAttribute("effectiveConfig", info.effectiveConfig());
model.addAttribute("runtimeInfo", info.runtime());
model.addAttribute("componentInfo", info.components());
model.addAttribute("requestInfo", info.request(request));
model.addAttribute("contentTemplate", "operator/app/about");
model.addAttribute("pageTitleKey", "op.about.title");
return "operator/op-layout";
@@ -1,6 +1,8 @@
package mx.quest.runway.console;
import jakarta.servlet.http.HttpServletRequest;
import mx.quest.runway.mail.PlatformMailer;
import mx.quest.runway.recovery.RecoveryLinks;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
@@ -13,20 +15,23 @@ import org.springframework.web.bind.annotation.GetMapping;
* alerts. Replaces the interim {@code @ResponseBody} login that {@code AppConsoleController} used to serve.
*
* <p>The {@code recoveryEnabled} flag drives the "Forgot your password?" link: it is shown only when the
* platform mail account is configured (there is no way to email a reset link otherwise).
* platform mail account is configured and the console has a known address for the link ({@link RecoveryLinks});
* there is no way to email a usable reset link otherwise.
*/
@Controller
public class AppLoginController {
private final PlatformMailer mailer;
private final RecoveryLinks links;
public AppLoginController(PlatformMailer mailer) {
public AppLoginController(PlatformMailer mailer, RecoveryLinks links) {
this.mailer = mailer;
this.links = links;
}
@GetMapping("/app/login")
public String login(Model model) {
model.addAttribute("recoveryEnabled", mailer.isConfigured());
public String login(Model model, HttpServletRequest request) {
model.addAttribute("recoveryEnabled", mailer.isConfigured() && links.appBase(request).isPresent());
return "operator/login-app";
}
}
@@ -1,16 +1,20 @@
package mx.quest.runway.console;
import jakarta.servlet.http.HttpServletRequest;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Locale;
import java.util.Optional;
import java.util.function.Function;
import mx.quest.runway.recovery.PasswordRecoveryService;
import mx.quest.runway.recovery.RecoveryLinks;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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.support.ServletUriComponentsBuilder;
/**
* The <b>application-realm</b> password-recovery flow — {@code /app/forgot-password} and {@code /app/reset},
@@ -21,17 +25,23 @@ import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
*
* <p>The request path is deliberately <b>non-enumerating</b>: a POST always shows the same neutral
* confirmation, whether or not any account matched.
*
* <p>The emailed link's address comes from {@link RecoveryLinks}, never from the request's host: a request with a
* made-up {@code Host} would otherwise have the platform mail a real user a link to the sender's site.
*/
@Controller
public class AppRecoveryController {
private static final Logger log = LoggerFactory.getLogger(AppRecoveryController.class);
private static final String BRAND = "Runway";
private static final int MIN_PASSWORD_LENGTH = 8;
private final PasswordRecoveryService recovery;
private final RecoveryLinks links;
public AppRecoveryController(PasswordRecoveryService recovery) {
public AppRecoveryController(PasswordRecoveryService recovery, RecoveryLinks links) {
this.recovery = recovery;
this.links = links;
}
@GetMapping("/app/forgot-password")
@@ -42,11 +52,18 @@ public class AppRecoveryController {
}
@PostMapping("/app/forgot-password")
public String requestLink(@RequestParam(required = false) String email, Locale locale) {
String base = ServletUriComponentsBuilder.fromCurrentContextPath().build().toUriString();
Function<String, String> linkFor =
token -> base + "/app/reset?token=" + URLEncoder.encode(token, StandardCharsets.UTF_8);
recovery.requestApp(email, BRAND, linkFor, locale);
public String requestLink(@RequestParam(required = false) String email, Locale locale,
HttpServletRequest request) {
Optional<String> base = links.appBase(request);
if (base.isPresent()) {
Function<String, String> linkFor =
token -> base.get() + "/app/reset?token=" + URLEncoder.encode(token, StandardCharsets.UTF_8);
log.info("password recovery requested on the console; a link, if mailed, points at {}", base.get());
recovery.requestApp(email, BRAND, linkFor, locale);
} else {
log.warn("password recovery requested on a host that is not the console's known address; no link sent "
+ "(set runway.console.hosts, or give the default site a public host name or a base URL)");
}
// Post-redirect-get to the neutral confirmation (no account enumeration, no form re-submit).
return "redirect:/app/forgot-password?sent";
}
@@ -1,9 +1,14 @@
package mx.quest.runway.console;
import jakarta.mail.MessagingException;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicReference;
import mx.quest.runway.crypto.SecretCipher;
import mx.quest.runway.log.AppActivityLog;
import mx.quest.runway.mail.OAuth2TokenClient;
import mx.quest.runway.mail.PlatformMailer;
import mx.quest.runway.platform.HostSettings;
import mx.quest.runway.platform.PlatformSettings;
@@ -40,9 +45,11 @@ import org.springframework.web.servlet.mvc.support.RedirectAttributes;
* <li><b>Response compression</b> — a master switch plus per-encoding Brotli / gzip switches. Applies
* immediately: {@link CompressionFilter} resolves them live per request.</li>
* <li><b>Platform mail (SMTP)</b> — the account used for application-level messages (password recovery, and
* any future operator notifications) for BOTH realms; never for site-generated mail. The password is
* stored {@code ENC(...)}-encrypted ({@link SecretCipher}) and masked on the form (a blank field on save
* keeps the stored secret). A "Send test email" action verifies the account. Applies immediately.</li>
* any future operator notifications) for BOTH realms; never for site-generated mail. It signs in with a
* password or with an OAuth2 token (XOAUTH2, for Microsoft 365). The password and the OAuth2 client secret
* are stored {@code ENC(...)}-encrypted ({@link SecretCipher}) and masked on the form (a blank field on save
* keeps the stored secret). A "Send test email" action verifies the account, and says when the token rather
* than the mail server failed. Applies immediately.</li>
* </ul>
*
* <p>Plus one maintenance action, <b>Clear template cache</b> ({@link #clearTemplateCache}). It sits here rather
@@ -110,6 +117,11 @@ public class AppSettingsController {
@RequestParam(required = false) String smtpFrom,
@RequestParam(name = "smtpStarttls", defaultValue = "false") boolean smtpStarttls,
@RequestParam(name = "smtpSsl", defaultValue = "false") boolean smtpSsl,
@RequestParam(required = false) String smtpAuthMethod,
@RequestParam(required = false) String smtpOauthTokenUrl,
@RequestParam(required = false) String smtpOauthClientId,
@RequestParam(required = false) String smtpOauthClientSecret,
@RequestParam(required = false) String smtpOauthScope,
Authentication authentication, RedirectAttributes redirect) {
platformAuthority.require(authentication);
try {
@@ -121,6 +133,9 @@ public class AppSettingsController {
strength = strength.toUpperCase(Locale.ROOT);
}
String level = strength;
List<String> cleared = new ArrayList<>();
AtomicReference<PlatformSettings> before = new AtomicReference<>();
AtomicReference<PlatformSettings> after = new AtomicReference<>();
// A checkbox submits nothing when unchecked (→ the false default) and its value when checked; so the
// three compression flags are always explicit here — stored as an override the live filter reads.
// A switch the server itself sets is not stored: the host's value wins (one home per setting).
@@ -136,15 +151,26 @@ public class AppSettingsController {
if (site != null && !sites.exists(site)) {
throw new IllegalArgumentException("no such site: " + site);
}
return new PlatformSettings(site, level, normalize(nodeName),
cleared.clear();
PlatformSettings next = new PlatformSettings(site, level, normalize(nodeName),
compressionOverride, brotliOverride, gzipOverride,
smtp(current.smtp(), smtpHost, smtpPort, smtpAuth, smtpUsername, smtpPassword, smtpFrom,
smtpStarttls, smtpSsl),
smtpStarttls, smtpSsl, new OAuthForm(smtpAuthMethod, smtpOauthTokenUrl,
smtpOauthClientId, smtpOauthClientSecret, smtpOauthScope), cleared),
current.settings(), current.siteQuotas(), current.embedHosts(), current.logLevels(),
current.siteStorageCeilings());
before.set(current);
after.set(next);
return next;
});
activity.record(authentication.getName(), "platform.settings-changed", "");
redirect.addFlashAttribute("flash", "Platform settings saved.");
// What changed, by name, never a value: who repointed the mail account, and when, is on the record.
List<String> changed = changedFields(before.get(), after.get());
String detail = String.join(", ", changed)
+ (cleared.isEmpty() ? "" : " (cleared " + String.join(", ", cleared) + ")");
activity.record(authentication.getName(), "platform.settings-changed", detail);
redirect.addFlashAttribute("flash", cleared.isEmpty() ? "Platform settings saved."
: "Platform settings saved. The stored " + String.join(" and ", cleared)
+ " was cleared because the server it is sent to changed: enter it again.");
} catch (IllegalArgumentException invalid) {
redirect.addFlashAttribute("error", invalid.getMessage());
}
@@ -172,6 +198,10 @@ public class AppSettingsController {
+ "used for password recovery and other application messages.");
activity.record(authentication.getName(), "platform.test-email", to);
redirect.addFlashAttribute("flash", "Test email sent to " + to + ".");
} catch (OAuth2TokenClient.TokenException e) {
// Its own message already names the endpoint and the cause; the root cause alone would not say OAuth2.
redirect.addFlashAttribute("error", "Test email failed before reaching the mail server: no OAuth2 token. "
+ e.getMessage());
} catch (MessagingException e) {
redirect.addFlashAttribute("error", "Test email failed: " + rootMessage(e));
}
@@ -196,36 +226,150 @@ public class AppSettingsController {
return "redirect:/__app/settings";
}
/** The OAuth2 sign-in fields of the platform mail form, as submitted. */
private record OAuthForm(String method, String tokenUrl, String clientId, String clientSecret, String scope) {
}
/**
* Builds the SMTP block from the submitted form, encrypting a newly-entered password and <b>preserving</b>
* the stored secret when the password field is left blank (the masked-secret convention). Returns
* Builds the SMTP block from the submitted form, encrypting a newly-entered password or OAuth2 client secret and
* <b>preserving</b> the stored one when its field is left blank (the masked-secret convention). Returns
* {@code null} when nothing is set, so an untouched form does not litter {@code platform.yml} with an
* all-blank block.
*
* <p>An account set to OAuth2 sign-in is checked here, so a mistake is reported on save rather than by the first
* password-recovery mail that fails: it needs TLS (STARTTLS or implicit), a token endpoint Runway will call
* ({@code https}, or {@code http} to loopback), a client ID and a client secret.
*
* <p><b>A stored secret follows its server.</b> Kept on a blank field only while the settings that say where it
* is sent stay the same: the password while host, port and username do, the client secret while the token
* endpoint and client ID do, and, for an OAuth2 account, the mail server (host and port) and the scope the token is
* minted for and sent with. Otherwise someone allowed to edit this screen, who does not know the secret, could
* point the account at a server of theirs and have Runway send it there (the rule plugin settings follow with
* {@code secretBoundTo}). A secret dropped this way is named in {@code cleared}; an OAuth2 account whose client
* secret was dropped is refused, since it cannot sign in without one.
*/
private PlatformSettings.Smtp smtp(PlatformSettings.Smtp current, String host, String port, boolean auth,
String username, String password, String from, boolean starttls,
boolean ssl) {
boolean ssl, OAuthForm oauth, List<String> cleared) {
String h = normalize(host);
String u = normalize(username);
String f = normalize(from);
Integer p = port(port);
String stored = current != null ? current.password() : null;
String secret;
if (normalize(password) == null) {
secret = stored; // blank field ⇒ keep the stored (encrypted) secret
} else {
if (!cipher.isAvailable()) {
throw new IllegalArgumentException("Cannot store an SMTP password: no encryption key is "
+ "configured (set runway.security.secret-key).");
String method = PlatformSettings.Smtp.AUTH_OAUTH2.equals(normalize(oauth.method()))
? PlatformSettings.Smtp.AUTH_OAUTH2 : PlatformSettings.Smtp.AUTH_PASSWORD;
String tokenUrl = normalize(oauth.tokenUrl());
String clientId = normalize(oauth.clientId());
String scope = normalize(oauth.scope());
boolean passwordMoved = current != null && (!sameHost(current.host(), h) || !Objects.equals(current.port(), p)
|| !Objects.equals(normalize(current.username()), u));
// The client secret goes to the token endpoint; the token minted from it goes to the mail server, for the
// scope asked: both follow it. Only for an OAuth2 account, so a password account whose hidden OAuth2 fields
// ride along is not told a secret was cleared when its host moves.
boolean oauthAccount = current != null && (PlatformSettings.Smtp.AUTH_OAUTH2.equals(current.authMethod())
|| PlatformSettings.Smtp.AUTH_OAUTH2.equals(method));
boolean clientSecretMoved = current != null && (!Objects.equals(normalize(current.oauthTokenUrl()), tokenUrl)
|| !Objects.equals(normalize(current.oauthClientId()), clientId)
|| oauthAccount && (!sameHost(current.host(), h) || !Objects.equals(current.port(), p)
|| !Objects.equals(normalize(current.oauthScope()), scope)));
String secret = secret(normalize(password), current != null ? current.password() : null, "an SMTP password",
passwordMoved, "SMTP password", cleared);
String clientSecret = secret(normalize(oauth.clientSecret()),
current != null ? current.oauthClientSecret() : null, "an OAuth2 client secret",
clientSecretMoved, "OAuth2 client secret", cleared);
if (auth && method.equals(PlatformSettings.Smtp.AUTH_OAUTH2)) {
if (cleared.contains("OAuth2 client secret")) {
throw new IllegalArgumentException("Enter the OAuth2 client secret again: the token endpoint, client "
+ "ID, mail server or scope changed, and neither the stored secret nor a token minted from it "
+ "goes to a new one.");
}
if (!starttls && !ssl) {
throw new IllegalArgumentException("OAuth2 sign-in needs STARTTLS or implicit TLS.");
}
try {
// The stored secret stays encrypted; only its presence matters for this check.
OAuth2TokenClient.endpoint(new OAuth2TokenClient.Request(tokenUrl, clientId, clientSecret, scope));
} catch (MessagingException invalid) {
throw new IllegalArgumentException("Platform mail: " + invalid.getMessage() + ".");
}
secret = cipher.encrypt(password.trim());
}
boolean oauthEmpty = tokenUrl == null && clientId == null && clientSecret == null && scope == null;
boolean empty = h == null && f == null && u == null
&& (secret == null || secret.isBlank()) && !auth && !starttls && !ssl && p == null;
&& (secret == null || secret.isBlank()) && !auth && !starttls && !ssl && p == null && oauthEmpty;
if (empty) {
return null;
}
return new PlatformSettings.Smtp(h, p, auth, u, secret, f, starttls, ssl);
return new PlatformSettings.Smtp(h, p, auth, u, secret, f, starttls, ssl, method, tokenUrl, clientId,
clientSecret, scope);
}
/**
* A newly entered secret, encrypted; or, when the field was left blank, the stored ciphertext, unless the server
* it is sent to {@code moved}: then nothing, and {@code name} is added to {@code cleared}.
*/
private String secret(String entered, String stored, String what, boolean moved, String name,
List<String> cleared) {
if (entered == null) {
if (stored == null || stored.isBlank()) {
return null;
}
if (moved) {
cleared.add(name);
return null;
}
return stored; // blank field, same server ⇒ keep the stored secret
}
if (!cipher.isAvailable()) {
throw new IllegalArgumentException("Cannot store " + what + ": no encryption key is "
+ "configured (set runway.security.secret-key).");
}
return cipher.encrypt(entered);
}
private static boolean sameHost(String a, String b) {
String x = normalize(a);
String y = normalize(b);
return x == null ? y == null : y != null && x.equalsIgnoreCase(y);
}
/**
* The names of the settings this save changed (never their values), for the activity log: the platform fields
* this screen owns, and each field of the mail account.
*/
static List<String> changedFields(PlatformSettings before, PlatformSettings after) {
List<String> changed = new ArrayList<>();
if (before == null || after == null) {
return changed;
}
diff(changed, "default site", before.defaultSiteId(), after.defaultSiteId());
diff(changed, "password strength", before.passwordStrength(), after.passwordStrength());
diff(changed, "node name", before.nodeName(), after.nodeName());
diff(changed, "compression", before.compressionEnabled(), after.compressionEnabled());
diff(changed, "brotli", before.brotliEnabled(), after.brotliEnabled());
diff(changed, "gzip", before.gzipEnabled(), after.gzipEnabled());
PlatformSettings.Smtp b = before.smtp();
PlatformSettings.Smtp a = after.smtp();
diff(changed, "mail host", b == null ? null : b.host(), a == null ? null : a.host());
diff(changed, "mail port", b == null ? null : b.port(), a == null ? null : a.port());
diff(changed, "mail sign-in", b == null ? null : b.auth(), a == null ? null : a.auth());
diff(changed, "mail sign-in method", b == null ? null : b.authMethod(), a == null ? null : a.authMethod());
diff(changed, "mail username", b == null ? null : b.username(), a == null ? null : a.username());
diff(changed, "mail password", b == null ? null : b.password(), a == null ? null : a.password());
diff(changed, "mail from", b == null ? null : b.from(), a == null ? null : a.from());
diff(changed, "mail STARTTLS", b == null ? null : b.starttls(), a == null ? null : a.starttls());
diff(changed, "mail TLS", b == null ? null : b.ssl(), a == null ? null : a.ssl());
diff(changed, "OAuth2 token endpoint", b == null ? null : b.oauthTokenUrl(),
a == null ? null : a.oauthTokenUrl());
diff(changed, "OAuth2 client ID", b == null ? null : b.oauthClientId(), a == null ? null : a.oauthClientId());
diff(changed, "OAuth2 client secret", b == null ? null : b.oauthClientSecret(),
a == null ? null : a.oauthClientSecret());
diff(changed, "OAuth2 scope", b == null ? null : b.oauthScope(), a == null ? null : a.oauthScope());
return changed;
}
private static void diff(List<String> changed, String name, Object before, Object after) {
if (!Objects.equals(before, after)) {
changed.add(name);
}
}
private void populate(Model model, PlatformSettings current) {
@@ -257,6 +401,13 @@ public class AppSettingsController {
model.addAttribute("smtpSsl", smtp != null && Boolean.TRUE.equals(smtp.ssl()));
model.addAttribute("smtpPasswordConfigured",
smtp != null && smtp.password() != null && !smtp.password().isBlank());
model.addAttribute("smtpAuthMethod", smtp != null && PlatformSettings.Smtp.AUTH_OAUTH2.equals(smtp.authMethod())
? PlatformSettings.Smtp.AUTH_OAUTH2 : PlatformSettings.Smtp.AUTH_PASSWORD);
model.addAttribute("smtpOauthTokenUrl", smtp != null ? orEmpty(smtp.oauthTokenUrl()) : "");
model.addAttribute("smtpOauthClientId", smtp != null ? orEmpty(smtp.oauthClientId()) : "");
model.addAttribute("smtpOauthScope", smtp != null ? orEmpty(smtp.oauthScope()) : "");
model.addAttribute("smtpOauthSecretConfigured",
smtp != null && smtp.oauthClientSecret() != null && !smtp.oauthClientSecret().isBlank());
model.addAttribute("smtpConfigured", smtp != null && smtp.isConfigured());
}
@@ -1,5 +1,6 @@
package mx.quest.runway.console;
import jakarta.servlet.http.HttpServletRequest;
import java.lang.management.ManagementFactory;
import java.lang.management.RuntimeMXBean;
import java.net.InetAddress;
@@ -22,7 +23,10 @@ import mx.quest.runway.i18n.I18nProperties;
import mx.quest.runway.platform.PlatformSettingsStore;
import mx.quest.runway.security.ActivePasswordStrength;
import mx.quest.runway.storage.StorageLayout;
import mx.quest.runway.web.ClientIp;
import mx.quest.runway.web.CompressionFilter;
import mx.quest.runway.web.ProxyResolution;
import mx.quest.runway.web.RequestOrigin;
import mx.quest.runway.web.RunwayProxyProperties;
import mx.quest.runway.web.RunwayTlsProperties;
import org.springframework.beans.factory.ObjectProvider;
@@ -162,6 +166,30 @@ public class RuntimeInfoService {
}
/** The "Host &amp; JVM" table describing the node serving the request. Row names are {@code op.about.rt.*} keys. */
/**
* The current request as Runway sees it: the connection it came in on, the {@code X-Forwarded-For} chain, the
* client address that rate limits, lockouts and logs use, and the origin. Lets an operator check a reverse-proxy
* setup ({@code runway.proxy.*}) from the browser: behind a correctly trusted proxy the client row shows the
* operator's own public address, not the proxy's. Values are the operator's own request data, nothing secret.
*/
public List<NameValue> request(HttpServletRequest request) {
List<NameValue> rows = new ArrayList<>();
ProxyResolution resolution = ProxyResolution.of(request);
if (resolution == null) {
rows.add(new NameValue("op.about.req.client", ClientIp.of(request)));
} else {
rows.add(new NameValue("op.about.req.peer", resolution.peer() + (resolution.peerTrusted()
? " (trusted proxy)" : " (not a trusted proxy)")));
String chain = resolution.forwardedFor().text();
rows.add(new NameValue("op.about.req.forwardedFor", chain.isEmpty() ? "none"
: resolution.honoured() ? chain : chain + " (ignored)"));
rows.add(new NameValue("op.about.req.client", resolution.clientIp()));
}
String origin = RequestOrigin.of(request);
rows.add(new NameValue("op.about.req.origin", origin.isEmpty() ? "—" : origin));
return rows;
}
public List<NameValue> runtime() {
RuntimeMXBean rb = ManagementFactory.getRuntimeMXBean();
Runtime rt = Runtime.getRuntime();
@@ -271,8 +271,10 @@ public class SitesController {
/**
* Edits a site's routing {@link Site#hosts} from the Sites screen. Gated to the grantable
* {@code MANAGE_SITE_HOSTS} permission by the {@code /__app/sites/*}/{@code hosts} request gate — so it is
* delegable to a role/user and the app master always passes — hence <b>no</b> in-controller
* {@link PlatformAuthority} check, unlike the master-only lifecycle actions. The service normalizes and
* delegable to a role/user and the app master always passes. The <b>default site</b> is the exception: with
* {@code runway.console.hosts} unset, the console's own password-reset links go to its base URL, so whoever sets
* it decides where the platform accounts' reset tokens are mailed; editing it needs a platform admin
* ({@link PlatformAuthority}), like the lifecycle actions. The service normalizes and
* validates the comma-separated hosts and rejects one already owned by another site; failures surface as a
* flash error and the page is redisplayed. The same dialog sets the site's base URL ({@link
* mx.quest.runway.site.SiteBaseUrl}), the origin of its absolute links: it is part of how the site is reached,
@@ -282,6 +284,9 @@ public class SitesController {
public String updateHosts(@PathVariable String id, @RequestParam(required = false) String hosts,
@RequestParam(required = false) String baseUrl,
Authentication authentication, RedirectAttributes redirect) {
if (platform.get().defaultSite().filter(id::equals).isPresent()) {
platformAuthority.require(authentication);
}
try {
// The base URL rides in the same dialog: absent (an older form) keeps it, blank means derived.
if (baseUrl == null) {
@@ -194,7 +194,7 @@ public class TenantBackupsController {
Site site = boundTenancy();
tenantAuthority.require(authentication, site.id());
try {
backups.restoreStored(site.id(), name);
backups.restoreStored(site.id(), name, true); // a site manager never changes how the site is reached
redirect.addFlashAttribute("flash", message("op.backups.restored", "Site restored from the backup."));
} catch (UnsupportedBackupFormatException e) {
redirect.addFlashAttribute("error", newerFormat(e));
@@ -216,7 +216,7 @@ public class TenantBackupsController {
return "redirect:/__admin/backups";
}
try (InputStream in = file.getInputStream()) {
backups.restore(site.id(), in);
backups.restore(site.id(), in, true); // a site manager never changes how the site is reached
redirect.addFlashAttribute("flash", message("op.backups.restored", "Site restored from the backup."));
} catch (UnsupportedBackupFormatException e) {
redirect.addFlashAttribute("error", newerFormat(e));
@@ -3,8 +3,10 @@ package mx.quest.runway.console;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Locale;
import java.util.Optional;
import java.util.function.Function;
import mx.quest.runway.recovery.PasswordRecoveryService;
import mx.quest.runway.recovery.RecoveryLinks;
import mx.quest.runway.site.Site;
import mx.quest.runway.site.SiteResolver;
import org.springframework.stereotype.Controller;
@@ -12,7 +14,8 @@ 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.support.ServletUriComponentsBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* The <b>tenant-realm</b> password-recovery flow — {@code /forgot-password} and {@code /reset}, served on a
@@ -23,18 +26,25 @@ import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
*
* <p>Like the login page, the routes are public; the flow is non-enumerating (a POST always shows the same
* neutral confirmation). All logic lives in {@link PasswordRecoveryService}.
*
* <p>The emailed link points at the site's own base URL ({@link RecoveryLinks}), never at the host the request named:
* an unknown host reaches the default site, and a link built from it would hand the token to whoever sent it.
*/
@Controller
public class TenantRecoveryController {
private static final Logger log = LoggerFactory.getLogger(TenantRecoveryController.class);
private static final int MIN_PASSWORD_LENGTH = 8;
private final PasswordRecoveryService recovery;
private final SiteResolver siteResolver;
private final RecoveryLinks links;
public TenantRecoveryController(PasswordRecoveryService recovery, SiteResolver siteResolver) {
public TenantRecoveryController(PasswordRecoveryService recovery, SiteResolver siteResolver,
RecoveryLinks links) {
this.recovery = recovery;
this.siteResolver = siteResolver;
this.links = links;
}
@GetMapping("/forgot-password")
@@ -46,11 +56,18 @@ public class TenantRecoveryController {
@PostMapping("/forgot-password")
public String requestLink(@RequestParam(required = false) String email, Locale locale) {
String siteId = siteResolver.current().map(Site::id).orElse(null);
String base = ServletUriComponentsBuilder.fromCurrentContextPath().build().toUriString();
Function<String, String> linkFor =
token -> base + "/reset?token=" + URLEncoder.encode(token, StandardCharsets.UTF_8);
recovery.requestTenant(siteId, email, brand(), linkFor, locale);
Optional<Site> site = siteResolver.current();
Optional<String> base = site.flatMap(links::siteBase);
if (base.isPresent()) {
Function<String, String> linkFor =
token -> base.get() + "/reset?token=" + URLEncoder.encode(token, StandardCharsets.UTF_8);
log.info("password recovery requested for site '{}'; a link, if mailed, points at {}", site.get().id(),
base.get());
recovery.requestTenant(site.get().id(), email, brand(), linkFor, locale);
} else {
log.warn("password recovery requested for site '{}', which has no public address to link to (no host "
+ "name, or only localhost and no base URL); no link sent", site.map(Site::id).orElse("?"));
}
return "redirect:/forgot-password?sent";
}
@@ -2,8 +2,11 @@ package mx.quest.runway.crypto;
/**
* Symmetric encryption of stored secrets (AES-256-GCM) in the tagged {@code ENC(<base64>)} form — the kernel
* seam plugins inject to decrypt their {@code secret}-typed settings (which bind as the raw {@code ENC(...)}
* string via {@code @ConfigurationProperties}), and the settings service uses to encrypt them on save.
* service the settings code uses to encrypt {@code secret}-typed settings on save and to decrypt them on read.
* It is <b>kernel-internal</b>: a plugin cannot inject it (host linkage is blocked). A plugin reads its secrets in
* clear through the SPI instead — {@code PluginSettings.secret(siteId, key)} for per-site settings and
* {@code PluginSettings.appSecret(key)} (SPI 1.1.0) for app-level ones, which otherwise bind only in their
* {@code ENC(...)} form.
*
* <p>Encryption is <b>non-deterministic</b> (a fresh GCM nonce each call), so the same plaintext yields a
* different ciphertext every time — never compare secrets by their stored form. The cipher is unavailable
@@ -1,6 +1,7 @@
package mx.quest.runway.log;
import jakarta.servlet.http.HttpServletRequest;
import mx.quest.runway.web.ClientIp;
import mx.quest.runway.web.RequestPaths;
import org.springframework.context.event.EventListener;
import org.springframework.security.authentication.event.AbstractAuthenticationFailureEvent;
@@ -60,9 +61,9 @@ public class AppAuditEventListener {
? attrs.getRequest() : null;
}
/** The best-effort client IP (honors X-Forwarded-For only when the container was told to trust the proxy). */
/** The client IP as {@link ClientIp} resolved it (behind a trusted proxy, the visitor's), or empty. */
private static String clientIp(HttpServletRequest request) {
String ip = request.getRemoteAddr();
String ip = ClientIp.of(request);
return ip == null ? "" : ip;
}
}
@@ -2,6 +2,7 @@ package mx.quest.runway.log;
import jakarta.servlet.http.HttpServletRequest;
import mx.quest.runway.site.SiteResolver;
import mx.quest.runway.web.ClientIp;
import mx.quest.runway.web.RequestPaths;
import org.springframework.context.event.EventListener;
import org.springframework.security.authentication.event.AbstractAuthenticationFailureEvent;
@@ -19,6 +20,11 @@ import org.springframework.web.context.request.ServletRequestAttributes;
* {@code /app/logout}) even when the app console was reached on a host that also resolves to a site: those belong
* to the application activity log ({@link AppAuditEventListener}), and an operator's name must not leak into a
* tenant's journal.
*
* <p>Each line carries the client address ({@code ip=…}) as {@link ClientIp} resolved it, behind a trusted proxy the
* visitor rather than the proxy, so a site's own audit trail answers "who signed in from where" the way the
* application activity log does. The address is kept whole: the site's "anonymize client IP addresses" setting covers
* the access log, not the audit log, which is a security record (a wrong current password is recorded the same way).
*/
@Component
public class AuditEventListener {
@@ -50,15 +56,22 @@ public class AuditEventListener {
if (isAppRealmRequest()) {
return;
}
siteResolver.current().ifPresent(site -> siteLog.audit(site.id(), actor, action, ""));
HttpServletRequest request = currentRequest();
String detail = request == null || ClientIp.of(request) == null ? "" : "ip=" + ClientIp.of(request);
siteResolver.current().ifPresent(site -> siteLog.audit(site.id(), actor, action, detail));
}
private static boolean isAppRealmRequest() {
if (!(RequestContextHolder.getRequestAttributes() instanceof ServletRequestAttributes attrs)) {
HttpServletRequest request = currentRequest();
if (request == null) {
return false;
}
HttpServletRequest request = attrs.getRequest();
String path = RequestPaths.normalized(request);
return AppAuditEventListener.APP_LOGIN_PATH.equals(path) || AppAuditEventListener.APP_LOGOUT_PATH.equals(path);
}
private static HttpServletRequest currentRequest() {
return RequestContextHolder.getRequestAttributes() instanceof ServletRequestAttributes attrs
? attrs.getRequest() : null;
}
}
@@ -0,0 +1,356 @@
package mx.quest.runway.mail;
import jakarta.mail.MessagingException;
import java.io.IOException;
import java.net.InetAddress;
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.Clock;
import java.time.Duration;
import java.time.Instant;
import java.util.Locale;
import java.util.Objects;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import tools.jackson.databind.JsonNode;
import tools.jackson.databind.ObjectMapper;
/**
* Gets the access token the platform mailer signs in to SMTP with when the account uses OAuth2 (SASL
* {@code XOAUTH2}): an OAuth2 <b>client-credentials</b> grant (RFC 6749 §4.4) against the configured token endpoint,
* which is how Microsoft 365 lets an application send through Exchange Online once password SMTP is retired.
*
* <p><b>Caching.</b> A token is reused until shortly before it expires (five minutes, or half its lifetime when that
* is shorter), so a burst of recovery mails costs one token request, not one each. One entry is kept, for the request
* last made: there is one platform account. Changing any part of the request (endpoint, client, secret, scope) asks
* for a new token. {@link #forget()} drops the entry, for when the mail server refused the token.
*
* <p><b>Bounds.</b> The endpoint must be {@code https} (plain {@code http} only to a loopback address, for a local
* identity provider or a test); the connection and the whole exchange, body included, are time-limited, and the
* response is read up to {@value #MAX_RESPONSE_BYTES} bytes. No redirect is followed: a token endpoint that redirects is misconfigured,
* and following it would send the client secret wherever the redirect points.
*
* <p><b>Secrets.</b> The client secret goes only into the form body of the token request. Neither it nor a token is
* logged or put in an exception message; an error names the HTTP status and the provider's own {@code error} and
* {@code error_description} (for Microsoft, the {@code AADSTS…} code that says what to fix).
*
* <p>Thread-safe. Concurrent callers for the same request share one in-flight token request and wait at most until
* its deadline, so a stalled identity provider holds every sender for one deadline, not one each in turn.
*/
@Component
public class OAuth2TokenClient {
/** The longest token response read. Real ones are a few kilobytes. */
static final int MAX_RESPONSE_BYTES = 64 * 1024;
/** How long to wait for the token endpoint to accept the connection. */
static final Duration CONNECT_TIMEOUT = Duration.ofSeconds(10);
/** How long the whole token exchange may take. */
static final Duration REQUEST_TIMEOUT = Duration.ofSeconds(30);
/** How long before expiry a cached token is replaced, at most. */
static final Duration REFRESH_MARGIN = Duration.ofMinutes(5);
/** The lifetime assumed when the response gives none: short, so a wrong guess costs little. */
static final Duration DEFAULT_LIFETIME = Duration.ofMinutes(5);
private static final ObjectMapper MAPPER = new ObjectMapper();
private static final int MAX_ERROR_TEXT = 300;
private final HttpClient http;
private final Clock clock;
private final Duration deadline;
private Cached cached;
/** The token request under way, which callers for the same request join. Guarded by {@code this}. */
private InFlight inFlight;
private record InFlight(Request request, CompletableFuture<String> result, long deadlineNanos) {
}
@Autowired
public OAuth2TokenClient() {
this(httpClient(), Clock.systemUTC());
}
/** The client the application uses: bounded connect, and never a redirect. Package-visible for tests. */
static HttpClient httpClient() {
return HttpClient.newBuilder()
.connectTimeout(CONNECT_TIMEOUT)
.followRedirects(HttpClient.Redirect.NEVER)
.build();
}
OAuth2TokenClient(HttpClient http, Clock clock) {
this(http, clock, REQUEST_TIMEOUT);
}
/** With a shorter deadline for the whole exchange, so a test of a stalled server finishes quickly. */
OAuth2TokenClient(HttpClient http, Clock clock, Duration deadline) {
this.http = http;
this.clock = clock;
this.deadline = deadline;
}
/**
* What to ask the token endpoint for.
*
* @param tokenUrl the token endpoint
* @param clientId the client (application) id
* @param clientSecret the client secret, in clear
* @param scope the scope to request; blank sends none
*/
public record Request(String tokenUrl, String clientId, String clientSecret, String scope) {
/** Never leak the secret in diagnostics. */
@Override
public String toString() {
return "Request[tokenUrl=" + tokenUrl + ", clientId=" + clientId + ", scope=" + scope + "]";
}
}
private record Cached(Request request, String token, Instant renewAt) {
}
/**
* No token: the OAuth2 settings are incomplete or not allowed, or the token endpoint could not be reached or
* refused. A {@link MessagingException}, so every mail caller's handling applies; its own type lets the console
* say that the token, not the mail server, is what failed.
*/
public static final class TokenException extends MessagingException {
TokenException(String message) {
super(message);
}
TokenException(String message, Exception cause) {
super(message, cause);
}
}
/**
* An access token for {@code request}: the cached one while it is still fresh, otherwise a new one.
*
* @throws TokenException when the request is incomplete, the endpoint is not allowed, cannot be reached, or
* does not return a bearer token; the message says which
*/
public String token(Request request) throws TokenException {
CompletableFuture<String> attempt;
long deadlineNanos;
boolean mine = false;
Instant now;
synchronized (this) {
now = clock.instant();
if (cached != null && cached.request().equals(request) && now.isBefore(cached.renewAt())) {
return cached.token();
}
cached = null;
if (inFlight != null && inFlight.request().equals(request)) {
attempt = inFlight.result();
deadlineNanos = inFlight.deadlineNanos();
} else {
attempt = new CompletableFuture<>();
deadlineNanos = System.nanoTime() + deadline.toNanos();
inFlight = new InFlight(request, attempt, deadlineNanos);
mine = true;
}
}
if (mine) {
try {
String token = fetch(request, now);
attempt.complete(token);
return token;
} catch (TokenException | RuntimeException e) {
attempt.completeExceptionally(e);
throw e;
} finally {
synchronized (this) {
if (inFlight != null && inFlight.result() == attempt) {
inFlight = null;
}
}
}
}
// Another caller is already asking: wait for its answer, no longer than its own deadline (plus a moment).
try {
long wait = Math.max(0, deadlineNanos - System.nanoTime()) + TimeUnit.SECONDS.toNanos(1);
return attempt.get(wait, TimeUnit.NANOSECONDS);
} catch (ExecutionException e) {
Throwable cause = e.getCause() == null ? e : e.getCause();
throw new TokenException(cause.getMessage(), cause instanceof Exception ex ? ex : e);
} catch (TimeoutException e) {
throw new TokenException("OAuth2 token request did not complete within " + deadline.toSeconds()
+ " seconds", e);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new TokenException("OAuth2 token request was interrupted", e);
}
}
/** One token request, against the deadline; the token is cached on success. */
private String fetch(Request request, Instant now) throws TokenException {
URI endpoint = endpoint(request);
String form = "grant_type=client_credentials"
+ "&client_id=" + encode(request.clientId())
+ "&client_secret=" + encode(request.clientSecret())
+ (blank(request.scope()) ? "" : "&scope=" + encode(request.scope().strip()));
HttpRequest post = HttpRequest.newBuilder(endpoint)
.timeout(deadline)
.header("Content-Type", "application/x-www-form-urlencoded")
.header("Accept", "application/json")
.POST(HttpRequest.BodyPublishers.ofString(form, StandardCharsets.UTF_8))
.build();
// The request timeout covers only the wait for the response headers; a server that then sends its body a byte
// at a time would hold this call, and every mail sender waiting on it, for as long as it liked. So
// the whole exchange, body included, runs against one deadline, and the body is cut off past the cap.
CompletableFuture<HttpResponse<byte[]>> exchange = http.sendAsync(post,
HttpResponse.BodyHandlers.limiting(HttpResponse.BodyHandlers.ofByteArray(), MAX_RESPONSE_BYTES));
HttpResponse<byte[]> response;
try {
response = exchange.get(deadline.toMillis(), TimeUnit.MILLISECONDS);
} catch (TimeoutException e) {
exchange.cancel(true);
throw new TokenException("OAuth2 token request to " + endpoint.getHost() + " did not complete within "
+ deadline.toSeconds() + " seconds", e);
} catch (ExecutionException e) {
Throwable cause = e.getCause() == null ? e : e.getCause();
if (cause instanceof IOException io && io.getMessage() != null
&& io.getMessage().contains("exceeds capacity")) { // BodyHandlers.limiting
throw new TokenException("OAuth2 token response from " + endpoint.getHost() + " is larger than "
+ MAX_RESPONSE_BYTES + " bytes");
}
throw new TokenException("OAuth2 token request to " + endpoint.getHost() + " failed: " + cause,
cause instanceof Exception ex ? ex : e);
} catch (InterruptedException e) {
exchange.cancel(true);
Thread.currentThread().interrupt();
throw new TokenException("OAuth2 token request to " + endpoint.getHost() + " was interrupted", e);
}
byte[] body = response.body();
JsonNode json = parse(body);
if (response.statusCode() != 200) {
throw new TokenException("OAuth2 token request to " + endpoint.getHost() + " was refused (HTTP "
+ response.statusCode() + ")" + providerError(json));
}
String token = json == null ? null : text(json, "access_token");
if (blank(token)) {
throw new TokenException("OAuth2 token response from " + endpoint.getHost()
+ " has no access_token" + providerError(json));
}
String type = text(json, "token_type");
if (type != null && !type.equalsIgnoreCase("bearer")) {
throw new TokenException("OAuth2 token response from " + endpoint.getHost()
+ " is not a bearer token (token_type " + clip(type) + ")");
}
Duration lifetime = lifetime(json);
Duration margin = lifetime.dividedBy(2).compareTo(REFRESH_MARGIN) < 0 ? lifetime.dividedBy(2) : REFRESH_MARGIN;
synchronized (this) {
cached = new Cached(request, token, now.plus(lifetime).minus(margin));
}
return token;
}
/** Drops the cached token, so the next send asks for a new one (after the mail server refused it). */
public synchronized void forget() {
cached = null;
}
/**
* The token endpoint, checked: complete request, an absolute {@code https} URL, or {@code http} to a loopback
* address. Public so the settings screen can refuse a bad endpoint when it is saved, not at the first send.
*
* @throws TokenException naming what is wrong
*/
public static URI endpoint(Request request) throws TokenException {
if (blank(request.tokenUrl()) || blank(request.clientId()) || blank(request.clientSecret())) {
throw new TokenException("OAuth2 sign-in needs a token endpoint, a client ID and a client secret");
}
URI uri;
try {
uri = new URI(request.tokenUrl().strip());
} catch (java.net.URISyntaxException e) {
throw new TokenException("the OAuth2 token endpoint is not a valid URL");
}
String scheme = uri.getScheme() == null ? "" : uri.getScheme().toLowerCase(Locale.ROOT);
if (uri.getHost() == null || uri.getRawUserInfo() != null || uri.getRawFragment() != null) {
throw new TokenException("the OAuth2 token endpoint must be a plain https URL with a host");
}
if (scheme.equals("https") || (scheme.equals("http") && isLoopback(uri.getHost()))) {
return uri;
}
throw new TokenException("the OAuth2 token endpoint must use https (http is accepted only on this "
+ "machine's loopback address)");
}
private static boolean isLoopback(String host) {
String literal = host.startsWith("[") && host.endsWith("]") ? host.substring(1, host.length() - 1) : host;
if (literal.equalsIgnoreCase("localhost")) {
return true;
}
try {
return InetAddress.ofLiteral(literal).isLoopbackAddress(); // a literal only: never resolves DNS
} catch (IllegalArgumentException notALiteral) {
return false;
}
}
private static JsonNode parse(byte[] body) {
try {
JsonNode json = MAPPER.readTree(body);
return json != null && json.isObject() ? json : null;
} catch (RuntimeException notJson) {
return null;
}
}
private static Duration lifetime(JsonNode json) {
JsonNode expires = json.get("expires_in");
long seconds = -1;
if (expires != null && expires.isNumber()) {
seconds = expires.asLong();
} else if (expires != null && expires.isString()) {
try {
seconds = Long.parseLong(expires.asString().strip()); // some providers send it as a string
} catch (NumberFormatException ignored) {
seconds = -1;
}
}
return seconds > 0 ? Duration.ofSeconds(Math.min(seconds, Duration.ofDays(1).toSeconds())) : DEFAULT_LIFETIME;
}
private static String providerError(JsonNode json) {
if (json == null) {
return "";
}
String error = text(json, "error");
String description = text(json, "error_description");
if (blank(error) && blank(description)) {
return "";
}
return ": " + clip(Objects.requireNonNullElse(error, "error"))
+ (blank(description) ? "" : " — " + clip(description));
}
private static String text(JsonNode json, String field) {
JsonNode node = json.get(field);
return node != null && node.isString() ? node.asString() : null;
}
/** One line of provider text, bounded: it ends up in a console message and the activity log. */
private static String clip(String text) {
String line = text.replaceAll("[\\p{Cntrl}]+", " ").strip();
return line.length() > MAX_ERROR_TEXT ? line.substring(0, MAX_ERROR_TEXT) + "…" : line;
}
private static String encode(String value) {
return URLEncoder.encode(value.strip(), StandardCharsets.UTF_8);
}
private static boolean blank(String value) {
return value == null || value.isBlank();
}
}
@@ -1,5 +1,6 @@
package mx.quest.runway.mail;
import jakarta.mail.AuthenticationFailedException;
import jakarta.mail.Authenticator;
import jakarta.mail.Message;
import jakarta.mail.MessagingException;
@@ -27,6 +28,13 @@ import org.springframework.stereotype.Component;
* here (via the injected {@link SecretCipher}) only at send time, handed straight to Jakarta Mail, and never
* logged ({@link PlatformSettings.Smtp#toString()} masks it).
*
* <p><b>Two ways to sign in.</b> With a password (SMTP {@code AUTH PLAIN}/{@code LOGIN}, whichever the server offers),
* or with an OAuth2 access token (SASL {@code XOAUTH2}), which Microsoft 365 requires once it retires password SMTP
* and Google also accepts. For OAuth2 the stored client secret is decrypted at send time, exchanged for a token by
* {@link OAuth2TokenClient} (cached until shortly before it expires), and the token is handed to Jakarta Mail in
* place of a password, as the mailbox named by the username (or, when that is blank, the From address). An OAuth2
* account must use TLS (STARTTLS or implicit): a bearer token is as good as a password to whoever reads it.
*
* <p>The build/send seam is {@link MailTransport}, injected so the full MIME build is unit-testable against a
* mock with no socket opened (the production {@link JakartaMailTransport} delegates to {@code jakarta.mail
* .Transport}). Jakarta Mail is a core kernel capability (bundled in the app jar), so no plugin is required.
@@ -44,11 +52,14 @@ public class PlatformMailer {
private final PlatformSettingsStore settings;
private final SecretCipher cipher;
private final MailTransport transport;
private final OAuth2TokenClient tokens;
public PlatformMailer(PlatformSettingsStore settings, SecretCipher cipher, MailTransport transport) {
public PlatformMailer(PlatformSettingsStore settings, SecretCipher cipher, MailTransport transport,
OAuth2TokenClient tokens) {
this.settings = settings;
this.cipher = cipher;
this.transport = transport;
this.tokens = tokens;
}
/**
@@ -74,7 +85,14 @@ public class PlatformMailer {
if (smtp == null || !smtp.isConfigured()) {
throw new MessagingException("platform mail is not configured");
}
transport.send(build(smtp, to, subject, body));
try {
transport.send(build(smtp, to, subject, body));
} catch (AuthenticationFailedException refused) {
if (smtp.usesOAuth2()) {
tokens.forget(); // a revoked or re-scoped token must not be offered again until it expires
}
throw refused;
}
}
/** Builds the MIME message from the platform relay settings. Package-visible for direct MIME-shape testing. */
@@ -135,6 +153,32 @@ public class PlatformMailer {
} else {
props.put("mail.smtp.starttls.enable", "false");
}
if (auth && smtp.usesOAuth2()) {
if (!ssl && !starttls) {
throw new MessagingException("OAuth2 sign-in needs STARTTLS or implicit TLS: the access token must "
+ "not cross the network in the clear");
}
String secret;
try {
secret = cipher.decrypt(smtp.oauthClientSecret() == null ? "" : smtp.oauthClientSecret());
} catch (RuntimeException unreadable) {
throw new MessagingException("platform mail OAuth2 client secret cannot be decrypted (wrong "
+ "runway.security.secret-key or corrupted value)", unreadable);
}
String token = tokens.token(new OAuth2TokenClient.Request(smtp.oauthTokenUrl(), smtp.oauthClientId(),
secret, smtp.oauthScope()));
String mailbox = smtp.username() == null || smtp.username().isBlank() ? smtp.from() : smtp.username();
// XOAUTH2 is off unless named; naming it alone keeps a server that does not offer it from being sent
// the token as a PLAIN password.
props.put("mail.smtp.auth.mechanisms", "XOAUTH2");
Authenticator authenticator = new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(mailbox, token);
}
};
return Session.getInstance(props, authenticator);
}
if (auth) {
String username = smtp.username();
String password;
@@ -156,21 +156,51 @@ public record PlatformSettings(String defaultSiteId, String passwordStrength, St
* @param from the envelope/From address platform messages are sent as; blank ⇒ not configured
* @param starttls whether to upgrade a plain connection with STARTTLS ({@code null} ⇒ false)
* @param ssl whether to open an implicit-TLS (SMTPS) connection ({@code null} ⇒ false)
* @param authMethod how to authenticate when {@code auth}: {@value #AUTH_PASSWORD} (the default, also for
* {@code null} or an unknown value) or {@value #AUTH_OAUTH2} (SASL XOAUTH2 with a token
* from an OAuth2 client-credentials grant, as Microsoft 365 requires)
* @param oauthTokenUrl the OAuth2 token endpoint (OAuth2 only); {@code https}, or {@code http} to a loopback
* address
* @param oauthClientId the OAuth2 client (application) id (OAuth2 only)
* @param oauthClientSecret the OAuth2 client secret as the stored {@code ENC(...)} ciphertext (OAuth2 only)
* @param oauthScope the scope requested with the token (OAuth2 only), e.g. Microsoft 365's
* {@code https://outlook.office365.com/.default}
*/
public record Smtp(String host, Integer port, Boolean auth, String username, String password, String from,
Boolean starttls, Boolean ssl) {
Boolean starttls, Boolean ssl, String authMethod, String oauthTokenUrl, String oauthClientId,
String oauthClientSecret, String oauthScope) {
/** {@link #authMethod} for a username and password. */
public static final String AUTH_PASSWORD = "password";
/** {@link #authMethod} for SASL XOAUTH2 with an OAuth2 client-credentials token. */
public static final String AUTH_OAUTH2 = "oauth2";
/** A password-only (or unauthenticated) account: the shape stored before OAuth2 sign-in existed. */
public Smtp(String host, Integer port, Boolean auth, String username, String password, String from,
Boolean starttls, Boolean ssl) {
this(host, port, auth, username, password, from, starttls, ssl, null, null, null, null, null);
}
/** Whether enough is set to attempt a send: a non-blank host AND a non-blank From address. */
public boolean isConfigured() {
return host != null && !host.isBlank() && from != null && !from.isBlank();
}
/** Never leak the (encrypted) password in diagnostics. */
/** Whether the account authenticates with an OAuth2 token rather than a password. */
public boolean usesOAuth2() {
return Boolean.TRUE.equals(auth) && AUTH_OAUTH2.equals(authMethod);
}
/** Never leak the (encrypted) password or client secret in diagnostics. */
@Override
public String toString() {
return "Smtp[host=" + host + ", port=" + port + ", auth=" + auth + ", username=" + username
+ ", from=" + from + ", starttls=" + starttls + ", ssl=" + ssl
+ ", password=" + (password == null || password.isBlank() ? "<none>" : "<set>") + "]";
return "Smtp[host=" + host + ", port=" + port + ", auth=" + auth + ", authMethod=" + authMethod
+ ", username=" + username + ", from=" + from + ", starttls=" + starttls + ", ssl=" + ssl
+ ", password=" + (password == null || password.isBlank() ? "<none>" : "<set>")
+ ", oauthTokenUrl=" + oauthTokenUrl + ", oauthClientId=" + oauthClientId
+ ", oauthClientSecret="
+ (oauthClientSecret == null || oauthClientSecret.isBlank() ? "<none>" : "<set>")
+ ", oauthScope=" + oauthScope + "]";
}
}
@@ -22,6 +22,7 @@ import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;
import org.springframework.core.env.Environment;
/**
* The factories behind the <b>plugin-scoped</b> SPI services ({@link PluginSettings}, {@link PluginSiteFiles},
@@ -53,6 +54,7 @@ public class PluginScopedServices {
private final SecretCipher cipher;
private final StorageLayout layout;
private final long siteFilesMaxBytes;
private final Environment environment;
private final Map<String, PluginSettings> settings = new ConcurrentHashMap<>();
private final Map<String, PluginSiteFiles> siteFiles = new ConcurrentHashMap<>();
private final Map<String, PluginInfo> infos = new ConcurrentHashMap<>();
@@ -62,16 +64,26 @@ public class PluginScopedServices {
* @param layout where the per-site plugin subtrees live ({@code null} only in tests that never ask
* for {@link PluginSiteFiles})
* @param siteFilesMaxBytes {@code runway.plugins.site-files.max-write-bytes} (non-positive = the default)
* @param environment the running environment, which holds each plugin's app-level settings as
* {@code runway.plugin.<id>.<key>} ({@code null} only in tests: no app-level secrets)
*/
@Autowired
public PluginScopedServices(PluginOwnership ownership, SitePluginConfigService siteConfig, SecretCipher cipher,
StorageLayout layout,
@Value("${runway.plugins.site-files.max-write-bytes:16777216}") long siteFilesMaxBytes) {
@Value("${runway.plugins.site-files.max-write-bytes:16777216}") long siteFilesMaxBytes,
Environment environment) {
this.ownership = ownership;
this.siteConfig = siteConfig;
this.cipher = cipher;
this.layout = layout;
this.siteFilesMaxBytes = siteFilesMaxBytes;
this.environment = environment;
}
/** Test form without the running environment: app-level secrets answer empty. */
public PluginScopedServices(PluginOwnership ownership, SitePluginConfigService siteConfig, SecretCipher cipher,
StorageLayout layout, long siteFilesMaxBytes) {
this(ownership, siteConfig, cipher, layout, siteFilesMaxBytes, null);
}
/** Test form without the per-site files (the SPI 0.4.0 shape). */
@@ -86,7 +98,8 @@ public class PluginScopedServices {
LoadedPlugin plugin = owner(injectionPoint, PluginSettings.class,
"kernel code reads per-site plugin settings through SitePluginConfigService");
return settings.computeIfAbsent(plugin.id(), id -> new PluginSettingsImpl(id,
plugin.descriptor().siteSettings(), siteConfig, cipher));
plugin.descriptor().siteSettings(), plugin.descriptor().settings(),
key -> environment == null ? null : environment.getProperty(key), siteConfig, cipher));
}
/** {@link PluginSiteFiles} bound to the injecting plugin's subtree {@code sites/<id>/plugins/<pluginId>/}. */
@@ -7,6 +7,7 @@ import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;
import mx.quest.runway.crypto.SecretCipher;
import mx.quest.runway.plugin.PluginSettingDef;
import mx.quest.runway.plugin.SettingType;
@@ -22,6 +23,8 @@ import org.slf4j.LoggerFactory;
* {@code PluginScopedServices} and handed to every injection point in that plugin's own jar. It reads through
* {@link SitePluginConfigService} (whose per-site cache is evicted on every save, on this node and — from SPI 0.4.0
* — on peers through the replayed change event), overlays the descriptor's declared defaults, and drops secrets.
* App-level secrets ({@link #appSecret}) come from the running environment instead, through a lookup the factory
* hands in, because app-level settings bind as {@code runway.plugin.<id>.<key>} properties at startup.
*
* <h2>Caching</h2>
* The merged view is memoised per site against the <b>identity</b> of the stored map the config service returns:
@@ -36,6 +39,8 @@ public final class PluginSettingsImpl implements PluginSettings {
private final String pluginId;
private final Map<String, PluginSettingDef> schema;
private final Map<String, PluginSettingDef> appSchema;
private final Function<String, String> appValues;
private final SitePluginConfigService config;
private final SecretCipher cipher;
private final Map<String, Memo> memo = new ConcurrentHashMap<>();
@@ -45,6 +50,8 @@ public final class PluginSettingsImpl implements PluginSettings {
}
/**
* Without app-level settings: {@link #appSecret} always answers empty.
*
* @param pluginId the plugin this instance answers for
* @param siteSettings that plugin's declared {@code siteSettings:} schema
* @param config the per-site settings store
@@ -52,16 +59,37 @@ public final class PluginSettingsImpl implements PluginSettings {
*/
public PluginSettingsImpl(String pluginId, List<PluginSettingDef> siteSettings, SitePluginConfigService config,
SecretCipher cipher) {
this(pluginId, siteSettings, List.of(), key -> null, config, cipher);
}
/**
* @param pluginId the plugin this instance answers for
* @param siteSettings that plugin's declared {@code siteSettings:} schema
* @param appSettings that plugin's declared app-level {@code settings:} schema
* @param appValues resolves a full property key ({@code runway.plugin.<id>.<key>}) to the value the running
* environment holds, or {@code null}
* @param config the per-site settings store
* @param cipher decrypts {@code ENC(...)} secrets
*/
public PluginSettingsImpl(String pluginId, List<PluginSettingDef> siteSettings, List<PluginSettingDef> appSettings,
Function<String, String> appValues, SitePluginConfigService config,
SecretCipher cipher) {
this.pluginId = Objects.requireNonNull(pluginId, "pluginId");
this.schema = byKey(siteSettings);
this.appSchema = byKey(appSettings);
this.appValues = Objects.requireNonNull(appValues, "appValues");
this.config = Objects.requireNonNull(config, "config");
this.cipher = cipher;
}
private static Map<String, PluginSettingDef> byKey(List<PluginSettingDef> defs) {
Map<String, PluginSettingDef> byKey = new LinkedHashMap<>();
for (PluginSettingDef def : siteSettings) {
for (PluginSettingDef def : defs == null ? List.<PluginSettingDef>of() : defs) {
if (def != null && def.key() != null && !def.key().isBlank()) {
byKey.putIfAbsent(def.key(), def);
}
}
this.schema = Map.copyOf(byKey);
this.config = Objects.requireNonNull(config, "config");
this.cipher = cipher;
return Map.copyOf(byKey);
}
/** The plugin this instance is bound to. */
@@ -118,7 +146,28 @@ public final class PluginSettingsImpl implements PluginSettings {
return Optional.empty(); // only a key the plugin declared `type: secret` is ever handed out in clear
}
Object raw = config.config(siteId, pluginId).get(key);
String value = raw == null ? null : String.valueOf(raw);
return reveal(raw == null ? null : String.valueOf(raw), "site '" + siteId + "'",
siteId + PathSafety.KEY_SEPARATOR + key, key);
}
/**
* Only a key this plugin declared {@code type: secret} in its own app-level {@code settings:} is handed out; the
* value is the running environment's ({@code runway.plugin.<id>.<key>}), so a saved change answers after the
* restart that applies it — the same moment the plugin's {@code @ConfigurationProperties} see it.
*/
@Override
public Optional<String> appSecret(String key) {
PluginSettingDef def = key == null ? null : appSchema.get(key);
if (def == null || !isSecret(def)) {
return Optional.empty();
}
// The separator cannot occur in a site id, so the app-level warn-once key never collides with a site's.
return reveal(appValues.apply("runway.plugin." + pluginId + "." + key), "the application",
PathSafety.KEY_SEPARATOR + "app" + PathSafety.KEY_SEPARATOR + key, key);
}
/** A stored secret in clear: empty when blank or undecryptable, a non-{@code ENC(...)} value unchanged. */
private Optional<String> reveal(String value, String scope, String warnKey, String key) {
if (value == null || value.isBlank()) {
return Optional.empty();
}
@@ -126,23 +175,23 @@ public final class PluginSettingsImpl implements PluginSettings {
return Optional.of(value); // a hand-written plaintext secret still works, as it always has
}
if (!cipher.isAvailable()) {
warnOnce(siteId, key, "it is encrypted but the platform secret key (runway.security.secret-key) is "
+ "not usable (unset, or itself in the ENC(...) form)");
warnOnce(warnKey, key, scope, "it is encrypted but the platform secret key (runway.security.secret-key) "
+ "is not usable (unset, or itself in the ENC(...) form)");
return Optional.empty();
}
try {
return Optional.of(cipher.decrypt(value));
} catch (RuntimeException failure) {
// Never log the value or the cause's message (it may echo ciphertext); the type is enough to act on.
warnOnce(siteId, key, "it could not be decrypted (" + failure.getClass().getSimpleName()
warnOnce(warnKey, key, scope, "it could not be decrypted (" + failure.getClass().getSimpleName()
+ ") — wrong platform secret key, or a corrupted value");
return Optional.empty();
}
}
private void warnOnce(String siteId, String key, String why) {
if (warned.add(siteId + PathSafety.KEY_SEPARATOR + key)) {
log.warn("plugin '{}' secret setting '{}' for site '{}' is unavailable: {}", pluginId, key, siteId, why);
private void warnOnce(String warnKey, String key, String scope, String why) {
if (warned.add(warnKey)) {
log.warn("plugin '{}' secret setting '{}' for {} is unavailable: {}", pluginId, key, scope, why);
}
}
@@ -7,6 +7,7 @@ import java.nio.file.DirectoryStream;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.LinkOption;
import java.nio.file.NoSuchFileException;
import java.nio.file.Path;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
@@ -90,10 +91,18 @@ public final class PluginSiteFilesImpl implements PluginSiteFiles {
@Override
public Optional<String> readText(String siteId, String relPath) throws IOException {
Path file = resolve(siteId, relPath, false);
if (!isRegularFile(file)) {
BasicFileAttributes attrs;
try {
attrs = Files.readAttributes(file, BasicFileAttributes.class, LinkOption.NOFOLLOW_LINKS);
} catch (NoSuchFileException absent) {
return Optional.empty();
}
if (Files.size(file) > maxBytes) {
// Only a file that is certainly not there is "absent": a folder that cannot be searched (permissions, a stale
// network mount) throws, so a caller never mistakes "cannot tell" for "nothing there" and acts on it.
if (!attrs.isRegularFile()) {
return Optional.empty();
}
if (attrs.size() > maxBytes) {
throw new IOException("plugin '" + pluginId + "' file '" + relPath + "' of site '" + siteId
+ "' is larger than the " + maxBytes + "-byte limit (runway.plugins.site-files.max-write-bytes)");
}
@@ -169,13 +178,14 @@ public final class PluginSiteFilesImpl implements PluginSiteFiles {
@Override
public List<FileEntry> list(String siteId, String relDir) throws IOException {
Path dir = resolve(siteId, relDir, true);
if (!Files.isDirectory(dir, LinkOption.NOFOLLOW_LINKS)) {
Optional<FileEntry> self = entryOf(dir); // a folder that cannot be searched throws, never reads as empty
if (self.isEmpty() || !self.get().directory()) {
return List.of();
}
List<FileEntry> entries = new ArrayList<>();
try (DirectoryStream<Path> children = Files.newDirectoryStream(dir)) {
for (Path child : children) {
entryOf(child).ifPresent(entries::add);
entryOf(child).ifPresent(entries::add); // one removed while listing reads as absent and is skipped
}
}
entries.sort(Comparator.comparing(FileEntry::name));
@@ -194,12 +204,17 @@ public final class PluginSiteFilesImpl implements PluginSiteFiles {
// --- internals ----------------------------------------------------------------------------------------------
/** A regular file or a folder, never a link (nor a device, socket, …); empty for anything else or nothing. */
/**
* A regular file or a folder, never a link (nor a device, socket, …); empty for anything else or nothing. Only a
* path that is certainly not there is absent: one whose folder cannot be searched throws.
*/
private static Optional<FileEntry> entryOf(Path path) throws IOException {
if (!Files.exists(path, LinkOption.NOFOLLOW_LINKS)) {
BasicFileAttributes attrs;
try {
attrs = Files.readAttributes(path, BasicFileAttributes.class, LinkOption.NOFOLLOW_LINKS);
} catch (NoSuchFileException absent) {
return Optional.empty();
}
BasicFileAttributes attrs = Files.readAttributes(path, BasicFileAttributes.class, LinkOption.NOFOLLOW_LINKS);
if (attrs.isSymbolicLink() || !(attrs.isRegularFile() || attrs.isDirectory())) {
return Optional.empty();
}
@@ -0,0 +1,107 @@
package mx.quest.runway.recovery;
import jakarta.servlet.http.HttpServletRequest;
import java.net.URI;
import java.util.List;
import java.util.Optional;
import mx.quest.runway.platform.PlatformSettingsStore;
import mx.quest.runway.site.Site;
import mx.quest.runway.site.SiteStore;
import mx.quest.runway.site.SiteViews;
import mx.quest.runway.web.ConsoleHostFilter;
import mx.quest.runway.web.ConsoleHostProperties;
import mx.quest.runway.web.RequestOrigin;
import org.springframework.stereotype.Component;
/**
* Where an emailed password-reset link points: {@code scheme://host[:port]}, from what the platform was told, never
* from the host the request names.
*
* <p><b>Why.</b> Anyone can send a request with any {@code Host} header (or {@code X-Forwarded-Host}, through a
* proxy that passes it on). A link built from it would be a genuine mail from this platform, sent to a real user, that
* hands the single-use token to whatever host the sender chose; one click and the account is theirs. So:
* <ul>
* <li><b>Site realm:</b> the site's own base URL, configured or derived from its first host name
* ({@link SiteViews#toView}). A link for a site always points at that site, whichever host the request came in
* on (an unknown host reaches the default site, for instance). A site with no host name has no address to
* mail: no link. Nor does one whose only address is derived from a loopback name ({@code localhost}, as the
* setup wizard leaves the default site): {@code https://localhost} reaches nobody who reads the mail.</li>
* <li><b>Application realm:</b> when its host is one of {@code runway.console.hosts} (the console answers on no
* other host then, so the name was checked), that entry's host name, the request's scheme, and the entry's port
* if it names one, else the request's; otherwise the default site's base URL, on which the console also
* answers; otherwise no link.</li>
* </ul>
* With no link, recovery is not offered on that address (the login page hides "Forgot your password?") and a request
* sends nothing.
*/
@Component
public class RecoveryLinks {
private final SiteStore sites;
private final PlatformSettingsStore platform;
private final List<ConsoleHost> consoleHosts;
/** A {@code runway.console.hosts} entry: its normalized host name, and its port, or {@code -1} when it names none. */
record ConsoleHost(String host, int port) {
}
public RecoveryLinks(SiteStore sites, PlatformSettingsStore platform, ConsoleHostProperties console) {
this.sites = sites;
this.platform = platform;
this.consoleHosts = console.getHosts() == null ? List.of() : console.getHosts().stream()
.map(RecoveryLinks::consoleHost).filter(h -> !h.host().isEmpty()).toList();
}
static ConsoleHost consoleHost(String entry) {
String host = ConsoleHostFilter.normalize(entry);
String rest = entry.strip();
int scheme = rest.indexOf("://");
rest = scheme >= 0 ? rest.substring(scheme + 3) : rest;
int slash = rest.indexOf('/');
rest = slash >= 0 ? rest.substring(0, slash) : rest;
int port = -1;
try {
port = URI.create("x://" + rest).getPort();
} catch (IllegalArgumentException notAnAuthority) {
// an unbracketed IPv6 literal, for instance: it names no port
}
return new ConsoleHost(host, port);
}
/** The origin of an application-realm reset link for {@code request}, or empty when none can be trusted. */
public Optional<String> appBase(HttpServletRequest request) {
if (!consoleHosts.isEmpty()) {
String host = ConsoleHostFilter.normalize(request.getServerName());
String scheme = request.getScheme();
if (scheme == null || scheme.isBlank()) {
return Optional.empty();
}
// The listed name, not the request's spelling of it (case, a trailing dot); a listed port bounds the
// request's, which is whatever the client wrote in its Host header.
return consoleHosts.stream().filter(entry -> entry.host().equals(host)).findFirst()
.map(entry -> RequestOrigin.origin(scheme, entry.host(),
entry.port() >= 0 ? entry.port() : request.getServerPort()));
}
return platform.get().defaultSite().flatMap(sites::find).flatMap(this::siteBase);
}
/**
* The origin of a site-realm reset link for {@code site}, or empty when the site has no address for one: no host
* name, or no base URL and a loopback first host.
*/
public Optional<String> siteBase(Site site) {
boolean configured = site.baseUrl() != null && !site.baseUrl().isBlank();
if (!configured && (site.hosts().isEmpty() || isLoopback(site.hosts().get(0)))) {
return Optional.empty();
}
String base = SiteViews.toView(site).baseUrl();
return base == null || base.isBlank() ? Optional.empty() : Optional.of(RequestOrigin.trusted(base, null));
}
/** {@code localhost} (or a name under it), {@code 127.x.x.x} or {@code ::1}: a name only this machine reaches. */
static boolean isLoopback(String host) {
String h = host.toLowerCase(java.util.Locale.ROOT);
return h.equals("localhost") || h.endsWith(".localhost") || h.matches("127(\\.\\d{1,3}){3}")
|| h.equals("::1") || h.equals("[::1]");
}
}
@@ -4,6 +4,7 @@ import java.util.Objects;
import mx.quest.runway.console.AssetVersion;
import mx.quest.runway.console.OperatorProperties;
import mx.quest.runway.mail.PlatformMailer;
import mx.quest.runway.recovery.RecoveryLinks;
import mx.quest.runway.site.SiteResolver;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.stereotype.Controller;
@@ -28,9 +29,11 @@ public class TenantConsoleController {
private final PlatformMailer mailer;
private final OperatorProperties operator;
private final AssetVersion assetVersion;
private final RecoveryLinks links;
public TenantConsoleController(SiteResolver siteResolver, PlatformMailer mailer, OperatorProperties operator,
AssetVersion assetVersion) {
AssetVersion assetVersion, RecoveryLinks links) {
this.links = Objects.requireNonNull(links, "links");
this.siteResolver = Objects.requireNonNull(siteResolver, "siteResolver");
this.mailer = Objects.requireNonNull(mailer, "mailer");
this.operator = Objects.requireNonNull(operator, "operator");
@@ -40,8 +43,10 @@ public class TenantConsoleController {
@GetMapping("/login")
public String login(Model model) {
model.addAttribute("siteName", siteResolver.current().map(site -> site.name()).orElse("Runway"));
// "Forgot your password?" is shown only when the platform can actually email a reset link.
model.addAttribute("recoveryEnabled", mailer.isConfigured());
// "Forgot your password?" is shown only when the platform can actually email a reset link: mail is configured
// and the site has a host name for the link to point at.
model.addAttribute("recoveryEnabled", mailer.isConfigured()
&& siteResolver.current().flatMap(links::siteBase).isPresent());
// Pre-auth language switcher (this controller is outside the console-package OperatorModelAdvice that
// supplies these on other operator pages): the offered languages, the one in force, and the return path.
model.addAttribute("operatorLanguages", operator.getUiLanguages());
@@ -3,7 +3,9 @@ package mx.quest.runway.site;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.nio.file.Files;
import java.nio.file.NoSuchFileException;
import java.nio.file.Path;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.Comparator;
import java.util.List;
import java.util.Objects;
@@ -13,6 +15,8 @@ import mx.quest.runway.storage.PathSafety;
import mx.quest.runway.storage.StorageLayout;
import mx.quest.runway.storage.StoreCache;
import mx.quest.runway.storage.YamlStore;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
/**
@@ -23,6 +27,7 @@ import org.springframework.stereotype.Component;
@Component
public class SiteStore {
private static final Logger log = LoggerFactory.getLogger(SiteStore.class);
private static final String SITE_FILE = "site.yml";
private final StorageLayout layout;
@@ -34,7 +39,12 @@ public class SiteStore {
this.store = Objects.requireNonNull(store, "store");
}
/** The stored site with this id, or empty if it does not exist (or the id is unsafe). */
/**
* The stored site with this id, or empty if it does not exist (or the id is unsafe).
*
* @throws UncheckedIOException when its record cannot be read, its folder included (a folder without search
* permission, a stalled mount): "cannot tell" is never answered as "no such site"
*/
public Optional<Site> find(String id) {
if (!PathSafety.isSafeId(id)) {
return Optional.empty();
@@ -52,7 +62,7 @@ public class SiteStore {
return entries.filter(Files::isDirectory)
.map(dir -> dir.getFileName().toString())
.filter(PathSafety::isSafeId)
.map(this::find)
.map(this::findForListing)
.flatMap(Optional::stream)
.sorted(Comparator.comparing(Site::id))
.toList();
@@ -104,9 +114,26 @@ public class SiteStore {
}
}
private Site load(String id) {
private Optional<Site> findForListing(String id) {
try {
return store.read(siteFile(id), Site.class).orElse(null);
return find(id);
} catch (UncheckedIOException e) {
log.warn("Site '{}' is left out of the list: {}", id, e.getMessage());
return Optional.empty();
}
}
private Site load(String id) {
Path file = siteFile(id);
try {
// Only a file that is not there means no site: Files.isRegularFile would also say false when the folder
// cannot be searched, and a plugin would then take a live site for a deleted one.
if (!Files.readAttributes(file, BasicFileAttributes.class).isRegularFile()) {
return null;
}
return store.read(file, Site.class).orElse(null);
} catch (NoSuchFileException e) {
return null;
} catch (IOException e) {
throw new UncheckedIOException("reading site " + id, e);
}
@@ -160,7 +160,7 @@ public class ConsoleHostFilter extends OncePerRequestFilter {
* A host name as {@link SiteResolver} compares it: lower case, trimmed, without the port. An IPv6 literal keeps
* its address and loses the brackets, so {@code [::1]}, {@code [::1]:8443} and {@code ::1} are one host.
*/
static String normalize(String host) {
public static String normalize(String host) {
if (host == null) {
return "";
}
@@ -0,0 +1,173 @@
package mx.quest.runway.web;
import java.net.InetAddress;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
/**
* Which address in an {@code X-Forwarded-For} chain is the client. Pure functions.
*
* <p>Each proxy <em>appends</em> the address it received the request from, so the chain reads left to right from the
* furthest hop to the nearest, and only the entries written by proxies Runway trusts are reliable: everything to their
* left may have been sent by the client itself. The client is therefore found <b>from the right</b>: skip the entries
* that are trusted proxies ({@code runway.proxy.trusted-cidrs}); the first one that is not is the address the nearest
* trusted proxy saw, and that is the client. Taking the leftmost entry instead, as Spring's {@code ForwardedHeaderFilter}
* does, lets any client choose its own address for rate limits, lockouts and logs whenever the proxy appends rather than
* replaces.
*
* <p>An entry that is not an address literal where one is needed (an obfuscated {@code unknown}, a host name, a
* garbled value) cannot name the client, so the request is attributed to the proxy that sent it: never resolve DNS,
* never guess. Only the rightmost {@value #MAX_ENTRIES} entries are read; any further left were written by the client.
*/
public final class ForwardedFor {
/** The header this class reads. */
public static final String HEADER = "X-Forwarded-For";
/** How many entries, counted from the right, are kept. */
static final int MAX_ENTRIES = 32;
/** The longest entry read as an address; anything longer is not one. */
static final int MAX_ENTRY_LENGTH = 64;
private ForwardedFor() {
}
/**
* The chain as received: every {@code X-Forwarded-For} line in order, split on commas, trimmed, empty entries
* dropped.
*
* @param headers the header's lines, or {@code null}
* @return at most the rightmost {@value #MAX_ENTRIES} entries, and how many there were in all
*/
public static Chain chain(Enumeration<String> headers) {
List<String> all = new ArrayList<>();
int total = 0;
if (headers != null) {
while (headers.hasMoreElements()) {
String line = headers.nextElement();
if (line == null) {
continue;
}
for (String part : line.split(",", -1)) {
String entry = part.strip();
if (entry.isEmpty()) {
continue;
}
total++;
all.add(entry.length() > MAX_ENTRY_LENGTH ? entry.substring(0, MAX_ENTRY_LENGTH) + "…" : entry);
if (all.size() > MAX_ENTRIES) {
all.removeFirst();
}
}
}
}
return new Chain(List.copyOf(all), total);
}
/**
* The client address: the rightmost entry that is not a trusted proxy; the leftmost entry when every entry is one;
* {@code peer} when the chain is empty or the deciding entry is not an address.
*
* @param chain the received chain
* @param trusted the trusted proxies
* @param peer the connection's own address (a trusted proxy, or this would not be called)
*/
public static String client(Chain chain, CidrSet trusted, String peer) {
List<String> entries = chain.entries();
String address = null;
for (int i = entries.size() - 1; i >= 0; i--) {
address = address(entries.get(i));
if (address == null) {
return peer;
}
if (!trusted.contains(address)) {
return address;
}
}
return address == null ? peer : address;
}
/**
* An entry's address without quotes, brackets or port, or {@code null} when it is not an address literal.
* Accepts {@code 192.0.2.1}, {@code 192.0.2.1:8080}, {@code 2001:db8::1}, {@code [2001:db8::1]} and
* {@code [2001:db8::1]:8080}, optionally in double quotes.
*/
static String address(String entry) {
if (entry == null) {
return null;
}
String text = entry.strip();
if (text.length() >= 2 && text.startsWith("\"") && text.endsWith("\"")) {
text = text.substring(1, text.length() - 1).strip();
}
if (text.isEmpty() || text.length() > MAX_ENTRY_LENGTH || text.indexOf('%') >= 0) {
return null;
}
if (text.startsWith("[")) {
int close = text.indexOf(']');
if (close < 0) {
return null;
}
String rest = text.substring(close + 1);
if (!rest.isEmpty() && !isPort(rest)) {
return null;
}
text = text.substring(1, close);
if (text.indexOf(':') < 0) {
return null; // brackets hold IPv6 only
}
} else {
int colon = text.indexOf(':');
if (colon >= 0 && colon == text.lastIndexOf(':')) {
// one colon: IPv4 with a port (IPv6 has at least two)
if (!isPort(text.substring(colon))) {
return null;
}
text = text.substring(0, colon);
if (text.indexOf('.') < 0) {
return null;
}
}
}
try {
InetAddress.ofLiteral(text); // literal only: never resolves DNS
return text;
} catch (RuntimeException e) {
return null;
}
}
private static boolean isPort(String colonAndDigits) {
if (colonAndDigits.length() < 2 || colonAndDigits.length() > 6 || colonAndDigits.charAt(0) != ':') {
return false;
}
for (int i = 1; i < colonAndDigits.length(); i++) {
char c = colonAndDigits.charAt(i);
if (c < '0' || c > '9') {
return false;
}
}
return true;
}
/**
* A received chain.
*
* @param entries at most the rightmost {@value #MAX_ENTRIES} entries, each cut to {@value #MAX_ENTRY_LENGTH}
* characters
* @param total how many entries the request carried
*/
public record Chain(List<String> entries, int total) {
/** No header. */
public static final Chain NONE = new Chain(List.of(), 0);
/** The chain as one line, with {@code …, } in front when entries were dropped on the left. */
public String text() {
String joined = String.join(", ", entries);
return total > entries.size() ? "…, " + joined : joined;
}
}
}
@@ -0,0 +1,28 @@
package mx.quest.runway.web;
import jakarta.servlet.http.HttpServletRequest;
/**
* How {@link TrustedForwardedHeaderFilter} attributed one request: the connection it arrived on, whether that peer's
* forwarded headers were honoured, the {@code X-Forwarded-For} chain it carried, and the client address the rest of
* Runway sees ({@link ClientIp#of}). Kept on the request so an operator can check a proxy setup on <b>About Runway</b>
* without signing in from a second address or reading logs. Read-only; holds nothing secret.
*
* @param peer the TCP peer's address, before any forwarded header
* @param peerTrusted whether the peer is in {@code runway.proxy.trusted-cidrs}
* @param honoured whether the forwarded headers were used: the peer is trusted and
* {@code runway.proxy.forwarded-headers} is on
* @param forwardedFor the {@code X-Forwarded-For} chain as received (also when it was ignored)
* @param clientIp the client address Runway uses for this request
*/
public record ProxyResolution(String peer, boolean peerTrusted, boolean honoured, ForwardedFor.Chain forwardedFor,
String clientIp) {
/** The request attribute that holds it. */
public static final String ATTRIBUTE = ProxyResolution.class.getName();
/** The resolution recorded on {@code request}, or {@code null} when the filter did not run for it. */
public static ProxyResolution of(HttpServletRequest request) {
return request.getAttribute(ATTRIBUTE) instanceof ProxyResolution resolution ? resolution : null;
}
}
@@ -25,12 +25,19 @@ public final class RequestOrigin {
if (scheme == null || scheme.isBlank() || host == null || host.isBlank()) {
return "";
}
return origin(scheme, host, request.getServerPort());
}
/**
* {@code scheme://host[:port]}: lowercase, the scheme's default port (or a port {@code <= 0}) omitted, an IPv6
* literal bracketed.
*/
public static String origin(String scheme, String host, int port) {
scheme = scheme.toLowerCase(Locale.ROOT);
host = host.toLowerCase(Locale.ROOT);
if (host.indexOf(':') >= 0 && !host.startsWith("[")) {
host = "[" + host + "]";
}
int port = request.getServerPort();
boolean defaultPort = port <= 0 || ("http".equals(scheme) && port == 80)
|| ("https".equals(scheme) && port == 443);
return scheme + "://" + host + (defaultPort ? "" : ":" + port);
@@ -0,0 +1,88 @@
package mx.quest.runway.web;
import org.eclipse.jetty.server.Connector;
import org.eclipse.jetty.server.ConnectionFactory;
import org.eclipse.jetty.server.HttpConfiguration;
import org.eclipse.jetty.server.Server;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.jetty.ConfigurableJettyWebServerFactory;
import org.springframework.boot.web.server.WebServerFactoryCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* Keeps slow clients from holding request threads: a minimum rate for request bodies ({@code
* runway.http.min-request-data-rate}, bytes per second; Settings → Server settings → Request limits), applied to every
* connector Jetty has when the server is built.
*
* <p><b>Why.</b> A servlet reads a request body on a request thread and blocks while it waits. Jetty's idle timeout
* limits one stalled read, not the whole body, so a client that sends a byte inside every idle interval kept a thread
* for as long as it liked, and a few of them (with uploads allowed up to 256 MB) could take the pool. With a minimum
* rate Jetty answers {@code 408 Request Timeout} as soon as the body has arrived more slowly than the rate since its
* first byte; time the application spends before reading does not count, because the rate is measured on what has
* arrived. Measured on Jetty 12.1.8: a client sending one byte a second against 1 KiB/s was cut after about two
* seconds, and a server pausing three seconds before reading a body that arrived at once still answered {@code 200}.
*
* <p><b>What it does not cover.</b> Slow header senders cost a connection, not a thread (Jetty parses headers without
* one); a proxy's connection cap is the limit there. A client that reads a response slowly is bounded by the
* connection idle timeout ({@code server.jetty.connection-idle-timeout}), which ends a write that cannot proceed for
* that long; Jetty's response-rate minimum was measured not to act while a write is blocked, so it is not used.
*/
@Configuration(proxyBeanMethods = false)
@EnableConfigurationProperties(SlowClientConfig.HttpLimitProperties.class)
public class SlowClientConfig {
private static final Logger log = LoggerFactory.getLogger(SlowClientConfig.class);
@Bean
public WebServerFactoryCustomizer<ConfigurableJettyWebServerFactory> slowClientJettyCustomizer(
HttpLimitProperties properties) {
long rate = Math.max(0, properties.getMinRequestDataRate());
return factory -> factory.addServerCustomizers(server -> apply(server, rate));
}
/**
* Sets the minimum request data rate on every HTTP configuration of {@code server}'s connectors.
*
* @param bytesPerSecond the rate; 0 turns the check off
* @return how many HTTP configurations were changed
*/
static int apply(Server server, long bytesPerSecond) {
int changed = 0;
for (Connector connector : server.getConnectors()) {
for (ConnectionFactory factory : connector.getConnectionFactories()) {
if (factory instanceof HttpConfiguration.ConnectionFactory http) {
http.getHttpConfiguration().setMinRequestDataRate(bytesPerSecond);
changed++;
}
}
}
if (bytesPerSecond > 0) {
log.info("request bodies slower than {} bytes/s are refused (runway.http.min-request-data-rate)",
bytesPerSecond);
} else {
log.warn("runway.http.min-request-data-rate is 0: a client sending a request body slowly can hold a "
+ "request thread for as long as it keeps sending");
}
return changed;
}
/** Bound {@code runway.http.*}: limits on how slowly a client may talk to Runway. */
@ConfigurationProperties("runway.http")
public static class HttpLimitProperties {
/** The slowest a request body may arrive, in bytes per second. Default 4096; 0 or less turns the check off. */
private long minRequestDataRate = 4096;
public long getMinRequestDataRate() {
return minRequestDataRate;
}
public void setMinRequestDataRate(long minRequestDataRate) {
this.minRequestDataRate = minRequestDataRate;
}
}
}
@@ -25,6 +25,18 @@ import org.springframework.web.filter.ForwardedHeaderFilter;
* <p>This replaces the container's ungated native handling (paired with {@code server.forward-headers-strategy:
* none}), giving exactly one gated source that {@link ClientIp#of} reads. Honoring forwarded headers from any
* peer is the classic spoofing foot-gun; the trust gate closes it.
*
* <p><b>The client address is Runway's own decision, not Spring's.</b> Spring takes the leftmost
* {@code X-Forwarded-For} entry, which the client can write itself whenever the proxy appends to the header instead
* of replacing it. This filter reads the chain from the right instead ({@link ForwardedFor#client}) and overrides the
* remote address Spring computed. Spring still applies the forwarded scheme, host and port.
*
* <p><b>Only the {@code X-Forwarded-*} family is read.</b> The standard {@code Forwarded} header (RFC 7239) is hidden
* even from a trusted peer: Spring prefers it over {@code X-Forwarded-*} whenever it is present, so a client could send
* its own {@code Forwarded} through a proxy that only manages {@code X-Forwarded-*} and choose its address, host and
* scheme. One family, managed by the proxy, leaves nothing for the client to add.
*
* <p>Every request records how it was attributed ({@link ProxyResolution}, for the About screen).
*/
public class TrustedForwardedHeaderFilter extends ForwardedHeaderFilter {
@@ -33,6 +45,9 @@ public class TrustedForwardedHeaderFilter extends ForwardedHeaderFilter {
"Forwarded", "X-Forwarded-For", "X-Forwarded-Host", "X-Forwarded-Port",
"X-Forwarded-Proto", "X-Forwarded-Prefix", "X-Forwarded-Ssl");
/** The RFC 7239 header, hidden even from a trusted peer: Runway reads the {@code X-Forwarded-*} family only. */
private static final Set<String> RFC_FORWARDED = Set.of("Forwarded");
private final CidrSet trustedProxies;
private final boolean enabled;
@@ -44,22 +59,57 @@ public class TrustedForwardedHeaderFilter extends ForwardedHeaderFilter {
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
throws ServletException, IOException {
if (enabled && trustedProxies.contains(request.getRemoteAddr())) {
super.doFilterInternal(request, response, chain); // trusted: honor + strip forwarded headers
String peer = request.getRemoteAddr();
boolean peerTrusted = trustedProxies.contains(peer);
ForwardedFor.Chain forwardedFor = ForwardedFor.chain(request.getHeaders(ForwardedFor.HEADER));
if (enabled && peerTrusted) {
String client = ForwardedFor.client(forwardedFor, trustedProxies, peer);
request.setAttribute(ProxyResolution.ATTRIBUTE,
new ProxyResolution(peer, true, true, forwardedFor, client));
// trusted: Spring applies scheme/host/port and strips the headers; the address is ours
super.doFilterInternal(new ForwardedHeaderHidingRequest(request, RFC_FORWARDED), response,
(req, res) -> chain.doFilter(new ClientAddressRequest((HttpServletRequest) req, client), res));
} else {
chain.doFilter(new ForwardedHeaderHidingRequest(request), response); // untrusted: hide them, raw peer stands
request.setAttribute(ProxyResolution.ATTRIBUTE,
new ProxyResolution(peer, peerTrusted, false, forwardedFor, peer));
// untrusted: hide them, raw peer stands
chain.doFilter(new ForwardedHeaderHidingRequest(request, FORWARDED_HEADERS), response);
}
}
private static boolean isForwarded(String name) {
return name != null && FORWARDED_HEADERS.stream().anyMatch(header -> header.equalsIgnoreCase(name));
/** Presents the client address this filter resolved, over whatever Spring derived from the leftmost entry. */
private static final class ClientAddressRequest extends HttpServletRequestWrapper {
private final String client;
ClientAddressRequest(HttpServletRequest request, String client) {
super(request);
this.client = client;
}
@Override
public String getRemoteAddr() {
return client;
}
@Override
public String getRemoteHost() {
return client; // never a reverse lookup
}
}
/** Hides the forwarded headers so no downstream code (or container default) can read a spoofed value. */
/** Hides the given forwarded headers so no downstream code (or container default) can read a spoofed value. */
private static final class ForwardedHeaderHidingRequest extends HttpServletRequestWrapper {
ForwardedHeaderHidingRequest(HttpServletRequest request) {
private final Set<String> hidden;
ForwardedHeaderHidingRequest(HttpServletRequest request, Set<String> hidden) {
super(request);
this.hidden = hidden;
}
private boolean isForwarded(String name) {
return name != null && hidden.stream().anyMatch(header -> header.equalsIgnoreCase(name));
}
@Override
@@ -87,6 +87,12 @@ server:
# runway.cluster.session-ttl, which feeds the Hazelcast sessions-map max-idle-seconds (Hazelcast, not the
# container, then evicts idle sessions). Keep the two in step.
timeout: 30m
# Jetty's connection idle timeout, stated rather than left to Jetty's default (the same 30 s): it ends a read or a
# write that cannot proceed for that long, which is what bounds a client reading a response slowly.
# runway.http.min-request-data-rate ends a request body that keeps arriving too slowly to trip it. The request
# thread pool (server.jetty.threads.*) is a console setting: Settings -> Server settings -> Capacity.
jetty:
connection-idle-timeout: 30s
# The gated TrustedForwardedHeaderFilter (FilterOrder.CORE_FORWARDED, outermost) is the SOLE handler of
# X-Forwarded-* / Forwarded. Keep the container's native handling OFF — it would trust those headers from
# ANY peer, letting a directly-reachable instance spoof its IP, host and scheme.
@@ -314,6 +320,12 @@ runway:
trusted-cidrs:
- "127.0.0.1/32"
- "::1/128"
# How slowly a client may send a request body, in bytes per second, before Jetty answers 408 and frees the
# request thread (SlowClientConfig). Measured from the body's first byte on what has arrived, so a server that is
# slow to read is never blamed. 4096 is below any real connection; 0 turns the check off. Also on Settings ->
# Server settings -> Request limits.
http:
min-request-data-rate: 4096
# Stored-backup retention (app-level, not tenant-editable). After a site backup is written, its own
# older stored backups are pruned so `backups/<id>/` does not grow without bound. Both limits apply
# independently; either set to 0 disables that dimension. The just-written backup is always kept.
@@ -684,6 +684,16 @@ op.settings.platform.smtp.password=Password
op.settings.platform.smtp.password.keep=A password is already stored; leave blank to keep it.
op.settings.platform.smtp.starttls=Use STARTTLS (upgrade a plain connection)
op.settings.platform.smtp.ssl=Use implicit TLS (SMTPS)
op.settings.platform.smtp.method=Sign-in method
op.settings.platform.smtp.method.password=Username and password
op.settings.platform.smtp.method.oauth2=OAuth2 token (Microsoft 365)
op.settings.platform.smtp.username.oauth2=With OAuth2, the mailbox to send as; blank uses the From address.
op.settings.platform.smtp.oauth.help=Runway asks the token endpoint for a token with these client credentials and signs in with it (XOAUTH2). Needs STARTTLS or implicit TLS. For Microsoft 365, see the Administration guide.
op.settings.platform.smtp.oauth.url=Token endpoint
op.settings.platform.smtp.oauth.client=Client ID
op.settings.platform.smtp.oauth.secret=Client secret
op.settings.platform.smtp.oauth.secret.keep=A client secret is stored; leave blank to keep it.
op.settings.platform.smtp.oauth.scope=Scope
op.settings.platform.save=Save settings
op.settings.platform.smtp.test=Send test email
op.settings.platform.smtp.test.help=Send a message through the platform mail account to verify it. Save your changes above first.
@@ -734,6 +744,12 @@ op.about.rt.pid=Process ID
op.about.rt.host=Host name
op.about.rt.timezone=Time zone
op.about.rt.locale=Default locale
op.about.request=This request
op.about.request.note=How Runway sees the request that loaded this page. Behind a reverse proxy, the client address should be your own public address, not the proxy's.
op.about.req.peer=Connection from
op.about.req.forwardedFor=X-Forwarded-For received
op.about.req.client=Client address used
op.about.req.origin=Scheme and host
# Site templates (app realm) — the seed presentation every new site is born from
op.sitetpl.title=Site templates
@@ -1471,6 +1487,8 @@ op.ks.runway.csp.frame-ancestors=frame-ancestors
op.ks.runway.csp.frame-ancestors.help=Which sites may show these pages in a frame. 'none' forbids all.
op.ks.runway.endpoints.max-form-bytes=Largest request before sign-in (bytes)
op.ks.runway.endpoints.max-form-bytes.help=The most a visitor who is not signed in may send in one request, on any path. Default 262144 (256 KiB).
op.ks.runway.http.min-request-data-rate=Slowest request body (bytes per second)
op.ks.runway.http.min-request-data-rate.help=A request body arriving more slowly is answered 408 Request Timeout, so a client sending a byte now and then cannot hold a request thread. Measured on what has arrived since the body's first byte. Default 4096; 0 turns the check off.
op.ks.runway.endpoints.max-body-bytes=Largest request to a plugin (bytes)
op.ks.runway.endpoints.max-body-bytes.help=The most a signed-in user may send to a plugin's route. Default 10485760 (10 MiB).
op.ks.spring.servlet.multipart.max-file-size=Largest uploaded file
@@ -1530,7 +1548,7 @@ op.ks.server.servlet.session.timeout.help=A duration such as 30m, 2h or 1d. Defa
op.ks.runway.proxy.forwarded-headers=Read X-Forwarded-* headers
op.ks.runway.proxy.forwarded-headers.help=From the trusted addresses below only.
op.ks.runway.proxy.trusted-cidrs=Trusted proxy addresses
op.ks.runway.proxy.trusted-cidrs.help=The exact address of your reverse proxy, e.g. 10.0.0.5/32. A /0 (0.0.0.0/0, ::/0), or ranges that add up to every address (0.0.0.0/1 with 128.0.0.0/1), would trust every client to fake its address, so it is refused.
op.ks.runway.proxy.trusted-cidrs.help=The exact address of your reverse proxy, e.g. 10.0.0.5/32, and of every proxy in front of it (a CDN). Check the result under About Runway → This request. A /0 (0.0.0.0/0, ::/0), or ranges that add up to every address (0.0.0.0/1 with 128.0.0.0/1), would trust every client to fake its address, so it is refused.
op.ks.server.jetty.threads.max=Most request threads
op.ks.server.jetty.threads.max.help=Default 200.
op.ks.server.jetty.threads.min=Fewest request threads
@@ -685,6 +685,16 @@ op.settings.platform.smtp.password=Contraseña
op.settings.platform.smtp.password.keep=Ya hay una contraseña guardada; déjelo en blanco para conservarla.
op.settings.platform.smtp.starttls=Usar STARTTLS (actualizar una conexión sin cifrar)
op.settings.platform.smtp.ssl=Usar TLS implícito (SMTPS)
op.settings.platform.smtp.method=Método de inicio de sesión
op.settings.platform.smtp.method.password=Usuario y contraseña
op.settings.platform.smtp.method.oauth2=Token OAuth2 (Microsoft 365)
op.settings.platform.smtp.username.oauth2=Con OAuth2, el buzón desde el que se envía; en blanco, se usa la dirección de origen.
op.settings.platform.smtp.oauth.help=Runway pide un token al endpoint de tokens con estas credenciales de cliente e inicia sesión con él (XOAUTH2). Requiere STARTTLS o TLS implícito. Para Microsoft 365, consulte la guía de administración.
op.settings.platform.smtp.oauth.url=Endpoint de tokens
op.settings.platform.smtp.oauth.client=ID de cliente
op.settings.platform.smtp.oauth.secret=Secreto de cliente
op.settings.platform.smtp.oauth.secret.keep=Ya hay un secreto de cliente guardado; déjelo en blanco para conservarlo.
op.settings.platform.smtp.oauth.scope=Ámbito
op.settings.platform.save=Guardar configuración
op.settings.platform.smtp.test=Enviar correo de prueba
op.settings.platform.smtp.test.help=Envíe un mensaje a través de la cuenta de correo de la plataforma para verificarla. Guarde primero los cambios de arriba.
@@ -735,6 +745,12 @@ op.about.rt.pid=ID de proceso
op.about.rt.host=Nombre del host
op.about.rt.timezone=Zona horaria
op.about.rt.locale=Idioma predeterminado
op.about.request=Esta solicitud
op.about.request.note=Cómo ve Runway la solicitud que cargó esta página. Detrás de un proxy inverso, la dirección del cliente debe ser su propia dirección pública, no la del proxy.
op.about.req.peer=Conexión desde
op.about.req.forwardedFor=X-Forwarded-For recibido
op.about.req.client=Dirección de cliente usada
op.about.req.origin=Esquema y host
# Plantillas de sitio (realm de aplicación) — la presentación semilla con la que nace cada sitio nuevo
op.sitetpl.title=Plantillas de sitio
@@ -1472,6 +1488,8 @@ op.ks.runway.csp.frame-ancestors=frame-ancestors
op.ks.runway.csp.frame-ancestors.help=Qué sitios pueden mostrar estas páginas en un marco. 'none' lo prohíbe.
op.ks.runway.endpoints.max-form-bytes=Solicitud máxima sin sesión (bytes)
op.ks.runway.endpoints.max-form-bytes.help=Lo máximo que un visitante sin sesión puede enviar en una solicitud, en cualquier ruta. Por omisión 262144 (256 KiB).
op.ks.runway.http.min-request-data-rate=Cuerpo de solicitud más lento (bytes por segundo)
op.ks.runway.http.min-request-data-rate.help=Un cuerpo de solicitud que llega más despacio recibe 408 Request Timeout, así que un cliente que envía un byte de vez en cuando no puede ocupar un hilo de solicitud. Se mide sobre lo recibido desde el primer byte del cuerpo. Por omisión 4096; 0 desactiva la comprobación.
op.ks.runway.endpoints.max-body-bytes=Solicitud máxima a un complemento (bytes)
op.ks.runway.endpoints.max-body-bytes.help=Lo máximo que un usuario con sesión puede enviar a una ruta de un complemento. Por omisión 10485760 (10 MiB).
op.ks.spring.servlet.multipart.max-file-size=Archivo subido máximo
@@ -1531,7 +1549,7 @@ op.ks.server.servlet.session.timeout.help=Una duración como 30m, 2h o 1d. Por o
op.ks.runway.proxy.forwarded-headers=Leer encabezados X-Forwarded-*
op.ks.runway.proxy.forwarded-headers.help=Solo de las direcciones de confianza de abajo.
op.ks.runway.proxy.trusted-cidrs=Direcciones de proxy de confianza
op.ks.runway.proxy.trusted-cidrs.help=La dirección exacta de su proxy inverso, p. ej. 10.0.0.5/32. Un /0 (0.0.0.0/0, ::/0), o rangos que juntos cubren todas las direcciones (0.0.0.0/1 con 128.0.0.0/1), dejaría que cualquier cliente falsee su dirección, así que se rechaza.
op.ks.runway.proxy.trusted-cidrs.help=La dirección exacta de su proxy inverso, p. ej. 10.0.0.5/32, y la de cada proxy delante de él (una CDN). Compruebe el resultado en Acerca de Runway → Esta solicitud. Un /0 (0.0.0.0/0, ::/0), o rangos que juntos cubren todas las direcciones (0.0.0.0/1 con 128.0.0.0/1), dejaría que cualquier cliente falsee su dirección, así que se rechaza.
op.ks.server.jetty.threads.max=Hilos de solicitud máximos
op.ks.server.jetty.threads.max.help=Por omisión 200.
op.ks.server.jetty.threads.min=Hilos de solicitud mínimos
@@ -41,6 +41,7 @@ settings:
- { key: runway.csp.form-action, type: string, default: "'self'", label: op.ks.runway.csp.form-action, help: op.ks.runway.csp.form-action.help, group: server.csp, advanced: true }
- { key: runway.csp.frame-ancestors, type: string, default: "'self'", label: op.ks.runway.csp.frame-ancestors, help: op.ks.runway.csp.frame-ancestors.help, group: server.csp, advanced: true }
- { key: runway.endpoints.max-form-bytes, type: int, default: "262144", range: "1024..104857600", label: op.ks.runway.endpoints.max-form-bytes, help: op.ks.runway.endpoints.max-form-bytes.help, group: server.limits }
- { key: runway.http.min-request-data-rate, type: int, default: "4096", range: "0..1048576", label: op.ks.runway.http.min-request-data-rate, help: op.ks.runway.http.min-request-data-rate.help, group: server.limits, advanced: true }
- { key: runway.endpoints.max-body-bytes, type: int, default: "10485760", range: "1024..1073741824", label: op.ks.runway.endpoints.max-body-bytes, help: op.ks.runway.endpoints.max-body-bytes.help, group: server.limits }
- { key: spring.servlet.multipart.max-file-size, type: string, default: "256MB", label: op.ks.spring.servlet.multipart.max-file-size, help: op.ks.spring.servlet.multipart.max-file-size.help, group: server.limits }
- { key: spring.servlet.multipart.max-request-size, type: string, default: "256MB", label: op.ks.spring.servlet.multipart.max-request-size, help: op.ks.spring.servlet.multipart.max-request-size.help, group: server.limits }
@@ -237,3 +237,7 @@ body.layout-fluid .page-header {
margin: 0;
padding: 0;
}
/* Platform mail: show the fields of the chosen sign-in method only (no script; :has() on the select's state). */
.rw-smtp:has(#ps-smtp-method option[value="password"]:checked) .rw-smtp-oauth { display: none; }
.rw-smtp:has(#ps-smtp-method option[value="oauth2"]:checked) .rw-smtp-pw { display: none; }
@@ -52,6 +52,25 @@
</div>
</div>
<div class="row row-cards mt-3">
<div class="col-lg-6">
<div class="card">
<div class="card-header"><h3 class="card-title" id="rq-title">This request</h3></div>
<div class="card-body">
<p class="text-secondary" id="rq-note">How Runway sees the request that loaded this page.</p>
<table class="table table-sm card-table">
<tbody id="rq-body">
<tr id="rq-row">
<th scope="row" id="rq-name" class="text-secondary fw-normal">name</th>
<td id="rq-val" class="text-end font-monospace text-break">value</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
<div class="row row-cards mt-3">
<div class="col-12">
<div class="card">
@@ -23,6 +23,13 @@
<attr sel="#rt-row/#rt-name" th:text="#{${nv.name()}}" th:id="${null}"/>
<attr sel="#rt-row/#rt-val" th:text="${nv.value()}" th:id="${null}"/>
<!-- This request — how the trusted-proxy gate attributed it -->
<attr sel="#rq-title" th:text="#{op.about.request}"/>
<attr sel="#rq-note" th:text="#{op.about.request.note}"/>
<attr sel="#rq-row" th:each="nv : ${requestInfo}" th:id="${null}"/>
<attr sel="#rq-row/#rq-name" th:text="#{${nv.name()}}" th:id="${null}"/>
<attr sel="#rq-row/#rq-val" th:text="${nv.value()}" th:id="${null}"/>
<!-- Bundled components — its own section -->
<attr sel="#cmp-title" th:text="#{op.about.runtime.components}"/>
<attr sel="#cmp-note" th:text="#{op.about.components.note}"/>
@@ -71,7 +71,7 @@
Brotli's native library did not load on this server; it falls back to gzip.</small>
</div>
<div class="mb-4">
<div class="mb-4 rw-smtp">
<div class="form-label" id="ps-l-mail">Platform mail (SMTP)</div>
<small class="form-hint d-block mb-2" id="ps-h-mail">
Used for password recovery and other application messages. Not used for a site's
@@ -98,13 +98,22 @@
name="smtpAuth" value="true">
<span class="form-check-label" id="ps-smtp-auth-lbl">Requires authentication</span>
</label>
<div class="mt-1">
<label class="form-label" id="ps-l-smtp-method" for="ps-smtp-method">Sign-in method</label>
<select id="ps-smtp-method" name="smtpAuthMethod" class="form-select">
<option id="ps-smtp-method-pw" value="password">Username and password</option>
<option id="ps-smtp-method-oauth" value="oauth2">OAuth2 token (Microsoft 365)</option>
</select>
</div>
<div class="row g-2 mt-1">
<div class="col-md-6">
<label class="form-label" id="ps-l-smtp-user" for="ps-smtp-user">Username</label>
<input id="ps-smtp-user" name="smtpUsername" type="text" class="form-control"
value="" autocomplete="off" spellcheck="false">
<small class="form-hint rw-smtp-oauth" id="ps-smtp-user-hint">
With OAuth2, the mailbox to send as; blank uses the From address.</small>
</div>
<div class="col-md-6">
<div class="col-md-6 rw-smtp-pw">
<label class="form-label" id="ps-l-smtp-pass" for="ps-smtp-pass">Password</label>
<input id="ps-smtp-pass" name="smtpPassword" type="password"
class="form-control" value="" autocomplete="new-password">
@@ -112,6 +121,37 @@
A password is stored; leave blank to keep it.</small>
</div>
</div>
<div class="rw-smtp-oauth mt-1">
<small class="form-hint d-block mb-2" id="ps-h-oauth">
Runway asks the token endpoint for a token with the client credentials, and signs
in with it (XOAUTH2). Needs STARTTLS or implicit TLS.</small>
<div>
<label class="form-label" id="ps-l-oauth-url" for="ps-oauth-url">Token endpoint</label>
<input id="ps-oauth-url" name="smtpOauthTokenUrl" type="url" class="form-control"
value="" autocomplete="off" spellcheck="false"
placeholder="https://login.microsoftonline.com/TENANT-ID/oauth2/v2.0/token">
</div>
<div class="row g-2 mt-1">
<div class="col-md-6">
<label class="form-label" id="ps-l-oauth-client" for="ps-oauth-client">Client ID</label>
<input id="ps-oauth-client" name="smtpOauthClientId" type="text"
class="form-control" value="" autocomplete="off" spellcheck="false">
</div>
<div class="col-md-6">
<label class="form-label" id="ps-l-oauth-secret" for="ps-oauth-secret">Client secret</label>
<input id="ps-oauth-secret" name="smtpOauthClientSecret" type="password"
class="form-control" value="" autocomplete="new-password">
<small class="form-hint" id="ps-oauth-secret-hint">
A client secret is stored; leave blank to keep it.</small>
</div>
</div>
<div class="mt-1">
<label class="form-label" id="ps-l-oauth-scope" for="ps-oauth-scope">Scope</label>
<input id="ps-oauth-scope" name="smtpOauthScope" type="text" class="form-control"
value="" autocomplete="off" spellcheck="false"
placeholder="https://outlook.office365.com/.default">
</div>
</div>
<label class="form-check form-switch mt-2">
<input id="ps-smtp-starttls" class="form-check-input" type="checkbox"
name="smtpStarttls" value="true">
@@ -55,6 +55,23 @@
<attr sel="#ps-l-smtp-pass" th:text="#{op.settings.platform.smtp.password}"/>
<attr sel="#ps-smtp-pass-hint" th:if="${smtpPasswordConfigured}"
th:text="#{op.settings.platform.smtp.password.keep}"/>
<attr sel="#ps-l-smtp-method" th:text="#{op.settings.platform.smtp.method}"/>
<attr sel="#ps-smtp-method-pw" th:text="#{op.settings.platform.smtp.method.password}"
th:selected="${smtpAuthMethod == 'password'}"/>
<attr sel="#ps-smtp-method-oauth" th:text="#{op.settings.platform.smtp.method.oauth2}"
th:selected="${smtpAuthMethod == 'oauth2'}"/>
<attr sel="#ps-smtp-user-hint" th:text="#{op.settings.platform.smtp.username.oauth2}"/>
<!-- OAuth2 sign-in. The client secret is never sent to the form either. -->
<attr sel="#ps-h-oauth" th:text="#{op.settings.platform.smtp.oauth.help}"/>
<attr sel="#ps-l-oauth-url" th:text="#{op.settings.platform.smtp.oauth.url}"/>
<attr sel="#ps-oauth-url" th:value="${smtpOauthTokenUrl}"/>
<attr sel="#ps-l-oauth-client" th:text="#{op.settings.platform.smtp.oauth.client}"/>
<attr sel="#ps-oauth-client" th:value="${smtpOauthClientId}"/>
<attr sel="#ps-l-oauth-secret" th:text="#{op.settings.platform.smtp.oauth.secret}"/>
<attr sel="#ps-oauth-secret-hint" th:if="${smtpOauthSecretConfigured}"
th:text="#{op.settings.platform.smtp.oauth.secret.keep}"/>
<attr sel="#ps-l-oauth-scope" th:text="#{op.settings.platform.smtp.oauth.scope}"/>
<attr sel="#ps-oauth-scope" th:value="${smtpOauthScope}"/>
<attr sel="#ps-smtp-starttls" th:checked="${smtpStarttls}"/>
<attr sel="#ps-smtp-starttls-lbl" th:text="#{op.settings.platform.smtp.starttls}"/>
<attr sel="#ps-smtp-ssl" th:checked="${smtpSsl}"/>
@@ -93,11 +93,12 @@
<attr sel="#si-row//.s-edit-cancel" th:text="#{op.sites.hosts.cancel}"/>
<attr sel="#si-row//.s-edit-save" th:text="#{op.sites.edit.save}"/>
<!-- Edit hosts (grantable MANAGE_SITE_HOSTS): a modal keyed by row index (CSS-safe, unlike a site id that
<!-- Edit hosts (grantable MANAGE_SITE_HOSTS; the default site's only for a platform admin): a modal keyed by row index (CSS-safe, unlike a site id that
may contain a dot) opened via the Tabler data-API; the form posts and redirects, so no JS closes it. -->
<attr sel="#si-row//.s-hosts-editbtn" th:if="${canEditHosts}" th:text="#{op.sites.hosts.edit}"
<attr sel="#si-row//.s-hosts-editbtn" th:if="${canEditHosts and (canEditSites or site.id() != defaultSiteId)}"
th:text="#{op.sites.hosts.edit}"
th:attr="data-bs-target='#si-hosts-modal-' + ${iter.index}"/>
<attr sel="#si-row//.s-hosts-modal" th:if="${canEditHosts}"
<attr sel="#si-row//.s-hosts-modal" th:if="${canEditHosts and (canEditSites or site.id() != defaultSiteId)}"
th:attr="id='si-hosts-modal-' + ${iter.index},aria-labelledby='si-hosts-title-' + ${iter.index}"/>
<attr sel="#si-row//.s-hosts-title" th:text="#{op.sites.hosts.edit}" th:id="|si-hosts-title-${iter.index}|"/>
<attr sel="#si-row//.s-hosts-siteid" th:text="${site.id()}"/>
@@ -441,6 +441,26 @@ class BackupServiceTest {
assertEquals(List.of("moved.test"), fresh.find("b").orElseThrow().hosts(), "b keeps it");
}
@Test
void aSiteManagersRestoreKeepsHowTheSiteIsReachedAPlatformAdminsBringsTheBackupsBack() throws IOException {
SiteStore store = new SiteStore(layout, new YamlStore());
store.save(new Site("r", "R", List.of("old.test"), Locale.ENGLISH, List.of(Locale.ENGLISH),
"https://evil.example", SiteStatus.ACTIVE)); // what an archive written by hand could say
ByteArrayOutputStream archive = new ByteArrayOutputStream();
svc.backup("r", archive);
store.save(store.find("r").orElseThrow().withHosts(List.of("r.test")).withBaseUrl(null));
svc.restore("r", new ByteArrayInputStream(archive.toByteArray()), true); // the site realm
Site kept = new SiteStore(layout, new YamlStore()).find("r").orElseThrow();
assertEquals(List.of("r.test"), kept.hosts());
assertEquals(null, kept.baseUrl());
svc.restore("r", new ByteArrayInputStream(archive.toByteArray())); // the application realm
Site back = new SiteStore(layout, new YamlStore()).find("r").orElseThrow();
assertEquals(List.of("old.test"), back.hosts());
assertEquals("https://evil.example", back.baseUrl());
}
@Test
void createFromBackupRejectsAnExistingId() throws IOException {
new SiteStore(layout, new YamlStore()).save(new Site("src", "Source", List.of(), Locale.ENGLISH,
@@ -28,10 +28,13 @@ 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 mx.quest.runway.web.ForwardedFor;
import mx.quest.runway.web.ProxyResolution;
import org.hamcrest.Matchers;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpSession;
import org.springframework.test.context.DynamicPropertyRegistry;
import org.springframework.test.context.DynamicPropertySource;
@@ -128,6 +131,39 @@ class AppAboutPageTest {
.andExpect(content().string(Matchers.containsString("href=\"/__app/settings\"")));
}
@Test
void aboutShowsThisRequestAsRunwaySeesIt() throws Exception {
MockHttpSession session = login();
mvc().perform(get("/__app/about").session(session).locale(Locale.ENGLISH))
.andExpect(status().isOk())
.andExpect(content().string(Matchers.containsString("This request")))
.andExpect(content().string(Matchers.containsString("Client address used")))
.andExpect(content().string(Matchers.containsString("Scheme and host")));
}
@Test
void theRequestRowsShowHowTheProxyGateAttributedIt() {
MockHttpServletRequest trusted = new MockHttpServletRequest("GET", "/__app/about");
trusted.setAttribute(ProxyResolution.ATTRIBUTE, new ProxyResolution("10.0.0.5", true, true,
new ForwardedFor.Chain(List.of("6.6.6.6", "203.0.113.7"), 2), "203.0.113.7"));
assertThat(info.request(trusted)).extracting(RuntimeInfoService.NameValue::value)
.containsExactly("10.0.0.5 (trusted proxy)", "6.6.6.6, 203.0.113.7", "203.0.113.7",
"http://localhost");
MockHttpServletRequest direct = new MockHttpServletRequest("GET", "/__app/about");
direct.setAttribute(ProxyResolution.ATTRIBUTE, new ProxyResolution("198.51.100.9", false, false,
new ForwardedFor.Chain(List.of("6.6.6.6"), 1), "198.51.100.9"));
assertThat(info.request(direct)).extracting(RuntimeInfoService.NameValue::value)
.containsExactly("198.51.100.9 (not a trusted proxy)", "6.6.6.6 (ignored)", "198.51.100.9",
"http://localhost");
MockHttpServletRequest none = new MockHttpServletRequest("GET", "/__app/about");
none.setAttribute(ProxyResolution.ATTRIBUTE,
new ProxyResolution("127.0.0.1", true, true, ForwardedFor.Chain.NONE, "127.0.0.1"));
assertThat(info.request(none)).extracting(RuntimeInfoService.NameValue::value)
.containsExactly("127.0.0.1 (trusted proxy)", "none", "127.0.0.1", "http://localhost");
}
@Test
void aboutRequiresAuthentication() throws Exception {
mvc().perform(get("/__app/about")).andExpect(status().is3xxRedirection());
@@ -2,6 +2,7 @@ package mx.quest.runway.console;
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 static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestBuilders.formLogin;
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf;
@@ -9,6 +10,7 @@ import static org.springframework.security.test.web.servlet.setup.SecurityMockMv
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.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.flash;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import java.io.IOException;
@@ -214,26 +216,62 @@ class AppSettingsScreenTest {
assertTrue(smtp.isConfigured());
}
private org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder passwordSave(String host,
String password)
throws Exception {
return passwordSave(host, password, "postmaster");
}
private org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder passwordSave(String host,
String password,
String username)
throws Exception {
return post("/__app/settings").session(sessionFor("admin")).with(csrf())
.param("defaultSiteId", "").param("passwordStrength", "")
.param("smtpHost", host).param("smtpFrom", "noreply@example.com")
.param("smtpAuth", "true").param("smtpUsername", username)
.param("smtpPassword", password);
}
@Test
void aBlankPasswordOnResavePreservesTheStoredSecret() throws Exception {
mvc.perform(post("/__app/settings").session(sessionFor("admin")).with(csrf())
.param("defaultSiteId", "").param("passwordStrength", "")
.param("smtpHost", "smtp.example.com").param("smtpFrom", "noreply@example.com")
.param("smtpAuth", "true").param("smtpUsername", "postmaster")
.param("smtpPassword", "original"))
.andExpect(status().is3xxRedirection());
void thePasswordAlsoFollowsThePortAndTheUsername() throws Exception {
mvc.perform(passwordSave("smtp.example.com", "original")).andExpect(status().is3xxRedirection());
mvc.perform(passwordSave("smtp.example.com", "").param("smtpPort", "2525"))
.andExpect(flash().attribute("flash", Matchers.containsString("SMTP password was cleared")));
assertNull(platform.get().smtp().password(), "another port: not sent there");
mvc.perform(passwordSave("smtp.example.com", "retyped").param("smtpPort", "2525"))
.andExpect(flash().attribute("flash", "Platform settings saved."));
mvc.perform(passwordSave("smtp.example.com", "", "someone-else").param("smtpPort", "2525"))
.andExpect(flash().attribute("flash", Matchers.containsString("SMTP password was cleared")));
assertNull(platform.get().smtp().password(), "another account: not sent for it");
}
@Test
void aBlankPasswordOnResaveKeepsTheStoredSecretOnlyForTheSameServer() throws Exception {
mvc.perform(passwordSave("smtp.example.com", "original")).andExpect(status().is3xxRedirection());
String stored = platform.get().smtp().password();
// Re-save with the password field BLANK and a changed host: the stored secret must be kept.
mvc.perform(post("/__app/settings").session(sessionFor("admin")).with(csrf())
.param("defaultSiteId", "").param("passwordStrength", "")
.param("smtpHost", "smtp2.example.com").param("smtpFrom", "noreply@example.com")
.param("smtpAuth", "true").param("smtpUsername", "postmaster")
.param("smtpPassword", ""))
.andExpect(status().is3xxRedirection());
// Same server, password field blank, another field changed: the stored secret is kept.
mvc.perform(passwordSave("SMTP.example.com", "").param("smtpStarttls", "true"))
.andExpect(flash().attribute("flash", "Platform settings saved."));
assertEquals(stored, platform.get().smtp().password(), "same host (any case): the secret stays");
// Another server with the field blank: the secret is not sent there, it is cleared and must be re-entered.
mvc.perform(passwordSave("smtp.attacker.example", ""))
.andExpect(status().is3xxRedirection())
.andExpect(flash().attribute("flash", Matchers.containsString("SMTP password was cleared")));
PlatformSettings.Smtp after = platform.get().smtp();
assertEquals(stored, after.password(), "a blank password field keeps the stored secret");
assertEquals("smtp2.example.com", after.host(), "the other fields still update");
assertNull(after.password(), "a blank field never carries the secret to a new host");
assertEquals("smtp.attacker.example", after.host(), "the other fields still update");
assertTrue(activityLog.tail(5).stream().anyMatch(line -> line.contains("platform.settings-changed")
&& line.contains("mail host") && line.contains("cleared SMTP password")
&& !line.contains("attacker")), "the log names what changed, never a value");
// Retyped with the new host: stored again.
mvc.perform(passwordSave("smtp.attacker.example", "retyped"))
.andExpect(flash().attribute("flash", "Platform settings saved."));
assertTrue(platform.get().smtp().password().startsWith("ENC("));
}
@Test
@@ -251,6 +289,117 @@ class AppSettingsScreenTest {
.andExpect(content().string(Matchers.not(Matchers.containsString("ENC("))));
}
private org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder oauthSave(String tokenUrl,
String secret,
boolean starttls)
throws Exception {
return oauthSave(tokenUrl, secret, starttls, "smtp.office365.com", "587", "client-1",
"https://outlook.office365.com/.default");
}
private org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder oauthSave(String tokenUrl,
String secret, boolean starttls, String host, String port, String clientId, String scope) throws Exception {
var post = post("/__app/settings").session(sessionFor("admin")).with(csrf())
.param("defaultSiteId", "").param("passwordStrength", "")
.param("smtpHost", host).param("smtpPort", port)
.param("smtpFrom", "noreply@example.com")
.param("smtpAuth", "true").param("smtpUsername", "noreply@example.com")
.param("smtpAuthMethod", "oauth2").param("smtpOauthTokenUrl", tokenUrl)
.param("smtpOauthClientId", clientId).param("smtpOauthClientSecret", secret)
.param("smtpOauthScope", scope);
return starttls ? post.param("smtpStarttls", "true") : post;
}
@Test
void theClientSecretFollowsTheClientTheMailServerAndTheScope() throws Exception {
String endpoint = "https://login.microsoftonline.com/t-1/oauth2/v2.0/token";
String scope = "https://outlook.office365.com/.default";
mvc.perform(oauthSave(endpoint, "client-s3cret", true)).andExpect(flash().attributeExists("flash"));
String stored = platform.get().smtp().oauthClientSecret();
// Each with the secret field blank: refused, nothing changed. The token minted from the secret would go to
// that server, or be asked for another scope.
for (var move : List.of(oauthSave(endpoint, "", true, "smtp.attacker.example", "587", "client-1", scope),
oauthSave(endpoint, "", true, "smtp.office365.com", "2525", "client-1", scope),
oauthSave(endpoint, "", true, "smtp.office365.com", "587", "client-2", scope),
oauthSave(endpoint, "", true, "smtp.office365.com", "587", "client-1", "https://graph.example/.default"))) {
mvc.perform(move).andExpect(flash().attribute("error",
Matchers.containsString("Enter the OAuth2 client secret again")));
PlatformSettings.Smtp now = platform.get().smtp();
assertEquals(stored, now.oauthClientSecret());
assertEquals("smtp.office365.com", now.host());
assertEquals(587, now.port());
assertEquals("client-1", now.oauthClientId());
assertEquals(scope, now.oauthScope());
}
// The same move with the secret typed again is saved.
mvc.perform(oauthSave(endpoint, "typed-again", true, "smtp.example.net", "587", "client-1", scope))
.andExpect(flash().attribute("flash", "Platform settings saved."));
assertEquals("smtp.example.net", platform.get().smtp().host());
}
@Test
void savingAnOAuth2AccountStoresItAndEncryptsTheClientSecret() throws Exception {
mvc.perform(oauthSave("https://login.microsoftonline.com/t-1/oauth2/v2.0/token", "client-s3cret", true))
.andExpect(status().is3xxRedirection())
.andExpect(flash().attributeExists("flash"));
PlatformSettings.Smtp smtp = platform.get().smtp();
assertTrue(smtp.usesOAuth2());
assertEquals("https://login.microsoftonline.com/t-1/oauth2/v2.0/token", smtp.oauthTokenUrl());
assertEquals("client-1", smtp.oauthClientId());
assertEquals("https://outlook.office365.com/.default", smtp.oauthScope());
assertTrue(smtp.oauthClientSecret().startsWith("ENC("), "the client secret is stored encrypted");
assertFalse(smtp.oauthClientSecret().contains("client-s3cret"));
// Re-save with the secret field blank: the stored secret is kept.
String stored = smtp.oauthClientSecret();
mvc.perform(oauthSave("https://login.microsoftonline.com/t-1/oauth2/v2.0/token", "", true))
.andExpect(flash().attributeExists("flash"));
assertEquals(stored, platform.get().smtp().oauthClientSecret());
// A new token endpoint with the field blank is refused: the stored secret is never sent to it.
mvc.perform(oauthSave("https://login.attacker.example/token", "", true))
.andExpect(flash().attribute("error", Matchers.containsString("Enter the OAuth2 client secret again")));
assertEquals("https://login.microsoftonline.com/t-1/oauth2/v2.0/token", platform.get().smtp().oauthTokenUrl(),
"the refused save changed nothing");
assertEquals(stored, platform.get().smtp().oauthClientSecret());
mvc.perform(get("/__app/settings").session(sessionFor("admin")))
.andExpect(status().isOk())
.andExpect(content().string(Matchers.containsString("name=\"smtpOauthClientSecret\"")))
.andExpect(content().string(Matchers.containsString(
"value=\"https://login.microsoftonline.com/t-1/oauth2/v2.0/token\"")))
.andExpect(content().string(Matchers.matchesRegex(
"(?s).*<option[^>]*value=\"oauth2\"[^>]*selected.*|.*<option[^>]*selected[^>]*value=\"oauth2\".*")))
.andExpect(content().string(Matchers.not(Matchers.containsString("client-s3cret"))))
.andExpect(content().string(Matchers.not(Matchers.containsString("ENC("))));
}
@Test
void anOAuth2AccountWithoutTlsOrWithAPlainHttpEndpointIsRefusedOnSave() throws Exception {
mvc.perform(oauthSave("https://login.microsoftonline.com/t-1/oauth2/v2.0/token", "x", false))
.andExpect(flash().attribute("error", Matchers.containsString("STARTTLS or implicit TLS")));
mvc.perform(oauthSave("http://login.example.com/token", "x", true))
.andExpect(flash().attribute("error", Matchers.containsString("must use https")));
mvc.perform(oauthSave("https://login.microsoftonline.com/t-1/oauth2/v2.0/token", "", true))
.andExpect(flash().attribute("error", Matchers.containsString("client secret")));
assertNull(platform.get().smtp(), "nothing was stored");
}
@Test
void aTestEmailThatCannotGetATokenSaysSo() throws Exception {
// Loopback http is allowed; nothing listens on port 1, so the token request fails before any SMTP.
mvc.perform(oauthSave("http://127.0.0.1:1/token", "x", true)).andExpect(flash().attributeExists("flash"));
mvc.perform(post("/__app/settings/test-email").session(sessionFor("admin")).with(csrf())
.param("testTo", "someone@example.com"))
.andExpect(status().is3xxRedirection())
.andExpect(flash().attribute("error", Matchers.allOf(
Matchers.containsString("no OAuth2 token"),
Matchers.containsString("OAuth2 token request to 127.0.0.1 failed"))));
}
@Test
void aTestEmailWithoutAConfiguredAccountRedirectsWithoutSending() throws Exception {
// Nothing configured (EMPTY seeded in setUp): the test action must not 500 — it redirects with an error.
@@ -80,6 +80,10 @@ class AppSiteHostsScreenTest {
sites.save(new Site("beta", "Beta", List.of("beta.test"), EN, List.of(EN), null, SiteStatus.ACTIVE));
sites.save(new Site("gamma", "Gamma", List.of("gamma.test"), EN, List.of(EN), null, SiteStatus.ACTIVE));
sites.save(new Site("delta", "Delta", List.of("delta.test"), EN, List.of(EN), null, SiteStatus.ACTIVE));
// The default site: with runway.console.hosts unset, the console's reset links go to its address.
sites.save(new Site("main", "Main", List.of("main.test"), EN, List.of(EN), null, SiteStatus.ACTIVE));
new mx.quest.runway.platform.PlatformSettingsStore(StorageLayout.from(props), new YamlStore())
.update(current -> current.withDefaultSiteId("main"));
new GrantStore(StorageLayout.from(props), new YamlStore())
.saveAppGrants(GrantFile.empty().withUserPermission("app-hosts", "MANAGE_SITE_HOSTS"));
registry.add("runway.storage.external", () -> external.toString());
@@ -151,6 +155,29 @@ class AppSiteHostsScreenTest {
.andExpect(status().isForbidden());
}
@Test
void onlyAPlatformAdminChangesTheDefaultSitesHostsOrBaseUrl() throws Exception {
MockHttpSession hoster = login("hoster", OPERATOR_PW);
mvc.perform(post("/__app/sites/main/hosts").session(hoster).with(csrf())
.param("hosts", "main.test").param("baseUrl", "https://evil.example"))
.andExpect(status().isForbidden());
mvc.perform(post("/__app/sites/main/hosts").session(hoster).with(csrf()).param("hosts", "evil.example"))
.andExpect(status().isForbidden());
Site main = siteStore.find("main").orElseThrow();
assertEquals(List.of("main.test"), main.hosts());
assertEquals(null, main.baseUrl());
String html = mvc.perform(get("/__app/sites").session(hoster)).andReturn().getResponse().getContentAsString();
assertFalse(html.contains("/__app/sites/main/hosts"), "no Edit hosts on the default site's row for them");
assertTrue(html.contains("/__app/sites/gamma/hosts") || html.contains("/__app/sites/acme/hosts"),
"the other rows keep it");
MockHttpSession master = login("admin", MASTER_PW);
mvc.perform(post("/__app/sites/main/hosts").session(master).with(csrf())
.param("hosts", "main.test, www.main.test"))
.andExpect(status().is3xxRedirection());
assertEquals(List.of("main.test", "www.main.test"), siteStore.find("main").orElseThrow().hosts());
}
@Test
void theBaseUrlIsSetCheckedAndClearedInTheSameDialog() throws Exception {
MockHttpSession session = login("admin", MASTER_PW);
@@ -13,6 +13,7 @@ import java.io.IOException;
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.platform.PlatformSettings;
import mx.quest.runway.platform.PlatformSettingsStore;
@@ -23,6 +24,9 @@ import mx.quest.runway.security.PasswordStrength;
import mx.quest.runway.security.Roles;
import mx.quest.runway.security.User;
import mx.quest.runway.security.UserStore;
import mx.quest.runway.site.Site;
import mx.quest.runway.site.SiteStatus;
import mx.quest.runway.site.SiteStore;
import mx.quest.runway.spi.model.Realm;
import mx.quest.runway.storage.YamlStore;
import org.hamcrest.Matchers;
@@ -71,6 +75,8 @@ class RecoveryScreenTest {
private RecoveryTokenStore tokens;
@Autowired
private AppUserStore appUsers;
@Autowired
private SiteStore sites;
private MockMvc mvc;
@BeforeEach
@@ -160,12 +166,21 @@ class RecoveryScreenTest {
}
@Test
void theLoginPageShowsForgotOnlyWhenMailIsConfigured() throws Exception {
void theLoginPageShowsForgotOnlyWithMailAndAnAddressForTheLink() throws Exception {
mvc.perform(get("/app/login"))
.andExpect(status().isOk())
.andExpect(content().string(Matchers.not(Matchers.containsString("/app/forgot-password"))));
// Mail alone is not enough: with no runway.console.hosts and no default site with a host name, there is no
// address a reset link may point at (never the request's own host), so recovery is not offered.
configureMail();
mvc.perform(get("/app/login"))
.andExpect(status().isOk())
.andExpect(content().string(Matchers.not(Matchers.containsString("/app/forgot-password"))));
sites.save(new Site("main", "Main", List.of("www.main.test"), Locale.ENGLISH, List.of(Locale.ENGLISH), null,
SiteStatus.ACTIVE, false, null));
platform.update(current -> current.withDefaultSiteId("main"));
mvc.perform(get("/app/login"))
.andExpect(status().isOk())
.andExpect(content().string(Matchers.containsString("/app/forgot-password")));
@@ -191,6 +191,6 @@ class TenantAuditRecordingTest {
@Test
void aTenantSignOutIsJournaled() throws Exception {
mvc.perform(post("/logout").session(admin()).with(csrf())).andExpect(status().is3xxRedirection());
verify(siteLog).audit("acme", "admin", "logout", "");
verify(siteLog).audit("acme", "admin", "logout", "ip=127.0.0.1"); // MockMvc's client address
}
}
@@ -22,7 +22,7 @@ import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.junit.jupiter.api.AfterEach;
/** The audit listener records tenant login outcomes, and skips app-realm logins (no bound site). */
/** The audit listener records tenant login outcomes with the client address, and skips app-realm logins. */
class AuditEventListenerTest {
private static Site site() {
@@ -88,7 +88,26 @@ class AuditEventListenerTest {
new AuditEventListener(resolver, logs)
.onLogout(new LogoutSuccessEvent(new UsernamePasswordAuthenticationToken("bob", "x")));
verify(logs).audit("acme", "bob", "logout", "");
verify(logs).audit("acme", "bob", "logout", "ip=127.0.0.1");
}
@Test
void aLoginRecordsTheResolvedClientAddressNotTheProxy() {
SiteResolver resolver = mock(SiteResolver.class);
when(resolver.current()).thenReturn(Optional.of(site()));
SiteLogService logs = mock(SiteLogService.class);
MockHttpServletRequest request = new MockHttpServletRequest("POST", "/login");
request.setRemoteAddr("198.51.100.7"); // what TrustedForwardedHeaderFilter left after reading the proxy's XFF
request.addHeader("X-Forwarded-For", "203.0.113.66"); // never read here
RequestContextHolder.setRequestAttributes(new ServletRequestAttributes(request));
AuditEventListener listener = new AuditEventListener(resolver, logs);
listener.onSuccess(new AuthenticationSuccessEvent(new UsernamePasswordAuthenticationToken("bob", "x")));
listener.onFailure(new AuthenticationFailureBadCredentialsEvent(
new UsernamePasswordAuthenticationToken("mallory", "x"), new BadCredentialsException("bad")));
verify(logs).audit("acme", "bob", "login.success", "ip=198.51.100.7");
verify(logs).audit("acme", "mallory", "login.failure", "ip=198.51.100.7");
}
@Test
@@ -0,0 +1,362 @@
package mx.quest.runway.mail;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import com.sun.net.httpserver.HttpServer;
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.time.Clock;
import java.time.Duration;
import java.time.Instant;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
/**
* The OAuth2 client-credentials exchange against a real HTTP server on loopback: what is posted, what is cached and
* for how long, how a refusal is reported (with the provider's reason and never the secret), and which endpoints are
* accepted at all.
*/
class OAuth2TokenClientTest {
private static final String SECRET = "s3cr3t~value+/=";
/** A clock the test moves by hand. */
private static final class TestClock extends Clock {
Instant now = Instant.parse("2026-10-28T22:00:00Z");
@Override public ZoneId getZone() {
return ZoneOffset.UTC;
}
@Override public Clock withZone(ZoneId zone) {
return this;
}
@Override public Instant instant() {
return now;
}
}
private HttpServer server;
private final List<Map<String, String>> posted = new ArrayList<>();
private final List<String> contentTypes = new ArrayList<>();
private volatile int status = 200;
private volatile String responseBody;
private volatile String location;
private int issued;
private final TestClock clock = new TestClock();
private OAuth2TokenClient client;
@BeforeEach
void start() throws IOException {
server = HttpServer.create(new InetSocketAddress(InetAddress.getLoopbackAddress(), 0), 0);
server.createContext("/tenant/oauth2/v2.0/token", exchange -> {
String form = new String(exchange.getRequestBody().readAllBytes(), StandardCharsets.UTF_8);
Map<String, String> fields = new LinkedHashMap<>();
for (String pair : form.split("&")) {
String[] kv = pair.split("=", 2);
fields.put(URLDecoder.decode(kv[0], StandardCharsets.UTF_8),
kv.length > 1 ? URLDecoder.decode(kv[1], StandardCharsets.UTF_8) : "");
}
synchronized (posted) {
posted.add(fields);
contentTypes.add(exchange.getRequestHeaders().getFirst("Content-Type"));
issued++;
}
String body = responseBody != null ? responseBody
: "{\"token_type\":\"Bearer\",\"expires_in\":3600,\"access_token\":\"token-" + issued + "\"}";
if (location != null) {
exchange.getResponseHeaders().add("Location", location);
}
byte[] bytes = body.getBytes(StandardCharsets.UTF_8);
exchange.sendResponseHeaders(status, bytes.length);
try (OutputStream out = exchange.getResponseBody()) {
out.write(bytes);
}
});
server.start();
// The application's own client, so a test of redirects or timeouts tests what runs in production.
client = new OAuth2TokenClient(OAuth2TokenClient.httpClient(), clock);
}
@AfterEach
void stop() {
server.stop(0);
}
private OAuth2TokenClient.Request request() {
return new OAuth2TokenClient.Request(
"http://127.0.0.1:" + server.getAddress().getPort() + "/tenant/oauth2/v2.0/token",
"client-123", SECRET, "https://outlook.office365.com/.default");
}
@Test
void postsAClientCredentialsGrantAndReturnsTheToken() throws Exception {
assertThat(client.token(request())).isEqualTo("token-1");
assertThat(posted).hasSize(1);
assertThat(posted.getFirst()).containsExactly(
Map.entry("grant_type", "client_credentials"),
Map.entry("client_id", "client-123"),
Map.entry("client_secret", SECRET), // form-encoded on the wire, decoded intact
Map.entry("scope", "https://outlook.office365.com/.default"));
assertThat(contentTypes.getFirst()).isEqualTo("application/x-www-form-urlencoded");
}
@Test
void aBlankScopeIsNotSent() throws Exception {
OAuth2TokenClient.Request r = request();
client.token(new OAuth2TokenClient.Request(r.tokenUrl(), r.clientId(), r.clientSecret(), " "));
assertThat(posted.getFirst()).doesNotContainKey("scope");
}
@Test
void aTokenIsReusedUntilFiveMinutesBeforeItExpires() throws Exception {
assertThat(client.token(request())).isEqualTo("token-1");
clock.now = clock.now.plusSeconds(3600 - 300 - 1);
assertThat(client.token(request())).isEqualTo("token-1");
assertThat(posted).hasSize(1);
clock.now = clock.now.plusSeconds(1);
assertThat(client.token(request())).isEqualTo("token-2");
assertThat(posted).hasSize(2);
}
@Test
void aShortLivedTokenIsRenewedAtHalfItsLifetime() throws Exception {
responseBody = "{\"token_type\":\"Bearer\",\"expires_in\":\"60\",\"access_token\":\"short\"}";
client.token(request());
clock.now = clock.now.plusSeconds(29);
client.token(request());
assertThat(posted).hasSize(1);
clock.now = clock.now.plusSeconds(1);
client.token(request());
assertThat(posted).hasSize(2);
}
@Test
void changingAnyPartOfTheRequestOrForgettingAsksAgain() throws Exception {
client.token(request());
OAuth2TokenClient.Request r = request();
assertThat(client.token(new OAuth2TokenClient.Request(r.tokenUrl(), r.clientId(), "rotated", r.scope())))
.isEqualTo("token-2");
assertThat(client.token(new OAuth2TokenClient.Request(r.tokenUrl(), "other", "rotated", r.scope())))
.isEqualTo("token-3");
client.forget();
assertThat(client.token(new OAuth2TokenClient.Request(r.tokenUrl(), "other", "rotated", r.scope())))
.isEqualTo("token-4");
}
@Test
void aRefusalNamesTheStatusAndTheProvidersReasonButNeverTheSecret() {
status = 401;
responseBody = "{\"error\":\"invalid_client\",\"error_description\":\"AADSTS7000215: Invalid client "
+ "secret provided.\\r\\nTrace ID: abc\"}";
assertThatThrownBy(() -> client.token(request()))
.isInstanceOf(OAuth2TokenClient.TokenException.class)
.hasMessageContaining("127.0.0.1")
.hasMessageContaining("HTTP 401")
.hasMessageContaining("invalid_client")
.hasMessageContaining("AADSTS7000215: Invalid client secret provided. Trace ID: abc")
.hasMessageNotContaining(SECRET);
}
@Test
void aRefusalIsNotCached() throws Exception {
status = 500;
responseBody = "oops";
assertThatThrownBy(() -> client.token(request())).hasMessageContaining("HTTP 500");
status = 200;
responseBody = null;
assertThat(client.token(request())).isEqualTo("token-2");
}
@Test
void aResponseWithoutABearerTokenIsRefused() {
responseBody = "{\"token_type\":\"Bearer\",\"expires_in\":3600}";
assertThatThrownBy(() -> client.token(request())).hasMessageContaining("has no access_token");
responseBody = "{\"token_type\":\"mac\",\"access_token\":\"t\"}";
assertThatThrownBy(() -> client.token(request())).hasMessageContaining("not a bearer token");
responseBody = "<html>login page</html>";
assertThatThrownBy(() -> client.token(request())).hasMessageContaining("has no access_token");
}
@Test
void anOversizedResponseIsRefused() {
responseBody = "{\"access_token\":\"" + "a".repeat(OAuth2TokenClient.MAX_RESPONSE_BYTES) + "\"}";
assertThatThrownBy(() -> client.token(request())).hasMessageContaining("larger than");
}
@Test
void aServerThatStallsInTheMiddleOfTheBodyIsCutOffAtTheDeadline() throws Exception {
CountDownLatch release = new CountDownLatch(1);
server.createContext("/stall", exchange -> {
exchange.getRequestBody().readAllBytes();
exchange.sendResponseHeaders(200, 1000); // headers at once, then the body never comes
try (OutputStream out = exchange.getResponseBody()) {
out.write("{\"access_token\":".getBytes(StandardCharsets.UTF_8));
out.flush();
release.await(30, TimeUnit.SECONDS);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
} catch (IOException closed) {
// the client gave up
}
});
OAuth2TokenClient bounded = new OAuth2TokenClient(OAuth2TokenClient.httpClient(), clock,
Duration.ofSeconds(2));
OAuth2TokenClient.Request r = request();
long start = System.nanoTime();
try {
assertThatThrownBy(() -> bounded.token(new OAuth2TokenClient.Request(
r.tokenUrl().replace("/tenant/oauth2/v2.0/token", "/stall"), r.clientId(), r.clientSecret(),
r.scope())))
.isInstanceOf(OAuth2TokenClient.TokenException.class)
.hasMessageContaining("did not complete within 2 seconds");
} finally {
release.countDown();
}
assertThat(Duration.ofNanos(System.nanoTime() - start)).isLessThan(Duration.ofSeconds(10));
}
@Test
void sendersWaitingOnAStalledProviderShareOneRequestAndOneDeadline() throws Exception {
CountDownLatch release = new CountDownLatch(1);
java.util.concurrent.atomic.AtomicInteger stalled = new java.util.concurrent.atomic.AtomicInteger();
server.createContext("/stall", exchange -> {
stalled.incrementAndGet();
exchange.getRequestBody().readAllBytes();
try {
release.await(30, TimeUnit.SECONDS); // no answer at all
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
exchange.close();
});
OAuth2TokenClient bounded = new OAuth2TokenClient(OAuth2TokenClient.httpClient(), clock,
Duration.ofSeconds(2));
OAuth2TokenClient.Request r = request();
OAuth2TokenClient.Request stalling = new OAuth2TokenClient.Request(
r.tokenUrl().replace("/tenant/oauth2/v2.0/token", "/stall"), r.clientId(), r.clientSecret(), r.scope());
java.util.concurrent.ExecutorService senders = java.util.concurrent.Executors.newFixedThreadPool(4);
long start = System.nanoTime();
try {
List<java.util.concurrent.Future<Throwable>> results = new ArrayList<>();
for (int i = 0; i < 4; i++) {
results.add(senders.submit(() -> {
try {
bounded.token(stalling);
return null;
} catch (Throwable t) {
return t;
}
}));
}
for (var result : results) {
assertThat(result.get(20, TimeUnit.SECONDS)).isInstanceOf(OAuth2TokenClient.TokenException.class);
}
} finally {
release.countDown();
senders.shutdownNow();
}
// One deadline for all four (2 s, plus a moment), not four in turn.
assertThat(Duration.ofNanos(System.nanoTime() - start)).isLessThan(Duration.ofMillis(4500));
assertThat(stalled.get()).isEqualTo(1);
}
@Test
void concurrentSendersGetOneTokenFromOneRequest() throws Exception {
java.util.concurrent.ExecutorService senders = java.util.concurrent.Executors.newFixedThreadPool(4);
try {
List<java.util.concurrent.Future<String>> tokens = new ArrayList<>();
for (int i = 0; i < 4; i++) {
tokens.add(senders.submit(() -> client.token(request())));
}
for (var token : tokens) {
assertThat(token.get(20, TimeUnit.SECONDS)).isEqualTo("token-1");
}
} finally {
senders.shutdownNow();
}
assertThat(issued).isEqualTo(1);
}
@Test
void aRedirectIsNotFollowedSoTheSecretGoesNowhereElse() {
status = 302;
location = "https://elsewhere.example/steal";
responseBody = "";
assertThatThrownBy(() -> client.token(request())).hasMessageContaining("HTTP 302");
// 307 is the one a following client would answer by POSTing the form, secret included, again.
status = 307;
location = "/tenant/oauth2/v2.0/token";
assertThatThrownBy(() -> client.token(request())).hasMessageContaining("HTTP 307");
assertThat(posted).hasSize(2); // one POST per call: nothing re-sent
}
@Test
void anUnreachableEndpointIsReportedAsATokenFailure() {
server.stop(0);
assertThatThrownBy(() -> client.token(request()))
.isInstanceOf(OAuth2TokenClient.TokenException.class)
.hasMessageContaining("OAuth2 token request to 127.0.0.1 failed");
}
@Test
void onlyHttpsOrLoopbackHttpEndpointsAreAccepted() throws Exception {
assertThat(OAuth2TokenClient.endpoint(endpoint("https://login.microsoftonline.com/t/oauth2/v2.0/token")))
.hasHost("login.microsoftonline.com");
assertThat(OAuth2TokenClient.endpoint(endpoint("http://localhost:9000/token"))).hasHost("localhost");
assertThat(OAuth2TokenClient.endpoint(endpoint("http://[::1]:9000/token"))).hasPort(9000);
for (String refused : List.of("http://login.example.com/token", "http://10.0.0.5/token",
"ftp://login.example.com/token", "https://user:pw@login.example.com/token",
"https://login.example.com/token#x", "login.example.com/token", "https://", "not a url")) {
assertThatThrownBy(() -> OAuth2TokenClient.endpoint(endpoint(refused)))
.as(refused).isInstanceOf(OAuth2TokenClient.TokenException.class);
}
}
@Test
void anIncompleteRequestIsRefusedBeforeAnyCall() {
for (OAuth2TokenClient.Request incomplete : List.of(
new OAuth2TokenClient.Request(null, "c", "s", null),
new OAuth2TokenClient.Request("https://l.example/t", " ", "s", null),
new OAuth2TokenClient.Request("https://l.example/t", "c", null, null))) {
assertThatThrownBy(() -> client.token(incomplete)).hasMessageContaining("needs a token endpoint");
}
assertThat(posted).isEmpty();
}
@Test
void theRequestNeverPrintsItsSecret() {
assertThat(request().toString()).doesNotContain(SECRET).contains("client-123");
}
private static OAuth2TokenClient.Request endpoint(String url) {
return new OAuth2TokenClient.Request(url, "c", "s", null);
}
}
@@ -6,12 +6,16 @@ import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import jakarta.mail.AuthenticationFailedException;
import jakarta.mail.Message;
import jakarta.mail.MessagingException;
import jakarta.mail.PasswordAuthentication;
import jakarta.mail.Session;
import jakarta.mail.internet.MimeMessage;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;
import java.util.concurrent.atomic.AtomicReference;
import mx.quest.runway.crypto.SecretCipher;
import mx.quest.runway.platform.PlatformSettings;
@@ -76,7 +80,7 @@ class PlatformMailerTest {
@Test
void isConfiguredReflectsHostAndFrom(@TempDir Path root) {
PlatformSettingsStore settings = store(root);
PlatformMailer mailer = new PlatformMailer(settings, new RecordingCipher(), new CapturingTransport());
PlatformMailer mailer = new PlatformMailer(settings, new RecordingCipher(), new CapturingTransport(), new OAuth2TokenClient());
assertFalse(mailer.isConfigured(), "no smtp block ⇒ not configured");
settings.update(previous -> PlatformSettings.EMPTY.withSmtp(
@@ -94,7 +98,7 @@ class PlatformMailerTest {
settings.update(previous -> PlatformSettings.EMPTY.withSmtp(
new PlatformSettings.Smtp("smtp.example.com", 587, false, null, null, "noreply@example.com", true, false)));
CapturingTransport transport = new CapturingTransport();
PlatformMailer mailer = new PlatformMailer(settings, new RecordingCipher(), transport);
PlatformMailer mailer = new PlatformMailer(settings, new RecordingCipher(), transport, new OAuth2TokenClient());
mailer.send("user@example.org", "Reset your password", "Click the link.");
@@ -110,7 +114,7 @@ class PlatformMailerTest {
void anUnconfiguredAccountRefusesToSend(@TempDir Path root) {
PlatformSettingsStore settings = store(root);
CapturingTransport transport = new CapturingTransport();
PlatformMailer mailer = new PlatformMailer(settings, new RecordingCipher(), transport);
PlatformMailer mailer = new PlatformMailer(settings, new RecordingCipher(), transport, new OAuth2TokenClient());
assertThrows(MessagingException.class, () -> mailer.send("a@b.com", "s", "b"));
assertEquals(0, transport.count, "nothing is sent when the platform account is not configured");
@@ -128,7 +132,7 @@ class PlatformMailerTest {
}
};
CapturingTransport transport = new CapturingTransport();
PlatformMailer mailer = new PlatformMailer(settings, wrongKey, transport);
PlatformMailer mailer = new PlatformMailer(settings, wrongKey, transport, new OAuth2TokenClient());
// Callers handle MessagingException (recovery stays non-enumerating, the test-send shows an error);
// an IllegalStateException would escape them.
@@ -144,7 +148,7 @@ class PlatformMailerTest {
String stored = cipher.encrypt("hunter2");
settings.update(previous -> PlatformSettings.EMPTY.withSmtp(new PlatformSettings.Smtp(
"smtp.example.com", 587, true, "postmaster", stored, "noreply@example.com", true, false)));
PlatformMailer mailer = new PlatformMailer(settings, cipher, new CapturingTransport());
PlatformMailer mailer = new PlatformMailer(settings, cipher, new CapturingTransport(), new OAuth2TokenClient());
mailer.send("user@example.org", "s", "b");
@@ -160,7 +164,7 @@ class PlatformMailerTest {
// mail.transport.protocol); a "smtps" value left mail.smtp.host unset, so the send dialed localhost:25 and
// failed with "Connection refused". Implicit TLS must ride mail.smtp.ssl.enable on the smtp protocol.
RecordingCipher cipher = new RecordingCipher();
PlatformMailer mailer = new PlatformMailer(store(root), cipher, new CapturingTransport());
PlatformMailer mailer = new PlatformMailer(store(root), cipher, new CapturingTransport(), new OAuth2TokenClient());
Session s = mailer.session(new PlatformSettings.Smtp(
"mail.example.com", 465, true, "postmaster", cipher.encrypt("pw"), "noreply@example.com", false, true));
@@ -175,7 +179,7 @@ class PlatformMailerTest {
@Test
void starttlsRidesStarttlsEnableOnTheSmtpProtocol(@TempDir Path root) throws MessagingException {
PlatformMailer mailer = new PlatformMailer(store(root), new RecordingCipher(), new CapturingTransport());
PlatformMailer mailer = new PlatformMailer(store(root), new RecordingCipher(), new CapturingTransport(), new OAuth2TokenClient());
Session s = mailer.session(new PlatformSettings.Smtp(
"mail.example.com", 587, false, null, null, "noreply@example.com", true, false));
@@ -191,7 +195,7 @@ class PlatformMailerTest {
@Test
void everySessionHasBoundedWaitsAndImplicitTlsChecksTheServerName(@TempDir Path root) throws MessagingException {
RecordingCipher cipher = new RecordingCipher();
PlatformMailer mailer = new PlatformMailer(store(root), cipher, new CapturingTransport());
PlatformMailer mailer = new PlatformMailer(store(root), cipher, new CapturingTransport(), new OAuth2TokenClient());
for (PlatformSettings.Smtp smtp : java.util.List.of(
new PlatformSettings.Smtp("m.example.com", 25, false, null, null, "n@example.com", false, false),
new PlatformSettings.Smtp("m.example.com", 587, false, null, null, "n@example.com", true, false),
@@ -210,4 +214,186 @@ class PlatformMailerTest {
assertEquals("false", plain.getProperty("mail.smtp.starttls.enable"), "plain says so explicitly");
assertNull(plain.getProperty("mail.smtp.starttls.required"));
}
/** A token client that hands out a fixed token and counts what it was asked, with no HTTP. */
private static final class FixedTokens extends OAuth2TokenClient {
final List<Request> asked = new ArrayList<>();
int forgotten;
FixedTokens() {
super(null, java.time.Clock.systemUTC());
}
@Override public synchronized String token(Request request) {
asked.add(request);
return "eyJ0eXAi.token";
}
@Override public synchronized void forget() {
forgotten++;
}
}
private static PlatformSettings.Smtp oauth(RecordingCipher cipher, String username, boolean starttls) {
return new PlatformSettings.Smtp("smtp.office365.com", 587, true, username, null, "noreply@example.com",
starttls, false, PlatformSettings.Smtp.AUTH_OAUTH2,
"https://login.microsoftonline.com/tenant-1/oauth2/v2.0/token", "client-1",
cipher.encrypt("client-secret"), "https://outlook.office365.com/.default");
}
private static PasswordAuthentication credentials(Session session) {
return session.requestPasswordAuthentication(null, 587, "smtp", null, null);
}
@Test
void anOAuth2AccountSignsInWithXoauth2AndTheTokenAsThePassword(@TempDir Path root) throws MessagingException {
RecordingCipher cipher = new RecordingCipher();
FixedTokens tokens = new FixedTokens();
PlatformMailer mailer = new PlatformMailer(store(root), cipher, new CapturingTransport(), tokens);
Session s = mailer.session(oauth(cipher, "mailbox@example.com", true));
assertEquals("XOAUTH2", s.getProperty("mail.smtp.auth.mechanisms"),
"only XOAUTH2: a server without it must not receive the token as a PLAIN password");
assertEquals("true", s.getProperty("mail.smtp.auth"));
assertEquals("true", s.getProperty("mail.smtp.starttls.required"));
PasswordAuthentication pa = credentials(s);
assertEquals("mailbox@example.com", pa.getUserName());
assertEquals("eyJ0eXAi.token", pa.getPassword());
assertEquals(List.of(new OAuth2TokenClient.Request(
"https://login.microsoftonline.com/tenant-1/oauth2/v2.0/token", "client-1", "client-secret",
"https://outlook.office365.com/.default")), tokens.asked, "the client secret was decrypted first");
}
@Test
void anOAuth2AccountWithNoUsernameSendsAsTheFromMailbox(@TempDir Path root) throws MessagingException {
RecordingCipher cipher = new RecordingCipher();
PlatformMailer mailer = new PlatformMailer(store(root), cipher, new CapturingTransport(), new FixedTokens());
assertEquals("noreply@example.com", credentials(mailer.session(oauth(cipher, " ", true))).getUserName());
}
@Test
void anOAuth2AccountWithoutTlsIsRefusedBeforeAnyTokenIsFetched(@TempDir Path root) {
RecordingCipher cipher = new RecordingCipher();
FixedTokens tokens = new FixedTokens();
PlatformMailer mailer = new PlatformMailer(store(root), cipher, new CapturingTransport(), tokens);
MessagingException e = assertThrows(MessagingException.class,
() -> mailer.session(oauth(cipher, "m@example.com", false)));
assertTrue(e.getMessage().contains("STARTTLS or implicit TLS"), e.getMessage());
assertTrue(tokens.asked.isEmpty());
}
@Test
void aPasswordAccountNamesNoMechanism(@TempDir Path root) throws MessagingException {
RecordingCipher cipher = new RecordingCipher();
FixedTokens tokens = new FixedTokens();
PlatformMailer mailer = new PlatformMailer(store(root), cipher, new CapturingTransport(), tokens);
// The OAuth2 fields are ignored while the method is "password" (switching back keeps them stored).
PlatformSettings.Smtp o = oauth(cipher, "u", true);
Session s = mailer.session(new PlatformSettings.Smtp(o.host(), o.port(), true, "u", cipher.encrypt("pw"),
o.from(), true, false, PlatformSettings.Smtp.AUTH_PASSWORD, o.oauthTokenUrl(), o.oauthClientId(),
o.oauthClientSecret(), o.oauthScope()));
assertNull(s.getProperty("mail.smtp.auth.mechanisms"));
assertEquals("pw", credentials(s).getPassword());
assertTrue(tokens.asked.isEmpty());
}
@Test
void aRefusedTokenIsForgottenSoTheNextSendAsksForANewOne(@TempDir Path root) {
RecordingCipher cipher = new RecordingCipher();
PlatformSettingsStore settings = store(root);
settings.update(previous -> PlatformSettings.EMPTY.withSmtp(oauth(cipher, "m@example.com", true)));
FixedTokens tokens = new FixedTokens();
MailTransport refusing = message -> {
throw new AuthenticationFailedException("535 5.7.3 Authentication unsuccessful");
};
PlatformMailer mailer = new PlatformMailer(settings, cipher, refusing, tokens);
assertThrows(AuthenticationFailedException.class, () -> mailer.send("u@example.org", "s", "b"));
assertEquals(1, tokens.forgotten);
}
@Test
void theXoauth2ExchangeOnTheWireCarriesTheMailboxAndTheBearerToken(@TempDir Path root) throws Exception {
// What the mailer configures, sent by the bundled Angus Mail to a scripted SMTP server: proves that "the token
// as the password, with mail.smtp.auth.mechanisms=XOAUTH2" yields RFC-shaped XOAUTH2. Only TLS is switched
// off for the test server; the mailer itself refuses OAuth2 without TLS.
RecordingCipher cipher = new RecordingCipher();
PlatformMailer mailer = new PlatformMailer(store(root), cipher, new CapturingTransport(), new FixedTokens());
Session configured = mailer.session(oauth(cipher, "mailbox@example.com", true));
try (java.net.ServerSocket listener = new java.net.ServerSocket(0, 1, java.net.InetAddress.getLoopbackAddress())) {
java.util.concurrent.CompletableFuture<List<String>> dialogue =
java.util.concurrent.CompletableFuture.supplyAsync(() -> scriptedSmtp(listener));
java.util.Properties props = new java.util.Properties();
props.putAll(configured.getProperties());
props.put("mail.smtp.host", "127.0.0.1");
props.put("mail.smtp.port", String.valueOf(listener.getLocalPort()));
props.put("mail.smtp.starttls.enable", "false");
props.put("mail.smtp.starttls.required", "false");
PasswordAuthentication pa = credentials(configured);
Session session = Session.getInstance(props, new jakarta.mail.Authenticator() {
@Override protected PasswordAuthentication getPasswordAuthentication() {
return pa;
}
});
MimeMessage message = mailer.build(oauth(cipher, "mailbox@example.com", true), "u@example.org", "s", "b");
jakarta.mail.Transport transport = session.getTransport("smtp");
transport.connect();
transport.sendMessage(message, message.getAllRecipients());
transport.close();
List<String> lines = dialogue.get(10, java.util.concurrent.TimeUnit.SECONDS);
String auth = lines.stream().filter(l -> l.startsWith("AUTH ")).findFirst().orElseThrow();
String[] parts = auth.split(" ");
assertEquals("XOAUTH2", parts[1], auth);
assertEquals("user=mailbox@example.com\u0001auth=Bearer eyJ0eXAi.token\u0001\u0001",
new String(Base64.getDecoder().decode(parts[2]), java.nio.charset.StandardCharsets.UTF_8));
assertTrue(lines.contains("MAIL FROM:<noreply@example.com>"), lines.toString());
}
}
/** A one-connection SMTP server offering AUTH XOAUTH2 that accepts anything; returns the client's lines. */
private static List<String> scriptedSmtp(java.net.ServerSocket listener) {
List<String> lines = new ArrayList<>();
try (java.net.Socket socket = listener.accept()) {
socket.setSoTimeout(10_000);
java.io.BufferedReader in = new java.io.BufferedReader(new java.io.InputStreamReader(
socket.getInputStream(), java.nio.charset.StandardCharsets.US_ASCII));
java.io.Writer out = new java.io.OutputStreamWriter(socket.getOutputStream(),
java.nio.charset.StandardCharsets.US_ASCII);
out.write("220 test ESMTP\r\n");
out.flush();
String line;
while ((line = in.readLine()) != null) {
lines.add(line);
String verb = line.length() >= 4 ? line.substring(0, 4).toUpperCase(java.util.Locale.ROOT) : line;
switch (verb) {
case "EHLO" -> out.write("250-test\r\n250-AUTH XOAUTH2 PLAIN LOGIN\r\n250 OK\r\n");
case "AUTH" -> out.write("235 2.7.0 Authentication successful\r\n");
case "DATA" -> {
out.write("354 go\r\n");
out.flush();
String body;
while ((body = in.readLine()) != null && !body.equals(".")) {
// the message itself is not checked here
}
out.write("250 queued\r\n");
}
case "QUIT" -> {
out.write("221 bye\r\n");
out.flush();
return lines;
}
default -> out.write("250 OK\r\n");
}
out.flush();
}
} catch (java.io.IOException e) {
throw new java.io.UncheckedIOException(e);
}
return lines;
}
}
@@ -71,4 +71,32 @@ class PlatformSettingsSmtpTest {
assertFalse(smtp.toString().contains("ENC(secret)"), "the (encrypted) password is masked in toString");
assertTrue(smtp.toString().contains("<set>"));
}
@Test
void theOAuth2FieldsRoundTripAndAPasswordOnlyFileLoadsAsPassword(@TempDir Path root) throws IOException {
PlatformSettingsStore store = store(root);
PlatformSettings.Smtp smtp = new PlatformSettings.Smtp("smtp.office365.com", 587, true, "box@x.io", null,
"box@x.io", true, false, PlatformSettings.Smtp.AUTH_OAUTH2, "https://login.example/t/token", "cid",
"ENC(client)", "https://outlook.office365.com/.default");
store.update(previous -> PlatformSettings.EMPTY.withSmtp(smtp));
assertEquals(smtp, store(root).get().smtp());
assertTrue(store(root).get().smtp().usesOAuth2());
// A 1.0.x file: an smtp block with no OAuth2 keys reads as a password account.
Path file = root.resolve("external").resolve("platform.yml");
Files.writeString(file, "smtp:\n host: \"m.x.io\"\n auth: true\n username: \"u\"\n"
+ " password: \"ENC(p)\"\n from: \"f@x.io\"\n");
PlatformSettings.Smtp old = store(root).get().smtp();
assertEquals("ENC(p)", old.password());
assertNull(old.authMethod());
assertFalse(old.usesOAuth2());
}
@Test
void theSmtpToStringMasksTheClientSecret() {
PlatformSettings.Smtp smtp = new PlatformSettings.Smtp("h", 587, true, "u", null, "f@x", true, false,
PlatformSettings.Smtp.AUTH_OAUTH2, "https://l.example/t", "cid", "ENC(client-secret)", null);
assertFalse(smtp.toString().contains("client-secret"));
assertTrue(smtp.toString().contains("oauthClientSecret=<set>"));
}
}
@@ -33,7 +33,8 @@ class KernelBeanNamesTest {
/** The first-party plugin ids (runway-plugins plus the essential plugin). */
static final List<String> FIRST_PARTY = List.of("blog", "carousel-manager", "contact", "runway-demo",
"discoverability", "search", "search-lucene", "lucene-provider", "protection");
"discoverability", "search", "search-lucene", "lucene-provider", "protection", "database",
"database-postgresql", "database-mariadb", "runway-demo-database");
@DynamicPropertySource
static void config(DynamicPropertyRegistry registry) throws IOException {
@@ -16,6 +16,7 @@ import java.nio.file.Path;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Optional;
import mx.quest.runway.backup.BackupParticipantRegistry;
import mx.quest.runway.content.ContentSourceRegistry;
import mx.quest.runway.endpoint.EndpointContributorRegistry;
@@ -32,6 +33,7 @@ import mx.quest.runway.spi.model.PageView;
import mx.quest.runway.spi.model.RenderFragment;
import mx.quest.runway.spi.model.SiteView;
import mx.quest.runway.spi.model.WidgetView;
import mx.quest.runway.spi.service.PluginSettings;
import mx.quest.runway.widget.ContentWidgetRegistry;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
@@ -392,6 +394,33 @@ class PluginContributionPolicyTest {
return new org.springframework.beans.factory.InjectionPoint(type.getDeclaredField(field));
}
@Test
void theFactoryHandsAPluginItsOwnAppLevelSecretFromTheRunningEnvironmentAndNothingElse() throws Exception {
assumeTrue(PluginFixture.compilerAvailable());
PluginDescriptor withSecret = PluginDescriptor.read(new ByteArrayInputStream((
"id: p1\nversion: 1.0.0\nmainClass: x.Y\nsettings:\n"
+ " - { key: apiKey, type: secret, label: l }\n"
+ " - { key: host, type: string, label: l }\n").getBytes(StandardCharsets.UTF_8)));
PluginOwnership owners = PluginOwnership.of(new PluginRuntime(
List.of(new LoadedPlugin(withSecret, root.resolve("p1")), loaded("p2")), loader, Map.of(), false));
mx.quest.runway.storage.StorageProperties props = new mx.quest.runway.storage.StorageProperties();
props.setExternal(root.resolve("external"));
mx.quest.runway.storage.StorageLayout layout = mx.quest.runway.storage.StorageLayout.from(props);
org.springframework.mock.env.MockEnvironment env = new org.springframework.mock.env.MockEnvironment()
.withProperty("runway.plugin.p1.apiKey", "p1-key")
.withProperty("runway.plugin.p1.host", "db.example")
.withProperty("runway.plugin.p2.apiKey", "p2-key");
PluginScopedServices scoped = new PluginScopedServices(owners,
new SitePluginConfigService(layout, null, event -> { }), null, layout, 1024, env);
PluginSettings p1 = scoped.pluginSettings(pointIn(head("p1", "k", false).getClass(), "key"));
PluginSettings p2 = scoped.pluginSettings(pointIn(head("p2", "k", false).getClass(), "key"));
assertEquals(Optional.of("p1-key"), p1.appSecret("apiKey"), "the running value of its own declared secret");
assertEquals(Optional.empty(), p1.appSecret("host"), "a non-secret app setting is never handed out here");
assertEquals(Optional.empty(), p2.appSecret("apiKey"),
"p2 declared no app-level secret, so the environment's value is not handed out");
}
@Test
void anInjectionPointInAPluginsOwnJarBindsToThatPlugin() throws Exception {
assumeTrue(PluginFixture.compilerAvailable());
@@ -191,4 +191,86 @@ class PluginSettingsImplTest {
assertEquals("Demo's", settings("demo").site("acme").string("title", ""));
assertEquals("Other's", settings("other").site("acme").string("title", ""));
}
// ---- app-level secrets (SPI 1.1.0) -------------------------------------------------------------
private static final List<PluginSettingDef> APP_SCHEMA = List.of(
new PluginSettingDef("password", "secret", null, "l", null),
new PluginSettingDef("host", "string", "localhost", "l", null));
private final java.util.Map<String, String> environment = new java.util.HashMap<>();
private PluginSettingsImpl withApp(String plugin) {
return new PluginSettingsImpl(plugin, SCHEMA, APP_SCHEMA, environment::get, config, cipher);
}
@Test
void anAppSecretIsReadFromTheRunningEnvironmentUnderTheCallersOwnPrefixAndDecrypted() {
environment.put("runway.plugin.database.password", cipher.encrypt("s3cret"));
environment.put("runway.plugin.other.password", "not-mine");
assertEquals(Optional.of("s3cret"), withApp("database").appSecret("password"));
assertEquals(Optional.empty(), withApp("unconfigured").appSecret("password"),
"the lookup is keyed by the bound plugin's own id: another plugin's value is never read");
}
@Test
void aHandWrittenPlaintextAppSecretIsReturnedUnchanged() {
environment.put("runway.plugin.database.password", "plain");
assertEquals(Optional.of("plain"), withApp("database").appSecret("password"));
}
@Test
void onlyAKeyDeclaredSecretInTheAppLevelSchemaIsHandedOut() {
environment.put("runway.plugin.database.host", "db.example");
environment.put("runway.plugin.database.smtpPassword", "site-level-key");
environment.put("runway.plugin.database.undeclared", "x");
PluginSettingsImpl settings = withApp("database");
assertEquals(Optional.empty(), settings.appSecret("host"), "declared, but not a secret");
assertEquals(Optional.empty(), settings.appSecret("smtpPassword"),
"a secret declared only in siteSettings: is not an app-level secret");
assertEquals(Optional.empty(), settings.appSecret("undeclared"));
assertEquals(Optional.empty(), settings.appSecret(null));
}
@Test
void anUnsetBlankOrUndecryptableAppSecretIsEmpty() {
PluginSettingsImpl settings = withApp("database");
assertEquals(Optional.empty(), settings.appSecret("password"), "unset");
environment.put("runway.plugin.database.password", " ");
assertEquals(Optional.empty(), settings.appSecret("password"), "blank");
environment.put("runway.plugin.database.password", cipher.encrypt("s3cret"));
cipherAvailable = false;
assertEquals(Optional.empty(), settings.appSecret("password"), "no usable platform secret key");
cipherAvailable = true;
cipherBroken = true;
assertEquals(Optional.empty(), settings.appSecret("password"), "wrong key or corrupted value");
}
@Test
void theValueFollowsTheEnvironmentItIsHandedNotAFileSavedSinceStartup() {
PluginSettingsImpl settings = withApp("database");
environment.put("runway.plugin.database.password", "first");
assertEquals(Optional.of("first"), settings.appSecret("password"));
environment.put("runway.plugin.database.password", "second");
assertEquals(Optional.of("second"), settings.appSecret("password"), "not cached past the environment");
}
@Test
void theSiteOnlyConstructorHasNoAppSecretsAndTheSpiDefaultIsEmpty() {
environment.put("runway.plugin.database.password", "plain");
assertEquals(Optional.empty(), settings("database").appSecret("password"));
mx.quest.runway.spi.service.PluginSettings bare = new mx.quest.runway.spi.service.PluginSettings() {
@Override
public SettingsView site(String siteId) {
return new SettingsView(java.util.Map.of());
}
@Override
public Optional<String> secret(String siteId, String key) {
return Optional.empty();
}
};
assertEquals(Optional.empty(), bare.appSecret("password"),
"an implementation written against SPI 1.0 still compiles and answers empty");
}
}
@@ -4,13 +4,16 @@ 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 static org.junit.jupiter.api.Assumptions.assumeFalse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.attribute.PosixFilePermission;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import mx.quest.runway.spi.model.FileEntry;
import mx.quest.runway.storage.StorageLayout;
import mx.quest.runway.storage.StorageProperties;
@@ -77,6 +80,26 @@ class PluginSiteFilesImplTest {
assertEquals(Optional.empty(), files.readText("ghost-site", "a.txt"), "an unknown site has no files");
}
@Test
void aFileWhoseFolderCannotBeSearchedIsAnErrorNotAbsent() throws IOException {
files.writeText("acme", "dir/token.yml", "token: x");
Path dir = root.resolve("dir");
Set<PosixFilePermission> before = Files.getPosixFilePermissions(dir);
Files.setPosixFilePermissions(dir, Set.of());
try {
assumeFalse(Files.isReadable(dir.resolve("token.yml")), "running as a user that ignores permissions");
// A caller that took "cannot tell" for "absent" would act as if the file were gone (the database plugin
// read a missing token as a recreated site and retired its data).
assertThrows(IOException.class, () -> files.readText("acme", "dir/token.yml"));
assertThrows(IOException.class, () -> files.stat("acme", "dir/token.yml"));
assertThrows(IOException.class, () -> files.list("acme", "dir/sub"));
assertThrows(IOException.class, () -> files.list("acme", "dir"), "a folder that cannot be listed");
} finally {
Files.setPosixFilePermissions(dir, before);
}
assertEquals(Optional.of("token: x"), files.readText("acme", "dir/token.yml"));
}
@Test
void aWriteReplacesTheFileAtomicallyAndLeavesNoTemporaryBehind() throws IOException {
files.writeText("acme", "a.txt", "one");
@@ -0,0 +1,182 @@
package mx.quest.runway.recovery;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import java.nio.file.Path;
import java.util.List;
import java.util.Locale;
import java.util.function.Function;
import mx.quest.runway.console.AppRecoveryController;
import mx.quest.runway.console.TenantRecoveryController;
import mx.quest.runway.platform.PlatformSettingsStore;
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 mx.quest.runway.web.ConsoleHostProperties;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import org.mockito.ArgumentCaptor;
import org.mockito.Mockito;
import org.springframework.mock.web.MockHttpServletRequest;
/**
* Where a password-reset link points. The request's own host never decides it: a request that names a made-up host
* (directly, or as {@code X-Forwarded-Host} through a proxy) must not get the platform to mail a real user a link to
* the sender's site. Checked on {@link RecoveryLinks} and through both recovery controllers, by capturing the link the
* mail would carry.
*/
class RecoveryLinksTest {
@TempDir
Path external;
private SiteStore sites;
private PlatformSettingsStore platform;
@BeforeEach
void setUp() {
StorageProperties props = new StorageProperties();
props.setExternal(external);
StorageLayout layout = StorageLayout.from(props);
YamlStore yaml = new YamlStore();
sites = new SiteStore(layout, yaml);
platform = new PlatformSettingsStore(layout, yaml);
sites.save(site("main", List.of("www.main.test", "main.test"), null));
sites.save(site("plain", List.of("plain.test"), "http://plain.test:8080"));
sites.save(site("hostless", List.of(), null));
}
private static Site site(String id, List<String> hosts, String baseUrl) {
return new Site(id, id, hosts, Locale.ENGLISH, List.of(Locale.ENGLISH), baseUrl, SiteStatus.ACTIVE, false,
null);
}
private RecoveryLinks links(String... consoleHosts) {
ConsoleHostProperties console = new ConsoleHostProperties();
console.setHosts(List.of(consoleHosts));
return new RecoveryLinks(sites, platform, console);
}
private static MockHttpServletRequest request(String scheme, String host, int port) {
MockHttpServletRequest request = new MockHttpServletRequest("POST", "/app/forgot-password");
request.setScheme(scheme);
request.setServerName(host);
request.setServerPort(port);
request.setSecure("https".equals(scheme));
return request;
}
@Test
void aSiteLinkIsTheSitesOwnAddressAndNeverTheRequests() {
RecoveryLinks links = links();
assertThat(links.siteBase(sites.find("main").orElseThrow())).contains("https://www.main.test");
assertThat(links.siteBase(sites.find("plain").orElseThrow())).contains("http://plain.test:8080");
assertThat(links.siteBase(sites.find("hostless").orElseThrow())).isEmpty();
}
@Test
void withoutConsoleHostsTheConsoleLinkIsTheDefaultSitesAddress() {
assertThat(links().appBase(request("https", "evil.example", 443))).isEmpty(); // no default site yet
platform.update(current -> current.withDefaultSiteId("main"));
assertThat(links().appBase(request("https", "evil.example", 443))).contains("https://www.main.test");
assertThat(links().appBase(request("http", "10.0.0.5", 8080))).contains("https://www.main.test");
platform.update(current -> current.withDefaultSiteId("hostless"));
assertThat(links().appBase(request("https", "evil.example", 443))).isEmpty();
}
@Test
void withConsoleHostsOnlyAListedHostMakesTheLink() {
RecoveryLinks links = links("https://Ops.Example.com/", "10.0.0.5");
assertThat(links.appBase(request("https", "ops.example.com", 443))).contains("https://ops.example.com");
assertThat(links.appBase(request("http", "10.0.0.5", 8080))).contains("http://10.0.0.5:8080");
assertThat(links.appBase(request("https", "evil.example", 443))).isEmpty();
platform.update(current -> current.withDefaultSiteId("main"));
assertThat(links.appBase(request("https", "evil.example", 443))).isEmpty(); // the list decides alone
}
@Test
void aLoopbackAddressIsNoAddressUnlessABaseUrlSaysSo() {
sites.save(site("default", List.of("localhost"), null)); // what the setup wizard leaves
sites.save(site("lab", List.of("127.0.0.1"), null));
sites.save(site("dev", List.of("localhost"), "http://localhost:8080")); // the operator's own word
RecoveryLinks links = links();
assertThat(links.siteBase(sites.find("default").orElseThrow())).isEmpty();
assertThat(links.siteBase(sites.find("lab").orElseThrow())).isEmpty();
assertThat(links.siteBase(sites.find("dev").orElseThrow())).contains("http://localhost:8080");
platform.update(current -> current.withDefaultSiteId("default"));
assertThat(links.appBase(request("https", "runway.example.com", 443))).isEmpty();
assertThat(RecoveryLinks.isLoopback("app.localhost")).isTrue();
assertThat(RecoveryLinks.isLoopback("localhost.example.com")).isFalse();
assertThat(RecoveryLinks.isLoopback("::1")).isTrue();
}
@Test
void aListedConsoleHostDecidesTheLinksSpellingAndAListedPortItsPort() {
RecoveryLinks links = links("ops.example.com", "admin.example.com:443", "[2001:db8::5]:8443");
assertThat(links.appBase(request("https", "Ops.Example.COM.", 443))).contains("https://ops.example.com");
// Without a listed port the request's stands (the client's Host header, or the proxy's).
assertThat(links.appBase(request("https", "ops.example.com", 8080))).contains("https://ops.example.com:8080");
assertThat(links.appBase(request("https", "admin.example.com", 8080))).contains("https://admin.example.com");
assertThat(links.appBase(request("https", "2001:db8::5", 9999))).contains("https://[2001:db8::5]:8443");
}
@Test
@SuppressWarnings("unchecked")
void theApplicationConsoleNeverMailsALinkToTheHostTheRequestNamed() {
platform.update(current -> current.withDefaultSiteId("main"));
PasswordRecoveryService recovery = Mockito.mock(PasswordRecoveryService.class);
AppRecoveryController controller = new AppRecoveryController(recovery, links());
controller.requestLink("root@example.com", Locale.ENGLISH, request("https", "evil.example", 443));
ArgumentCaptor<Function<String, String>> link = ArgumentCaptor.forClass(Function.class);
verify(recovery).requestApp(eq("root@example.com"), anyString(), link.capture(), any());
assertThat(link.getValue().apply("tok")).isEqualTo("https://www.main.test/app/reset?token=tok");
}
@Test
void withNoKnownAddressTheApplicationConsoleSendsNothing() {
PasswordRecoveryService recovery = Mockito.mock(PasswordRecoveryService.class);
AppRecoveryController controller = new AppRecoveryController(recovery, links("ops.example.com"));
String view = controller.requestLink("root@example.com", Locale.ENGLISH,
request("https", "evil.example", 443));
assertThat(view).isEqualTo("redirect:/app/forgot-password?sent"); // the same neutral answer
verify(recovery, never()).requestApp(anyString(), anyString(), any(), any());
}
@Test
@SuppressWarnings("unchecked")
void aSiteConsoleLinkPointsAtTheSiteItIsFor() {
PasswordRecoveryService recovery = Mockito.mock(PasswordRecoveryService.class);
SiteResolver resolver = new SiteResolver(sites, platform);
TenantRecoveryController controller = new TenantRecoveryController(recovery, resolver, links());
resolver.bind(sites.find("main").orElseThrow()); // an unknown host falls back to the default site
try {
controller.requestLink("editor@example.com", Locale.ENGLISH);
} finally {
resolver.clear();
}
ArgumentCaptor<Function<String, String>> link = ArgumentCaptor.forClass(Function.class);
verify(recovery).requestTenant(eq("main"), eq("editor@example.com"), anyString(), link.capture(), any());
assertThat(link.getValue().apply("tok")).isEqualTo("https://www.main.test/reset?token=tok");
resolver.bind(sites.find("hostless").orElseThrow());
try {
controller.requestLink("editor@example.com", Locale.ENGLISH);
} finally {
resolver.clear();
}
verify(recovery, never()).requestTenant(eq("hostless"), anyString(), anyString(), any(), any());
}
}
@@ -2,16 +2,20 @@ package mx.quest.runway.site;
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.io.UncheckedIOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.attribute.PosixFilePermissions;
import java.util.List;
import java.util.Locale;
import mx.quest.runway.storage.StorageLayout;
import mx.quest.runway.storage.StorageProperties;
import mx.quest.runway.storage.YamlStore;
import org.junit.jupiter.api.Assumptions;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
@@ -125,4 +129,28 @@ class SiteStoreTest {
assertFalse(loaded.maintenance(), "missing maintenance key defaults to off");
assertEquals(null, loaded.maintenanceMessage());
}
/**
* A site whose folder cannot be searched is "cannot tell", never "no such site": a plugin that takes a missing
* site for a deleted one would drop its data. A listing still goes on past it.
*/
@Test
void aSiteFolderThatCannotBeSearchedIsAnErrorNotAMissingSite(@TempDir Path tmp) throws IOException {
Assumptions.assumeTrue(!"root".equals(System.getProperty("user.name")), "root reads any folder");
SiteStore store = storeIn(tmp);
store.save(site("acme", "acme.test"));
store.save(site("beta", "beta.test"));
Path dir = tmp.resolve("sites").resolve("acme");
Files.setPosixFilePermissions(dir, PosixFilePermissions.fromString("rw-------"));
try {
store.evict("acme");
assertThrows(UncheckedIOException.class, () -> store.find("acme"));
assertEquals(List.of("beta"), store.findAll().stream().map(Site::id).toList());
assertTrue(store.find("gone").isEmpty(), "a site that is not there is still simply missing");
} finally {
Files.setPosixFilePermissions(dir, PosixFilePermissions.fromString("rwx------"));
}
store.evict("acme");
assertTrue(store.find("acme").isPresent());
}
}
@@ -0,0 +1,102 @@
package mx.quest.runway.web;
import static org.assertj.core.api.Assertions.assertThat;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import org.junit.jupiter.api.Test;
/** The client is read from the right of the X-Forwarded-For chain, past the trusted proxies only. */
class ForwardedForTest {
private static final CidrSet PROXIES = CidrSet.of(List.of("10.0.0.0/8", "2001:db8:ffff::/48"));
private static ForwardedFor.Chain chain(String... lines) {
return ForwardedFor.chain(Collections.enumeration(List.of(lines)));
}
@Test
void anAppendingProxyCannotBeFooledByAClientWrittenEntry() {
// The client sent "X-Forwarded-For: 6.6.6.6"; the proxy appended the address it saw.
assertThat(ForwardedFor.client(chain("6.6.6.6, 203.0.113.7"), PROXIES, "10.0.0.9")).isEqualTo("203.0.113.7");
// Same, with the proxy adding a second header line instead of appending to the first.
assertThat(ForwardedFor.client(chain("6.6.6.6", "203.0.113.7"), PROXIES, "10.0.0.9")).isEqualTo("203.0.113.7");
}
@Test
void trustedHopsAreSkippedFromTheRight() {
assertThat(ForwardedFor.client(chain("6.6.6.6, 203.0.113.7, 10.1.1.1, 10.2.2.2"), PROXIES, "10.0.0.9"))
.isEqualTo("203.0.113.7");
assertThat(ForwardedFor.client(chain("203.0.113.7, [2001:db8:ffff::1]:443"), PROXIES, "10.0.0.9"))
.isEqualTo("203.0.113.7");
}
@Test
void aChainOfTrustedProxiesOnlyGivesItsLeftmostEntry() {
assertThat(ForwardedFor.client(chain("10.3.3.3, 10.1.1.1"), PROXIES, "10.0.0.9")).isEqualTo("10.3.3.3");
}
@Test
void noChainLeavesThePeer() {
assertThat(ForwardedFor.client(ForwardedFor.Chain.NONE, PROXIES, "10.0.0.9")).isEqualTo("10.0.0.9");
assertThat(ForwardedFor.client(chain(" , ,"), PROXIES, "10.0.0.9")).isEqualTo("10.0.0.9");
assertThat(ForwardedFor.chain(null)).isEqualTo(ForwardedFor.Chain.NONE);
}
@Test
void aDecidingEntryThatIsNotAnAddressFallsBackToThePeer() {
assertThat(ForwardedFor.client(chain("203.0.113.7, unknown"), PROXIES, "10.0.0.9")).isEqualTo("10.0.0.9");
assertThat(ForwardedFor.client(chain("203.0.113.7, example.com"), PROXIES, "10.0.0.9")).isEqualTo("10.0.0.9");
// An unreadable entry to the LEFT of the client does not matter: it is never reached.
assertThat(ForwardedFor.client(chain("garbage, 203.0.113.7"), PROXIES, "10.0.0.9")).isEqualTo("203.0.113.7");
}
@Test
void addressFormsAreNormalised() {
assertThat(ForwardedFor.address("192.0.2.1")).isEqualTo("192.0.2.1");
assertThat(ForwardedFor.address("192.0.2.1:8080")).isEqualTo("192.0.2.1");
assertThat(ForwardedFor.address("\"192.0.2.1\"")).isEqualTo("192.0.2.1");
assertThat(ForwardedFor.address("2001:db8::1")).isEqualTo("2001:db8::1");
assertThat(ForwardedFor.address("[2001:db8::1]")).isEqualTo("2001:db8::1");
assertThat(ForwardedFor.address("[2001:db8::1]:8080")).isEqualTo("2001:db8::1");
assertThat(ForwardedFor.address("\"[2001:db8::1]:8080\"")).isEqualTo("2001:db8::1");
}
@Test
void nonAddressesAreRefusedWithoutAnyLookup() {
assertThat(ForwardedFor.address(null)).isNull();
assertThat(ForwardedFor.address("")).isNull();
assertThat(ForwardedFor.address("unknown")).isNull();
assertThat(ForwardedFor.address("_hidden")).isNull();
assertThat(ForwardedFor.address("localhost")).isNull();
assertThat(ForwardedFor.address("192.0.2.1:http")).isNull();
assertThat(ForwardedFor.address("192.0.2.1:")).isNull();
assertThat(ForwardedFor.address("192.0.2.256")).isNull();
assertThat(ForwardedFor.address("[192.0.2.1]")).isNull();
assertThat(ForwardedFor.address("[2001:db8::1")).isNull();
assertThat(ForwardedFor.address("[2001:db8::1]x")).isNull();
assertThat(ForwardedFor.address("fe80::1%eth0")).isNull();
assertThat(ForwardedFor.address("1:2")).isNull();
assertThat(ForwardedFor.address("1".repeat(65))).isNull();
}
@Test
void aHugeChainKeepsOnlyItsRightmostEntries() {
String line = IntStream.range(0, 1000).mapToObj(i -> "6.6." + (i / 250) + "." + (i % 250))
.collect(Collectors.joining(", ")) + ", 203.0.113.7";
ForwardedFor.Chain chain = chain(line);
assertThat(chain.total()).isEqualTo(1001);
assertThat(chain.entries()).hasSize(ForwardedFor.MAX_ENTRIES).endsWith("203.0.113.7");
assertThat(chain.text()).startsWith("…, ").endsWith(", 203.0.113.7");
assertThat(ForwardedFor.client(chain, PROXIES, "10.0.0.9")).isEqualTo("203.0.113.7");
}
@Test
void aLongEntryIsCutForDisplayAndNeverTakenAsAnAddress() {
ForwardedFor.Chain chain = chain("x".repeat(500));
assertThat(chain.entries().getFirst()).hasSize(ForwardedFor.MAX_ENTRY_LENGTH + 1).endsWith("…");
assertThat(ForwardedFor.client(chain, PROXIES, "10.0.0.9")).isEqualTo("10.0.0.9");
}
}
@@ -0,0 +1,160 @@
package mx.quest.runway.web;
import static org.assertj.core.api.Assertions.assertThat;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import org.eclipse.jetty.ee11.servlet.ServletContextHandler;
import org.eclipse.jetty.ee11.servlet.ServletHolder;
import org.eclipse.jetty.server.HttpConnectionFactory;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.ServerConnector;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;
import java.util.Map;
import org.springframework.boot.context.properties.bind.Binder;
import org.springframework.boot.context.properties.source.MapConfigurationPropertySource;
import org.springframework.boot.jetty.JettyWebServer;
import org.springframework.boot.jetty.servlet.JettyServletWebServerFactory;
import org.springframework.boot.web.server.WebServer;
/**
* The minimum request data rate, against a real Jetty: a body trickled in is cut with {@code 408} instead of holding a
* request thread, and a server that is slow to start reading is not blamed for it. Guards the behaviour across Jetty
* upgrades, since the rate check is Jetty's.
*/
class SlowClientConfigTest {
/** The bean, as Spring binds and applies it: the property, the clamp, and every connector of Boot's own Jetty. */
@Test
void theBoundPropertyReachesEveryConnectorOfTheServerBootBuilds() throws Exception {
assertThat(rateOnBootsServer("1024")).containsOnly(1024L).isNotEmpty();
assertThat(rateOnBootsServer("-5")).as("a negative value is clamped to off").containsOnly(0L);
}
private java.util.List<Long> rateOnBootsServer(String configured) throws Exception {
SlowClientConfig.HttpLimitProperties properties = new Binder(new MapConfigurationPropertySource(
Map.of("runway.http.min-request-data-rate", configured)))
.bind("runway.http", SlowClientConfig.HttpLimitProperties.class).get();
JettyServletWebServerFactory factory = new JettyServletWebServerFactory(0);
new SlowClientConfig().slowClientJettyCustomizer(properties).customize(factory);
WebServer web = factory.getWebServer();
web.start();
try {
java.util.List<Long> rates = new java.util.ArrayList<>();
for (org.eclipse.jetty.server.Connector connector : ((JettyWebServer) web).getServer().getConnectors()) {
for (org.eclipse.jetty.server.ConnectionFactory f : connector.getConnectionFactories()) {
if (f instanceof org.eclipse.jetty.server.HttpConfiguration.ConnectionFactory http) {
rates.add(http.getHttpConfiguration().getMinRequestDataRate());
}
}
}
return rates;
} finally {
web.stop();
}
}
private Server server;
@AfterEach
void stop() throws Exception {
if (server != null) {
server.stop();
}
}
/** A server whose servlet reads the whole body after {@code pauseMillis}, with the rate applied by the config. */
private int start(long bytesPerSecond, long pauseMillis) throws Exception {
server = new Server();
ServerConnector connector = new ServerConnector(server, new HttpConnectionFactory());
connector.setPort(0);
connector.setIdleTimeout(30_000);
server.addConnector(connector);
ServletContextHandler context = new ServletContextHandler();
context.addServlet(new ServletHolder(new HttpServlet() {
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
try {
Thread.sleep(pauseMillis);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
response.getWriter().write("read " + request.getInputStream().readAllBytes().length);
}
}), "/*");
server.setHandler(context);
assertThat(SlowClientConfig.apply(server, bytesPerSecond)).isEqualTo(1);
server.start();
return connector.getLocalPort();
}
private static String statusLine(Socket socket) throws IOException {
socket.setSoTimeout(10_000);
String response = new String(socket.getInputStream().readAllBytes(), StandardCharsets.US_ASCII);
return response.isEmpty() ? "" : response.substring(0, response.indexOf("\r\n"));
}
@Test
void aTrickledBodyIsCutWithRequestTimeout() throws Exception {
int port = start(1024, 0);
long started = System.nanoTime();
try (Socket socket = new Socket("127.0.0.1", port)) {
OutputStream out = socket.getOutputStream();
out.write("POST / HTTP/1.1\r\nHost: x\r\nContent-Length: 1000\r\nConnection: close\r\n\r\n"
.getBytes(StandardCharsets.US_ASCII));
out.flush();
try {
for (int i = 0; i < 20; i++) { // one byte a second: far below 1 KiB/s
Thread.sleep(1000);
out.write('a');
out.flush();
}
} catch (IOException closedByServer) {
// expected: Jetty answered and closed while the client was still trickling
}
assertThat(statusLine(socket)).isEqualTo("HTTP/1.1 408 Request Timeout");
}
assertThat(Duration.ofNanos(System.nanoTime() - started)).isLessThan(Duration.ofSeconds(15));
}
@Test
void aServerSlowToReadIsNotBlamed() throws Exception {
int port = start(1024, 3000);
try (Socket socket = new Socket("127.0.0.1", port)) {
OutputStream out = socket.getOutputStream();
out.write(("POST / HTTP/1.1\r\nHost: x\r\nContent-Length: 100\r\nConnection: close\r\n\r\n"
+ "a".repeat(100)).getBytes(StandardCharsets.US_ASCII));
out.flush();
assertThat(statusLine(socket)).isEqualTo("HTTP/1.1 200 OK");
}
}
@Test
void theDefaultIsFourKilobytesPerSecond() {
assertThat(new SlowClientConfig.HttpLimitProperties().getMinRequestDataRate()).isEqualTo(4096);
}
@Test
void zeroTurnsTheCheckOff() throws Exception {
int port = start(0, 0);
try (Socket socket = new Socket("127.0.0.1", port)) {
OutputStream out = socket.getOutputStream();
out.write("POST / HTTP/1.1\r\nHost: x\r\nContent-Length: 3\r\nConnection: close\r\n\r\n"
.getBytes(StandardCharsets.US_ASCII));
out.flush();
for (int i = 0; i < 3; i++) { // one byte a second, accepted when the check is off
Thread.sleep(1000);
out.write('a');
out.flush();
}
assertThat(statusLine(socket)).isEqualTo("HTTP/1.1 200 OK");
}
}
}
@@ -89,4 +89,51 @@ class TrustedForwardedHeaderFilterTest {
assertNull(seen.getHeader("X-Forwarded-Host"), "forwarded handling off => always hide");
assertEquals("localhost", seen.getServerName());
}
@Test
void aClientWrittenLeftmostEntryDoesNotChooseTheAddress() throws Exception {
TrustedForwardedHeaderFilter filter = new TrustedForwardedHeaderFilter(CidrSet.of(List.of("10.0.0.0/8")), true);
MockHttpServletRequest request = behindProxy("10.0.0.9");
request.removeHeader("X-Forwarded-For");
request.addHeader("X-Forwarded-For", "6.6.6.6, 203.0.113.7"); // client sent 6.6.6.6, the proxy appended
HttpServletRequest seen = run(filter, request);
assertEquals("203.0.113.7", seen.getRemoteAddr(), "the address the trusted proxy saw, not the client's claim");
assertEquals("203.0.113.7", seen.getRemoteHost(), "never the leftmost, never a reverse lookup");
assertEquals("203.0.113.7", ClientIp.of(seen));
assertEquals("example.com", seen.getServerName(), "Spring still applies the forwarded host");
assertEquals("https", seen.getScheme(), "and the forwarded scheme");
}
@Test
void theStandardForwardedHeaderIsHiddenEvenFromATrustedPeer() throws Exception {
TrustedForwardedHeaderFilter filter = new TrustedForwardedHeaderFilter(CidrSet.of(List.of("10.0.0.0/8")), true);
MockHttpServletRequest request = behindProxy("10.0.0.9");
// A client-sent RFC 7239 header that a proxy managing X-Forwarded-* passed through untouched.
request.addHeader("Forwarded", "for=6.6.6.6;host=evil.example;proto=http");
HttpServletRequest seen = run(filter, request);
assertEquals("203.0.113.7", seen.getRemoteAddr());
assertEquals("example.com", seen.getServerName(), "Forwarded must not override X-Forwarded-Host");
assertEquals("https", seen.getScheme(), "Forwarded must not override X-Forwarded-Proto");
assertNull(seen.getHeader("Forwarded"));
}
@Test
void eachRequestRecordsHowItWasAttributed() throws Exception {
TrustedForwardedHeaderFilter filter = new TrustedForwardedHeaderFilter(CidrSet.of(List.of("10.0.0.0/8")), true);
MockHttpServletRequest viaProxy = behindProxy("10.0.0.9");
run(filter, viaProxy);
ProxyResolution trusted = ProxyResolution.of(viaProxy);
assertEquals(new ProxyResolution("10.0.0.9", true, true,
new ForwardedFor.Chain(List.of("203.0.113.7"), 1), "203.0.113.7"), trusted);
MockHttpServletRequest direct = behindProxy("198.51.100.9");
run(filter, direct);
ProxyResolution untrusted = ProxyResolution.of(direct);
assertEquals(new ProxyResolution("198.51.100.9", false, false,
new ForwardedFor.Chain(List.of("203.0.113.7"), 1), "198.51.100.9"), untrusted);
MockHttpServletRequest off = behindProxy("10.0.0.9");
run(new TrustedForwardedHeaderFilter(CidrSet.of(List.of("10.0.0.0/8")), false), off);
assertEquals(new ProxyResolution("10.0.0.9", true, false,
new ForwardedFor.Chain(List.of("203.0.113.7"), 1), "10.0.0.9"), ProxyResolution.of(off));
}
}