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

@@ -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()}"/>