Runway 1.2.0

This commit is contained in:
Runway committed 2026-10-30 11:24:46 -06:00
1 parent 5fa0c1ef9f
commit 9144c206be
90 files changed
+2737 -554

No files matched your search

@@ -1,6 +1,7 @@
package mx.quest.runway.backup;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
@@ -20,6 +21,10 @@ import org.springframework.stereotype.Component;
* leftover scratch. A work dir whose recovery move itself fails is left untouched (its {@code old} preserved
* for manual recovery), never deleted.
*
* <p>The site's logs and stats ride in the work dir until a restore has swapped and merged them, so the sweep
* finishes that too, with the same routine the restore uses ({@link BackupService#settle}): a site folder holding no
* {@code site.yml} — one a log write recreated mid-swap — is never mistaken for the site.
*
* <p>The scratch lives under {@code sites/.restore-work/}, a hidden name {@link
* mx.quest.runway.storage.PathSafety#isSafeId} rejects, so it is never mistaken for a tenant.
*/
@@ -49,20 +54,18 @@ public class BackupRestoreRecovery {
}
for (Path workDir : workDirs) {
String siteId = workDir.getFileName().toString();
Path old = workDir.resolve("old");
Path siteDir = layout.siteDir(siteId);
if (Files.exists(old) && !Files.exists(siteDir)) {
try {
Files.move(old, siteDir);
try {
if (BackupService.settle(siteDir, workDir)) {
log.warn("recovered site '{}' from an interrupted restore", siteId);
} catch (IOException e) {
// Recovery failed — DO NOT delete this work dir; `old` is the only copy of the site.
log.error("could not recover site '{}' automatically — its content is preserved at {}",
siteId, old, e);
continue;
}
} catch (IOException | UncheckedIOException e) {
// Recovery failed — DO NOT delete this work dir: it may hold the only copy of the site, or its logs.
log.error("could not recover site '{}' automatically — its content is preserved at {}",
siteId, workDir, e);
continue;
}
BackupService.deleteRecursively(workDir); // recovered or not needed — the leftovers are safe to drop
BackupService.deleteRecursively(workDir); // settled — the leftovers (a staging copy) are safe to drop
}
}
}
@@ -9,6 +9,7 @@ import java.io.InputStream;
import java.io.OutputStream;
import java.io.UncheckedIOException;
import java.nio.file.AtomicMoveNotSupportedException;
import java.nio.file.FileAlreadyExistsException;
import java.nio.file.Files;
import java.nio.file.LinkOption;
import java.nio.file.Path;
@@ -296,7 +297,7 @@ public class BackupService {
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);
Staged staged = stageAndSwap(siteId, in, true);
if (live != null) {
keepRouting(siteId, live);
} else {
@@ -307,7 +308,9 @@ public class BackupService {
sites.evict(siteId);
events.publishEvent(new SiteChangedEvent(siteId, SiteChangedEvent.Kind.RESTORED));
importParticipants(siteId, staged.pluginData());
deleteRecursively(staged.work());
if (staged.settled()) {
deleteRecursively(staged.work());
} // else: the site's previous logs wait in it for the next restore or start (swapIntoPlace)
log.info("restored site '{}' from backup", siteId);
}
@@ -384,7 +387,7 @@ public class BackupService {
if (sites.exists(newId)) {
throw new IllegalStateException("a site with id '" + newId + "' already exists");
}
Staged staged = stageAndSwap(newId, in);
Staged staged = stageAndSwap(newId, in, false); // a new site starts its own logs
try {
// The staged site.yml still carries the SOURCE identity — no event has fired, so rewrite it now.
Site source = sites.find(newId).orElseThrow(() -> new IOException("restored site.yml is unreadable"));
@@ -420,19 +423,30 @@ public class BackupService {
}
/** The result of staging a backup: the manifest, the plugin data to import, and the work dir to clean up. */
private record Staged(BackupManifest manifest, Map<String, Map<String, byte[]>> pluginData, Path work) {
private record Staged(BackupManifest manifest, Map<String, Map<String, byte[]>> pluginData, Path work,
boolean settled) {
}
/**
* Extracts + validates the archive into a staging dir and atomically swaps it into {@code siteId}'s folder.
* Publishes no event and imports no participant data — the caller owns the lifecycle (restore vs create),
* so create can rewrite the identity before anything observes the swapped-in files.
* so create can rewrite the identity before anything observes the swapped-in files. {@code keepTransient}: the
* live site's logs and stats stay with it (a restore), or are dropped (a new site starts its own).
*/
private Staged stageAndSwap(String siteId, InputStream in) throws IOException {
private Staged stageAndSwap(String siteId, InputStream in, boolean keepTransient) throws IOException {
Path siteDir = layout.siteDir(siteId);
Path work = workDir(siteId);
Path staging = work.resolve("staging");
Path old = work.resolve("old");
if (Files.exists(work, LinkOption.NOFOLLOW_LINKS)) {
// A previous swap may have left the site's logs (or, after a crash, the site itself) here: finish it
// first, and refuse rather than delete it when that fails.
try {
settle(siteDir, work);
} catch (UncheckedIOException e) {
throw e.getCause();
}
}
deleteRecursively(work);
Files.createDirectories(staging);
// TOCTOU guard: between the delete above and this create, a local attacker could plant a symlink at
@@ -492,8 +506,8 @@ public class BackupService {
throw new IOException("not a valid Runway site backup (missing manifest.yml or site content)");
}
warnParticipantDrift(siteId, manifest, pluginData);
swapIntoPlace(siteDir, staging, old);
return new Staged(manifest, pluginData, work);
boolean settled = swapIntoPlace(siteDir, staging, old, keepTransient);
return new Staged(manifest, pluginData, work, settled);
}
/**
@@ -747,7 +761,7 @@ public class BackupService {
/** Transient per-site data (access/audit logs, bandwidth stats) excluded from the content backup. */
private static boolean isTransient(String rel) {
return rel.equals("logs") || rel.startsWith("logs/") || rel.equals("stats") || rel.startsWith("stats/");
return TRANSIENT_DIRS.stream().anyMatch(dir -> rel.equals(dir) || rel.startsWith(dir + "/"));
}
private static void collectPluginEntry(Map<String, Map<String, byte[]>> into, String rest, byte[] bytes) {
@@ -772,27 +786,191 @@ public class BackupService {
}
}
/** Atomic same-filesystem swap: current → old, staged → live, drop old; restore the original on failure. */
private static void swapIntoPlace(Path siteDir, Path staging, Path old) throws IOException {
/**
* Atomic same-filesystem swap: current → old, staged → live, drop old; restore the original on failure.
*
* <p><b>The site's logs and usage stats stay with the site</b> when {@code keepTransient} (a restore): a backup
* never carries them, so the swap alone would start the audit journal again from nothing — and a restore is
* exactly the act a journal must survive. They stay inside {@code old} until the new copy is in place, then
* {@link #settle} merges them in. Until that has succeeded the work folder is kept: the next restore of the
* site, or the next start ({@link BackupRestoreRecovery}), settles it again, so neither a crash nor a failed
* merge loses them. Whatever an archive carries under those names is discarded first: a backup never writes
* them, so a crafted one must not plant journal lines.
*
* <p>The log writer and the bandwidth flush create these folders on demand, so a write landing between the two
* renames recreates the site folder and the second rename fails. That folder (it holds no {@code site.yml}) is
* set aside as {@code late} and the rename retried once; its lines are merged like the others.
*
* @return whether the work folder holds nothing more of the site's and may be deleted
*/
private static boolean swapIntoPlace(Path siteDir, Path staging, Path old, boolean keepTransient)
throws IOException {
for (String name : TRANSIENT_DIRS) {
deleteRecursively(staging.resolve(name));
}
Path work = old.getParent();
Path late = work.resolve(LATE_DIR);
try {
if (Files.exists(siteDir)) {
move(siteDir, old);
}
move(staging, siteDir);
try {
move(staging, siteDir);
} catch (IOException recreated) {
if (!setAsideIfNotASite(siteDir, late)) {
throw recreated;
}
move(staging, siteDir);
}
} catch (IOException swapFailed) {
if (Files.exists(old) && !Files.exists(siteDir)) {
if (Files.exists(old)) {
try {
move(old, siteDir); // roll back
} catch (IOException rollbackFailed) {
settle(siteDir, work); // rolls the original back, with any lines written meanwhile
} catch (IOException | UncheckedIOException rollbackFailed) {
// Leave `old` in place as the recovery copy — the startup sweep rolls it forward. Do NOT
// delete it (it now holds the ONLY copy of the original site).
// delete it (it may hold the ONLY copy of the original site).
swapFailed.addSuppressed(rollbackFailed);
throw swapFailed;
}
}
throw swapFailed;
}
if (keepTransient) {
try {
settle(siteDir, work);
} catch (IOException | UncheckedIOException e) {
// The restore itself succeeded. The site's previous logs stay in the work folder for the next try.
log.warn("could not carry the logs of site folder {} over the restore yet; the next restore of "
+ "the site or the next start does", siteDir, e);
return false;
}
}
deleteRecursively(late);
deleteRecursively(old);
return true;
}
/**
* Finishes what a swap left in its work folder: the site's previous copy ({@code old}) and the lines written
* while the site folder was away ({@code late}). Used after a swap, before the next restore of the same site,
* and by the startup sweep. A site folder holding no {@code site.yml} is never taken for the site.
* <ul>
* <li>{@code old} and no site folder: the swap never completed — {@code old} goes back, followed by the
* {@code late} lines;</li>
* <li>{@code old} and the site: the swap completed — the {@code late} and then the {@code old} lines go
* before the site's own;</li>
* <li>no {@code old}: a rollback put the original back — the {@code late} lines go after its own.</li>
* </ul>
* Each merged file is removed from the work folder, so a run that fails half-way can simply be repeated.
*
* @return whether the previous copy was rolled back into place
* @throws IOException when a move or a merge fails; the work folder must then be kept
*/
static boolean settle(Path siteDir, Path workDir) throws IOException {
Path old = workDir.resolve("old");
Path late = workDir.resolve(LATE_DIR);
if (!Files.exists(old, LinkOption.NOFOLLOW_LINKS)) {
mergeTransient(late, siteDir, false);
return false;
}
setAsideIfNotASite(siteDir, late);
if (!Files.exists(siteDir, LinkOption.NOFOLLOW_LINKS)) {
move(old, siteDir);
mergeTransient(late, siteDir, false);
return true;
}
mergeTransient(late, siteDir, true);
mergeTransient(old, siteDir, true);
return false;
}
/** The site folder's transient sub-folders, as {@link #isTransient(String)} names them. */
static final List<String> TRANSIENT_DIRS = List.of("logs", "stats");
/** Beside {@code old} in a restore's work folder: a site folder a late write recreated mid-swap. */
static final String LATE_DIR = "late";
/**
* Moves {@code siteDir} to {@code aside} when it exists but holds no {@code site.yml} — a folder a log or stats
* write recreated, not a site — merging it after whatever {@code aside} already holds.
*
* @return whether {@code siteDir} was set aside
*/
static boolean setAsideIfNotASite(Path siteDir, Path aside) throws IOException {
if (!Files.isDirectory(siteDir, LinkOption.NOFOLLOW_LINKS) || Files.exists(siteDir.resolve("site.yml"))) {
return false;
}
if (Files.exists(aside, LinkOption.NOFOLLOW_LINKS)) {
mergeTransient(siteDir, aside, false);
deleteRecursively(siteDir);
} else {
move(siteDir, aside);
}
return true;
}
/**
* Moves the transient files under {@code from} ({@link #TRANSIENT_DIRS}) into the site folder {@code into}.
* A file {@code into} lacks is moved; a log both have is joined, {@code from}'s lines first when
* {@code fromIsOlder} (the journal is read in file order, so the order of the lines is the order of the events);
* a stats file both have keeps {@code into}'s, which the bandwidth service rewrites whole from memory. Symlinks
* and other non-regular files are left behind. Missing folders are a no-op. A line the log writer appends to a
* joined file during the copy is lost: a window of one file copy, during a restore.
*/
static void mergeTransient(Path from, Path into, boolean fromIsOlder) throws IOException {
if (!Files.isDirectory(from, LinkOption.NOFOLLOW_LINKS) || !Files.isDirectory(into, LinkOption.NOFOLLOW_LINKS)) {
return;
}
for (String name : TRANSIENT_DIRS) {
Path root = from.resolve(name);
if (!Files.isDirectory(root, LinkOption.NOFOLLOW_LINKS)) {
continue;
}
List<Path> files;
try (Stream<Path> walk = Files.walk(root)) {
files = walk.filter(f -> Files.isRegularFile(f, LinkOption.NOFOLLOW_LINKS)).toList();
}
for (Path file : files) {
Path target = into.resolve(name).resolve(root.relativize(file).toString());
Files.createDirectories(target.getParent());
if (moveIfAbsent(file, target)) {
continue;
}
if (name.equals("logs") && Files.isRegularFile(target, LinkOption.NOFOLLOW_LINKS)) {
// Streamed through a sibling file: today's access log of a busy site can be large.
Path joined = target.resolveSibling(target.getFileName() + ".joining");
try (OutputStream out = Files.newOutputStream(joined)) {
Files.copy(fromIsOlder ? file : target, out);
Files.copy(fromIsOlder ? target : file, out);
}
move(joined, target);
}
Files.delete(file); // merged (or superseded): a re-run must not join it twice
}
}
}
/**
* Moves {@code file} to {@code target} unless {@code target} exists, atomically: a hard link fails when the
* name is taken, where a rename would replace a log the writer has just created. Falls back to a checked move
* on a filesystem without hard links.
*
* @return whether the file was moved
*/
private static boolean moveIfAbsent(Path file, Path target) throws IOException {
try {
Files.createLink(target, file);
} catch (FileAlreadyExistsException taken) {
return false;
} catch (UnsupportedOperationException noLinks) {
try {
Files.move(file, target); // no REPLACE_EXISTING: refuses an existing target
return true;
} catch (FileAlreadyExistsException taken) {
return false;
}
}
Files.delete(file);
return true;
}
/** A same-filesystem rename, atomic where the filesystem supports it. */
@@ -1,5 +1,6 @@
package mx.quest.runway.console;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
@@ -98,8 +99,8 @@ public class AppBackupsController {
/** Stream a fresh backup of any site. */
@GetMapping("/__app/backups/{siteId}/download")
public void download(@PathVariable String siteId, Authentication authentication, HttpServletResponse response)
throws IOException {
public void download(@PathVariable String siteId, Authentication authentication, HttpServletRequest request,
HttpServletResponse response) throws IOException {
platformAuthority.require(authentication);
if (!sites.exists(siteId)) {
throw new ResponseStatusException(HttpStatus.NOT_FOUND, "no such site");
@@ -107,13 +108,17 @@ public class AppBackupsController {
response.setContentType("application/zip");
response.setHeader(HttpHeaders.CONTENT_DISPOSITION,
"attachment; filename=\"" + siteId + "-backup-" + LocalDate.now() + ".zip\"");
if (TenantBackupsController.isHead(request)) {
return; // the headers only: no archive is built, and nothing is downloaded
}
backups.backup(siteId, response.getOutputStream());
activity.record(authentication.getName(), "backup.downloaded", siteId + " (full)");
}
/** Stream a <b>transfer</b> archive of any site — no credentials, accounts or origin hostnames. */
@GetMapping("/__app/backups/{siteId}/download-transfer")
public void downloadForTransfer(@PathVariable String siteId, Authentication authentication,
HttpServletResponse response) throws IOException {
HttpServletRequest request, HttpServletResponse response) throws IOException {
platformAuthority.require(authentication);
if (!sites.exists(siteId)) {
throw new ResponseStatusException(HttpStatus.NOT_FOUND, "no such site");
@@ -121,7 +126,11 @@ public class AppBackupsController {
response.setContentType("application/zip");
response.setHeader(HttpHeaders.CONTENT_DISPOSITION,
"attachment; filename=\"" + siteId + "-transfer-" + LocalDate.now() + ".zip\"");
if (TenantBackupsController.isHead(request)) {
return;
}
backups.backup(siteId, response.getOutputStream(), BackupService.BackupPurpose.TRANSFER);
activity.record(authentication.getName(), "backup.downloaded", siteId + " (transfer)");
}
/** Save a stored backup of any site on the server. */
@@ -1,5 +1,6 @@
package mx.quest.runway.console;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
@@ -7,6 +8,7 @@ import java.nio.file.Path;
import java.time.LocalDate;
import mx.quest.runway.backup.BackupService;
import mx.quest.runway.backup.UnsupportedBackupFormatException;
import mx.quest.runway.log.SiteLogService;
import mx.quest.runway.site.Site;
import mx.quest.runway.site.SiteResolver;
import org.slf4j.Logger;
@@ -50,6 +52,14 @@ import org.springframework.web.servlet.mvc.support.RedirectAttributes;
* A stored backup a delegated holder created stays on the server for an administrator (or the platform operator, on
* {@code /__app/backups}) to download or restore. Bound-tenancy only — a tenant can only ever back up or restore its
* own site.
*
* <p>Every act that took effect is recorded in the site's audit log, under the actions the application console
* records for the same acts in the platform's activity log: {@code backup.saved} and {@code backup.deleted} naming
* the backup, {@code backup.downloaded} ({@code full}, {@code transfer}, or {@code full} and the stored backup's
* name, when it is handed over; a HEAD request, or a range resuming one, is not a new download) and
* {@code site.restored} (the backup's name, or {@code (upload)}). Who
* took a copy of the site, or replaced it, is what an administrator reviewing the site needs to know. A refused
* act, or one that failed before changing anything, writes nothing.
*/
@Controller
public class TenantBackupsController {
@@ -62,11 +72,13 @@ public class TenantBackupsController {
private final MessageSource messages;
private final mx.quest.runway.backup.BackupProperties policy;
private final mx.quest.runway.platform.PlatformSettingsStore platform;
private final SiteLogService siteLog;
public TenantBackupsController(SiteResolver siteResolver, BackupService backups, TenantAuthority tenantAuthority,
@Qualifier("operatorAwareMessageSource") MessageSource messages,
mx.quest.runway.backup.BackupProperties policy,
mx.quest.runway.platform.PlatformSettingsStore platform) {
mx.quest.runway.platform.PlatformSettingsStore platform, SiteLogService siteLog) {
this.siteLog = siteLog;
this.platform = platform;
this.policy = policy;
this.siteResolver = siteResolver;
@@ -120,10 +132,11 @@ public class TenantBackupsController {
/** Save a new backup on the server. */
@PostMapping("/__admin/backups/create")
@PreAuthorize("@authz.may('MANAGE_BACKUPS')")
public String create(RedirectAttributes redirect) {
public String create(Authentication authentication, RedirectAttributes redirect) {
Site site = boundTenancy();
try {
String name = backups.create(site.id());
siteLog.audit(site.id(), actor(authentication), "backup.saved", name);
redirect.addFlashAttribute("flash", message("op.backups.created", "Backup created.") + " " + name);
} catch (IOException e) {
log.warn("backup create failed for {}", site.id(), e);
@@ -138,13 +151,18 @@ public class TenantBackupsController {
*/
@GetMapping("/__admin/backups/download")
@PreAuthorize("@authz.may('MANAGE_BACKUPS')")
public void download(Authentication authentication, HttpServletResponse response) throws IOException {
public void download(Authentication authentication, HttpServletRequest request, HttpServletResponse response)
throws IOException {
Site site = boundTenancy();
tenantAuthority.require(authentication, site.id());
response.setContentType("application/zip");
response.setHeader(HttpHeaders.CONTENT_DISPOSITION,
"attachment; filename=\"" + site.id() + "-backup-" + LocalDate.now() + ".zip\"");
if (isHead(request)) {
return; // the headers only: no archive is built, and nothing is downloaded
}
backups.backup(site.id(), response.getOutputStream());
siteLog.audit(site.id(), actor(authentication), "backup.downloaded", "full");
}
@@ -158,12 +176,17 @@ public class TenantBackupsController {
*/
@GetMapping("/__admin/backups/download-transfer")
@PreAuthorize("@authz.may('MANAGE_BACKUPS')")
public void downloadForTransfer(HttpServletResponse response) throws IOException {
public void downloadForTransfer(Authentication authentication, HttpServletRequest request,
HttpServletResponse response) throws IOException {
Site site = boundTenancy();
response.setContentType("application/zip");
response.setHeader(HttpHeaders.CONTENT_DISPOSITION,
"attachment; filename=\"" + site.id() + "-transfer-" + LocalDate.now() + ".zip\"");
if (isHead(request)) {
return;
}
backups.backup(site.id(), response.getOutputStream(), BackupService.BackupPurpose.TRANSFER);
siteLog.audit(site.id(), actor(authentication), "backup.downloaded", "transfer");
}
/**
@@ -173,7 +196,8 @@ public class TenantBackupsController {
*/
@GetMapping("/__admin/backups/{name}/download")
@PreAuthorize("@authz.may('MANAGE_BACKUPS')")
public ResponseEntity<Resource> downloadStored(@PathVariable String name, Authentication authentication) {
public ResponseEntity<Resource> downloadStored(@PathVariable String name, Authentication authentication,
HttpServletRequest request) {
Site site = boundTenancy();
tenantAuthority.require(authentication, site.id());
Path file = backups.file(site.id(), name)
@@ -181,6 +205,12 @@ public class TenantBackupsController {
// Name the download from the RESOLVED file, never the raw path variable — the header must not echo
// attacker-controlled input (CRLF / quotes) even though the store already rejects it as an unsafe id.
String filename = file.getFileName().toString();
// Recorded when the file is handed over, before it streams (after this method returns, with HEAD and
// resumable ranges handled by the framework). A HEAD request takes no copy, and a range that does not start
// at the beginning continues a download already recorded, so neither writes a line.
if (!isHead(request) && startsAtTheBeginning(request.getHeader(HttpHeaders.RANGE))) {
siteLog.audit(site.id(), actor(authentication), "backup.downloaded", "full " + filename);
}
return ResponseEntity.ok()
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + filename + "\"")
.contentType(MediaType.parseMediaType("application/zip"))
@@ -190,9 +220,11 @@ public class TenantBackupsController {
/** Delete a stored backup. */
@PostMapping("/__admin/backups/{name}/delete")
@PreAuthorize("@authz.may('MANAGE_BACKUPS')")
public String delete(@PathVariable String name, RedirectAttributes redirect) {
public String delete(@PathVariable String name, Authentication authentication, RedirectAttributes redirect) {
Site site = boundTenancy();
backups.delete(site.id(), name);
if (backups.delete(site.id(), name)) {
siteLog.audit(site.id(), actor(authentication), "backup.deleted", name);
}
redirect.addFlashAttribute("flash", message("op.backups.deleted", "Backup deleted."));
return "redirect:/__admin/backups";
}
@@ -204,6 +236,7 @@ public class TenantBackupsController {
tenantAuthority.require(authentication, site.id());
try {
backups.restoreStored(site.id(), name, true); // a site manager never changes how the site is reached
siteLog.audit(site.id(), actor(authentication), "site.restored", name);
redirect.addFlashAttribute("flash", message("op.backups.restored", "Site restored from the backup."));
redirect.addFlashAttribute(AppBackupsController.REVIEW_HOSTS, Boolean.TRUE);
} catch (UnsupportedBackupFormatException e) {
@@ -227,6 +260,7 @@ public class TenantBackupsController {
}
try (InputStream in = file.getInputStream()) {
backups.restore(site.id(), in, true); // a site manager never changes how the site is reached
siteLog.audit(site.id(), actor(authentication), "site.restored", "(upload)");
redirect.addFlashAttribute("flash", message("op.backups.restored", "Site restored from the backup."));
redirect.addFlashAttribute(AppBackupsController.REVIEW_HOSTS, Boolean.TRUE);
} catch (UnsupportedBackupFormatException e) {
@@ -238,6 +272,20 @@ public class TenantBackupsController {
return "redirect:/__admin/backups";
}
/** Whether a {@code Range} header (or none) asks for the file from its first byte. */
static boolean startsAtTheBeginning(String range) {
return range == null || range.isBlank() || range.strip().replace(" ", "").startsWith("bytes=0-");
}
/** A HEAD request (a link checker, a preview) asks for the headers only: it builds and records nothing. */
static boolean isHead(HttpServletRequest request) {
return "HEAD".equalsIgnoreCase(request.getMethod());
}
private static String actor(Authentication authentication) {
return authentication == null ? "unknown" : authentication.getName();
}
private String message(String code, String fallback) {
return messages.getMessage(code, null, fallback, LocaleContextHolder.getLocale());
}
@@ -13,6 +13,8 @@ import mx.quest.runway.spi.service.ContentChanges;
import mx.quest.runway.spi.service.PluginSettings;
import mx.quest.runway.spi.service.PluginSiteFiles;
import mx.quest.runway.storage.StorageLayout;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InjectionPoint;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.beans.factory.annotation.Autowired;
@@ -49,6 +51,8 @@ import org.springframework.core.env.Environment;
@Configuration(proxyBeanMethods = false)
public class PluginScopedServices {
private static final Logger log = LoggerFactory.getLogger(PluginScopedServices.class);
private final PluginOwnership ownership;
private final SitePluginConfigService siteConfig;
private final SecretCipher cipher;
@@ -99,7 +103,26 @@ public class PluginScopedServices {
"kernel code reads per-site plugin settings through SitePluginConfigService");
return settings.computeIfAbsent(plugin.id(), id -> new PluginSettingsImpl(id,
plugin.descriptor().siteSettings(), plugin.descriptor().settings(),
key -> environment == null ? null : environment.getProperty(key), siteConfig, cipher));
key -> environment == null ? null : environment.getProperty(key), key -> savedApp(id, key),
siteConfig, cipher));
}
/**
* One saved app-level value in its stored form; {@code null} when unset, without a layout, or when the file cannot
* be read or parsed. A hand-edited file with a syntax error must not turn the plugin's check into an error page,
* and the parser's message is not logged: it can quote the offending line, which may hold a password.
*/
private String savedApp(String pluginId, String key) {
if (layout == null) {
return null;
}
try {
return PluginSettingsService.saved(layout, pluginId).get(key);
} catch (RuntimeException e) {
log.warn("plugin '{}': its saved settings file could not be read ({})", pluginId,
e.getClass().getSimpleName());
return null;
}
}
/** {@link PluginSiteFiles} bound to the injecting plugin's subtree {@code sites/<id>/plugins/<pluginId>/}. */
@@ -174,8 +174,20 @@ public class PluginSettingsService {
// ---- file I/O (nested YAML under runway.plugin.<id>) ------------------------------------------------
/** Flat map of {@code <settingKey> → stored string value} read from the file (empty if absent/unreadable). */
@SuppressWarnings("unchecked")
private Map<String, String> readSubtree(String pluginId) {
return saved(layout, pluginId);
}
/**
* One plugin's app-level settings as saved in {@code external/plugin-settings/<id>.yml}, flat
* {@code <settingKey> → stored string value}: empty when the file is absent. Secrets stay in their stored form.
* What {@code PluginSettings.savedApp} reads, so it and the form never disagree on what is saved.
*
* @throws UncheckedIOException when the file exists but cannot be read
* @throws RuntimeException the YAML parser's own exception when the file is not valid YAML
*/
@SuppressWarnings("unchecked")
public static Map<String, String> saved(StorageLayout layout, String pluginId) {
Path file = layout.pluginSettingsFile(pluginId); // traversal-safe
if (!Files.isRegularFile(file)) {
return Map.of();
@@ -41,6 +41,7 @@ public final class PluginSettingsImpl implements PluginSettings {
private final Map<String, PluginSettingDef> schema;
private final Map<String, PluginSettingDef> appSchema;
private final Function<String, String> appValues;
private final Function<String, String> savedAppValues;
private final SitePluginConfigService config;
private final SecretCipher cipher;
private final Map<String, Memo> memo = new ConcurrentHashMap<>();
@@ -74,6 +75,24 @@ public final class PluginSettingsImpl implements PluginSettings {
public PluginSettingsImpl(String pluginId, List<PluginSettingDef> siteSettings, List<PluginSettingDef> appSettings,
Function<String, String> appValues, SitePluginConfigService config,
SecretCipher cipher) {
this(pluginId, siteSettings, appSettings, appValues, 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 savedAppValues resolves a setting key to the value saved in the plugin's app-level settings file now,
* in its stored form, 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, Function<String, String> savedAppValues,
SitePluginConfigService config, SecretCipher cipher) {
this.savedAppValues = Objects.requireNonNull(savedAppValues, "savedAppValues");
this.pluginId = Objects.requireNonNull(pluginId, "pluginId");
this.schema = byKey(siteSettings);
this.appSchema = byKey(appSettings);
@@ -166,6 +185,29 @@ public final class PluginSettingsImpl implements PluginSettings {
PathSafety.KEY_SEPARATOR + "app" + PathSafety.KEY_SEPARATOR + key, key);
}
/**
* A key this plugin declared in its own app-level {@code settings:}, as saved in its settings file now: the saved
* value when not blank (a secret decrypted), else a non-secret's declared default. The file is read on each call,
* which suits the one use, checking settings before the restart that applies them.
*/
@Override
public Optional<String> savedApp(String key) {
PluginSettingDef def = key == null ? null : appSchema.get(key);
if (def == null) {
return Optional.empty();
}
String raw = savedAppValues.apply(key);
if (isSecret(def)) {
return reveal(raw, "the application (saved, not yet applied)",
PathSafety.KEY_SEPARATOR + "saved" + PathSafety.KEY_SEPARATOR + key, key);
}
if (raw != null && !raw.isBlank()) {
return Optional.of(raw);
}
Object fallback = def.defaultValue();
return fallback == null ? Optional.empty() : Optional.of(String.valueOf(fallback));
}
/** 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()) {
@@ -1194,6 +1194,7 @@ op.audit.action.site.created-from-backup=Site created from backup
op.audit.action.demo.installed=Demo site installed
op.audit.action.backup.saved=Backup saved
op.audit.action.backup.deleted=Backup deleted
op.audit.action.backup.downloaded=Backup downloaded
op.audit.action.site-template.created=Site template created
op.audit.action.site-template.imported=Site template imported
op.audit.action.site-template.deleted=Site template deleted
@@ -1225,6 +1226,12 @@ op.audit.action.page.unpublished=Page unpublished
op.audit.action.user.created=User created
op.audit.action.user.password-reset=User password reset
op.audit.action.user.deleted=User deleted
op.audit.action.user.updated=User changed
op.audit.action.user.suspended=User suspended
op.audit.action.user.resumed=User resumed
op.audit.action.static.uploaded=Static file uploaded
op.audit.action.static.folder-created=Static folder created
op.audit.action.static.deleted=Static file or folder deleted
op.audit.action.logs.settings-changed=Log settings changed
op.audit.action.site-config.changed=Site settings changed
@@ -1195,6 +1195,7 @@ op.audit.action.site.created-from-backup=Sitio creado desde una copia de segurid
op.audit.action.demo.installed=Sitio de demostración instalado
op.audit.action.backup.saved=Copia de seguridad guardada
op.audit.action.backup.deleted=Copia de seguridad eliminada
op.audit.action.backup.downloaded=Copia de seguridad descargada
op.audit.action.site-template.created=Plantilla de sitio creada
op.audit.action.site-template.imported=Plantilla de sitio importada
op.audit.action.site-template.deleted=Plantilla de sitio eliminada
@@ -1226,6 +1227,12 @@ op.audit.action.page.unpublished=Página despublicada
op.audit.action.user.created=Usuario creado
op.audit.action.user.password-reset=Contraseña de usuario restablecida
op.audit.action.user.deleted=Usuario eliminado
op.audit.action.user.updated=Usuario modificado
op.audit.action.user.suspended=Usuario suspendido
op.audit.action.user.resumed=Usuario reactivado
op.audit.action.static.uploaded=Archivo estático subido
op.audit.action.static.folder-created=Carpeta estática creada
op.audit.action.static.deleted=Archivo o carpeta estática eliminada
op.audit.action.logs.settings-changed=Ajustes de registros modificados
op.audit.action.site-config.changed=Ajustes del sitio modificados
@@ -44,7 +44,7 @@
<label class="form-label wi-label" for="wi-input">key</label>
<input class="form-control wi-input-text" type="text" id="wi-input" name="key" value="">
<textarea class="form-control wi-input-area" name="key" rows="3"></textarea>
<input class="form-control wi-input-secret" type="password" name="key" autocomplete="off"
<input class="form-control wi-input-secret" type="password" name="key" autocomplete="new-password"
placeholder="leave blank to keep">
<label class="form-check">
<input class="form-check-input wi-input-bool" type="checkbox" name="key" value="true">
@@ -58,7 +58,7 @@
<form id="ma-reset-form" method="post" class="row g-2">
<input class="ma-csrf" type="hidden" name="_csrf" value="">
<div class="col-md-6"><select class="form-select a11y-user" name="principalId" aria-label="User"><option class="ma-opt">m</option></select></div>
<div class="col-md-4"><input class="form-control a11y-newpass" name="password" type="password" placeholder="New password" aria-label="New password"></div>
<div class="col-md-4"><input class="form-control a11y-newpass" name="password" type="password" autocomplete="new-password" placeholder="New password" aria-label="New password"></div>
<div class="col-md-2"><button type="submit" class="btn btn-outline-secondary w-100" id="ma-reset-btn">Reset</button></div>
</form>
</div>
@@ -3,13 +3,15 @@
<head><meta charset="utf-8"><title>setting row</title></head>
<body>
<!-- One setting's row, inserted by the settings form once per field (selected by the .sr-row class, never an
id, because the form repeats it). Only the input variant matching the field's inputKind survives. -->
id, because the form repeats it). Only the input variant matching the field's inputKind survives.
A secret is "new-password": browsers ignore "off" on a text box followed by a password box and fill in the
operator's own console login, which a save would then store as the plugin's credential. -->
<div class="sr-row mb-3">
<label class="form-label sr-label" for="sr-input">key</label>
<input class="form-control sr-text" type="text" name="key" value="">
<textarea class="form-control sr-area" name="key" rows="3"></textarea>
<input class="form-control sr-secret" type="password" name="key" autocomplete="off"
<input class="form-control sr-secret" type="password" name="key" autocomplete="new-password"
placeholder="leave blank to keep">
<select class="form-select sr-select" name="key">
<option class="sr-opt" value="">value</option>
@@ -71,6 +71,67 @@ class BackupRestoreRecoveryTest {
"the scratch work dir is cleared");
}
/** The swap completed but the crash came before the logs were carried: they are merged, older lines first. */
@Test
void aCompletedSwapGetsItsLogsMergedOnStartup() throws IOException {
Path siteDir = layout.siteDir("demo");
Files.createDirectories(siteDir.resolve("logs"));
Files.writeString(siteDir.resolve("site.yml"), "id: demo\nname: RESTORED\n", StandardCharsets.UTF_8);
Files.writeString(siteDir.resolve("logs/audit-2026-10-30.log"), "AFTER\n", StandardCharsets.UTF_8);
Path old = workOld("demo");
Files.createDirectories(old.resolve("logs"));
Files.writeString(old.resolve("site.yml"), "id: demo\nname: BEFORE\n", StandardCharsets.UTF_8);
Files.writeString(old.resolve("logs/audit-2026-10-30.log"), "BEFORE\n", StandardCharsets.UTF_8);
Files.writeString(old.resolve("logs/audit-2026-10-29.log"), "YESTERDAY\n", StandardCharsets.UTF_8);
recovery.recover();
assertEquals("id: demo\nname: RESTORED\n", Files.readString(siteDir.resolve("site.yml")), "the restore stands");
assertEquals("BEFORE\nAFTER\n", Files.readString(siteDir.resolve("logs/audit-2026-10-30.log")),
"a day both have is joined in order");
assertEquals("YESTERDAY\n", Files.readString(siteDir.resolve("logs/audit-2026-10-29.log")));
assertFalse(Files.exists(layout.sites().resolve(BackupService.WORK_DIR).resolve("demo")));
}
/**
* A log write recreated the site folder between the two renames, and the process died: that folder holds only
* logs. It must not count as the site (which would delete `old`, the only copy); the site is rolled forward and
* the late lines follow its own.
*/
@Test
void aSiteFolderHoldingOnlyLateLogsIsNotMistakenForTheSite() throws IOException {
Path siteDir = layout.siteDir("demo");
Files.createDirectories(siteDir.resolve("logs"));
Files.writeString(siteDir.resolve("logs/access-2026-10-30.log"), "LATE\n", StandardCharsets.UTF_8);
Path old = workOld("demo");
Files.createDirectories(old.resolve("logs"));
Files.writeString(old.resolve("site.yml"), "id: demo\n", StandardCharsets.UTF_8);
Files.writeString(old.resolve("logs/access-2026-10-30.log"), "EARLIER\n", StandardCharsets.UTF_8);
recovery.recover();
assertEquals("id: demo\n", Files.readString(siteDir.resolve("site.yml")), "the original site is back");
assertEquals("EARLIER\nLATE\n", Files.readString(siteDir.resolve("logs/access-2026-10-30.log")));
assertFalse(Files.exists(layout.sites().resolve(BackupService.WORK_DIR).resolve("demo")));
}
/** A rollback put the site back but could not merge the lines written meanwhile: they follow its own. */
@Test
void lateLinesLeftByARollbackAreMergedAfterTheSitesOwn() throws IOException {
Path siteDir = layout.siteDir("demo");
Files.createDirectories(siteDir.resolve("logs"));
Files.writeString(siteDir.resolve("site.yml"), "id: demo\n", StandardCharsets.UTF_8);
Files.writeString(siteDir.resolve("logs/access-2026-10-30.log"), "OWN\n", StandardCharsets.UTF_8);
Path late = layout.sites().resolve(BackupService.WORK_DIR).resolve("demo").resolve(BackupService.LATE_DIR);
Files.createDirectories(late.resolve("logs"));
Files.writeString(late.resolve("logs/access-2026-10-30.log"), "LATE\n", StandardCharsets.UTF_8);
recovery.recover();
assertEquals("OWN\nLATE\n", Files.readString(siteDir.resolve("logs/access-2026-10-30.log")));
assertFalse(Files.exists(layout.sites().resolve(BackupService.WORK_DIR).resolve("demo")));
}
@Test
void noWorkDirIsANoOp() {
recovery.recover(); // must not throw when sites/.restore-work does not exist
@@ -4,6 +4,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assumptions.assumeFalse;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
@@ -492,6 +493,113 @@ class BackupServiceTest {
assertTrue(sawContent, "real site content is still archived");
}
/** A restore replaces the content, not the site's history: its audit log and stats stay as they were. */
@Test
void aRestoreKeepsTheLiveSitesLogsAndStats() throws IOException {
ByteArrayOutputStream archive = new ByteArrayOutputStream();
svc.backup("demo", archive);
write(siteDir.resolve("logs/audit-2026-10-30.log"), "LIVE-AUDIT");
write(siteDir.resolve("stats/bandwidth.csv"), "LIVE-STATS");
write(siteDir.resolve("templates/_master.html"), "MASTER_BROKEN");
svc.restore("demo", new ByteArrayInputStream(archive.toByteArray()));
assertEquals("MASTER_V1", read(siteDir.resolve("templates/_master.html")), "the content is restored");
assertEquals("LIVE-AUDIT", read(siteDir.resolve("logs/audit-2026-10-30.log")), "the audit log survives");
assertEquals("LIVE-STATS", read(siteDir.resolve("stats/bandwidth.csv")), "the stats survive");
}
/** A backup never writes logs or stats, so whatever an archive carries under those names is discarded. */
@Test
void aRestoreDiscardsLogsAndStatsCarriedByTheArchive() throws IOException {
ByteArrayOutputStream original = new ByteArrayOutputStream();
svc.backup("demo", original);
ByteArrayOutputStream crafted = new ByteArrayOutputStream();
try (ZipInputStream in = new ZipInputStream(new ByteArrayInputStream(original.toByteArray()));
ZipOutputStream out = new ZipOutputStream(crafted)) {
ZipEntry e;
while ((e = in.getNextEntry()) != null) {
out.putNextEntry(new ZipEntry(e.getName()));
in.transferTo(out);
out.closeEntry();
}
for (String planted : List.of("site/logs/audit-2026-10-30.log", "site/logs/audit-2026-10-29.log",
"site/stats/bandwidth.csv")) {
out.putNextEntry(new ZipEntry(planted));
out.write("PLANTED".getBytes(StandardCharsets.UTF_8));
out.closeEntry();
}
}
// The live site has an audit log of its own, and no stats yet.
write(siteDir.resolve("logs/audit-2026-10-30.log"), "LIVE-AUDIT");
svc.restore("demo", new ByteArrayInputStream(crafted.toByteArray()));
assertEquals("LIVE-AUDIT", read(siteDir.resolve("logs/audit-2026-10-30.log")), "the live log is kept");
assertFalse(Files.exists(siteDir.resolve("logs/audit-2026-10-29.log")), "no planted day is added");
assertFalse(Files.exists(siteDir.resolve("stats")), "no planted stats appear");
}
private Path work(String siteId) {
return layout.sites().resolve(BackupService.WORK_DIR).resolve(siteId);
}
/** A merge that fails is kept, never deleted, and a repeated run finishes it without joining anything twice. */
@Test
void aFailedLogMergeIsKeptAndFinishedByTheNextRun() throws IOException {
write(siteDir.resolve("logs/audit-2026-10-30.log"), "NEW\n");
Path old = work("demo").resolve("old");
write(old.resolve("site.yml"), "id: demo\n");
write(old.resolve("logs/audit-2026-10-29.log"), "YESTERDAY\n");
Path unreadable = old.resolve("logs/audit-2026-10-30.log");
write(unreadable, "OLD\n");
unreadable.toFile().setReadable(false);
// As root (some CI containers) a file stays readable whatever its mode: the failure cannot be staged there.
assumeFalse(Files.isReadable(unreadable), "the file can be made unreadable");
try {
assertThrows(IOException.class, () -> BackupService.settle(siteDir, work("demo")));
} finally {
assertTrue(unreadable.toFile().setReadable(true));
}
assertTrue(Files.exists(unreadable), "the unmerged log is kept");
BackupService.settle(siteDir, work("demo"));
assertEquals("OLD\nNEW\n", read(siteDir.resolve("logs/audit-2026-10-30.log")), "joined once, in order");
assertEquals("YESTERDAY\n", read(siteDir.resolve("logs/audit-2026-10-29.log")), "moved once");
}
/** Logs a previous restore could not carry over are merged by the next restore of the site, not deleted. */
@Test
void theNextRestoreFinishesLogsAPreviousOneLeftBehind() throws IOException {
ByteArrayOutputStream archive = new ByteArrayOutputStream();
svc.backup("demo", archive);
write(work("demo").resolve("old/site.yml"), "id: demo\n");
write(work("demo").resolve("old/logs/audit-2026-10-29.log"), "LEFT-BEHIND\n");
svc.restore("demo", new ByteArrayInputStream(archive.toByteArray()));
assertEquals("LEFT-BEHIND\n", read(siteDir.resolve("logs/audit-2026-10-29.log")));
assertFalse(Files.exists(work("demo")), "the work folder is cleared once settled");
}
/** A new site starts its own logs: a leftover folder under its id (no site.yml) is not adopted. */
@Test
void aSiteCreatedFromABackupDoesNotAdoptLeftoverLogs() throws IOException {
new SiteStore(layout, new YamlStore()).save(new Site("src", "Source", List.of("src.test"), Locale.ENGLISH,
List.of(Locale.ENGLISH), "https://src.test", SiteStatus.ACTIVE));
write(layout.siteDir("src").resolve("templates/home.html"), "SRC_CONTENT");
ByteArrayOutputStream archive = new ByteArrayOutputStream();
svc.backup("src", archive);
Path stray = layout.siteDir("clone");
write(stray.resolve("logs/audit-2026-10-30.log"), "STRAY");
svc.createFromBackup("clone", "Cloned", List.of("clone.test"), new ByteArrayInputStream(archive.toByteArray()));
assertTrue(Files.exists(stray.resolve("site.yml")), "the site is created");
assertFalse(Files.exists(stray.resolve("logs")), "no leftover log becomes the new site's journal");
}
// ---- a restore must not make every page look edited today ------------------------------------
/**
@@ -103,7 +103,9 @@ class AuditViewTest {
"permissions.role-inherit-removed", "page.saved", "page.deleted", "page.published",
"page.unpublished", "user.created", "user.password-reset", "user.deleted",
"plugin.settings-changed", "logs.settings-changed", "site-config.changed", "master.assigned",
"master.unassigned", "site.created", "site.hosts-updated", "backup.saved",
"master.unassigned", "site.created", "site.hosts-updated", "backup.saved", "backup.deleted",
"backup.downloaded", "site.restored", "user.updated", "user.suspended", "user.resumed",
"static.uploaded", "static.folder-created", "static.deleted",
"platform.kernel-settings-changed", "platform.kernel-setting-adopted")) {
assertTrue(en.contains(recorded), "a label for " + recorded);
}
@@ -2,10 +2,17 @@ package mx.quest.runway.console;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.ArgumentMatchers.startsWith;
import static org.mockito.Mockito.clearInvocations;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestBuilders.formLogin;
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf;
import static org.springframework.security.test.web.servlet.setup.SecurityMockMvcConfigurers.springSecurity;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.head;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.multipart;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
@@ -23,6 +30,7 @@ import java.util.Set;
import mx.quest.runway.authz.GrantFile;
import mx.quest.runway.authz.GrantStore;
import mx.quest.runway.backup.BackupService;
import mx.quest.runway.log.SiteLogService;
import mx.quest.runway.security.PasswordEncoders;
import mx.quest.runway.security.PasswordStrength;
import mx.quest.runway.security.Roles;
@@ -46,6 +54,7 @@ import org.springframework.mock.web.MockHttpSession;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.test.context.DynamicPropertyRegistry;
import org.springframework.test.context.DynamicPropertySource;
import org.springframework.test.context.bean.override.mockito.MockitoSpyBean;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.request.RequestPostProcessor;
@@ -104,6 +113,8 @@ class TenantBackupsScreenTest {
private SiteResolver siteResolver;
@Autowired
private BackupService backups;
@MockitoSpyBean
private SiteLogService siteLog;
private MockMvc mvc;
@BeforeEach
@@ -189,6 +200,75 @@ class TenantBackupsScreenTest {
}
}
// --- the site's audit log ----------------------------------------------------------------------
/** Each act that took effect is one line in the site's own audit log, with who did it and what. */
@Test
void everyBackupActIsRecordedInTheSitesAuditLog() throws Exception {
MockHttpSession admin = sessionFor("admin");
clearInvocations(siteLog);
mvc.perform(post("/__admin/backups/create").session(admin).with(csrf()))
.andExpect(status().is3xxRedirection());
String name = backups.list("acme").get(0).name();
verify(siteLog).audit("acme", "admin", "backup.saved", name);
mvc.perform(get("/__admin/backups/download").session(admin)).andExpect(status().isOk());
verify(siteLog).audit("acme", "admin", "backup.downloaded", "full");
mvc.perform(get("/__admin/backups/download-transfer").session(admin)).andExpect(status().isOk());
verify(siteLog).audit("acme", "admin", "backup.downloaded", "transfer");
mvc.perform(get("/__admin/backups/" + name + "/download").session(admin)).andExpect(status().isOk());
verify(siteLog).audit("acme", "admin", "backup.downloaded", "full " + name);
mvc.perform(post("/__admin/backups/" + name + "/restore").session(admin).with(csrf()))
.andExpect(flash().attributeExists("flash"));
verify(siteLog).audit("acme", "admin", "site.restored", name);
byte[] zip = mvc.perform(get("/__admin/backups/download").session(admin)).andReturn()
.getResponse().getContentAsByteArray();
mvc.perform(multipart("/__admin/backups/restore")
.file(new MockMultipartFile("file", "acme.zip", "application/zip", zip))
.session(admin).with(csrf()))
.andExpect(flash().attributeExists("flash"));
verify(siteLog).audit("acme", "admin", "site.restored", "(upload)");
mvc.perform(post("/__admin/backups/" + name + "/delete").session(admin).with(csrf()))
.andExpect(status().is3xxRedirection());
verify(siteLog).audit("acme", "admin", "backup.deleted", name);
}
/** A refused, failed or empty act writes nothing: the log says what happened, not what was tried. */
@Test
void aRefusedOrFailedBackupActIsNotRecorded() throws Exception {
String name = storedBackup();
MockHttpSession keeper = sessionFor("keeper");
MockHttpSession admin = sessionFor("admin");
clearInvocations(siteLog);
mvc.perform(get("/__admin/backups/download").session(keeper)).andExpect(status().isForbidden());
mvc.perform(get("/__admin/backups/" + name + "/download").session(keeper))
.andExpect(status().isForbidden());
// A HEAD request (a link checker, a preview) takes no copy: answered, not recorded.
for (String path : List.of("/__admin/backups/download", "/__admin/backups/download-transfer",
"/__admin/backups/" + name + "/download")) {
mvc.perform(head(path).session(admin))
.andExpect(status().isOk())
.andExpect(header().string("Content-Disposition", Matchers.containsString("attachment")));
}
// A range that resumes a download is not a new one.
mvc.perform(get("/__admin/backups/" + name + "/download").session(admin).header("Range", "bytes=10-"))
.andExpect(status().isPartialContent());
mvc.perform(post("/__admin/backups/" + name + "/restore").session(keeper).with(csrf()))
.andExpect(status().isForbidden());
mvc.perform(post("/__admin/backups/no-such-backup.zip/delete").session(admin).with(csrf()))
.andExpect(status().is3xxRedirection());
mvc.perform(post("/__admin/backups/no-such-backup.zip/restore").session(admin).with(csrf()))
.andExpect(flash().attributeExists("error"));
mvc.perform(multipart("/__admin/backups/restore")
.file(new MockMultipartFile("file", "junk.zip", "application/zip", new byte[] {1, 2, 3}))
.session(admin).with(csrf()))
.andExpect(flash().attributeExists("error"));
verify(siteLog, never()).audit(anyString(), anyString(), startsWith("backup."), anyString());
verify(siteLog, never()).audit(anyString(), anyString(), eq("site.restored"), anyString());
}
/** Without MANAGE_BACKUPS at all, nothing — not even a transfer copy. */
@Test
void anOperatorWithoutTheGrantGetsNoDownloadOfAnyKind() throws Exception {
@@ -421,6 +421,41 @@ class PluginContributionPolicyTest {
"p2 declared no app-level secret, so the environment's value is not handed out");
}
@Test
void theFactoryHandsAPluginItsOwnSavedAppSettingsFromItsOwnFileOnly() throws Exception {
assumeTrue(PluginFixture.compilerAvailable());
String schema = "settings:\n - { key: apiKey, type: secret, label: l }\n"
+ " - { key: host, type: string, label: l }\n";
PluginDescriptor d1 = PluginDescriptor.read(new ByteArrayInputStream(("id: p1\nversion: 1.0.0\nmainClass: x.Y\n"
+ schema).getBytes(StandardCharsets.UTF_8)));
PluginDescriptor d2 = PluginDescriptor.read(new ByteArrayInputStream(("id: p2\nversion: 1.0.0\nmainClass: x.Y\n"
+ schema).getBytes(StandardCharsets.UTF_8)));
PluginOwnership owners = PluginOwnership.of(new PluginRuntime(
List.of(new LoadedPlugin(d1, root.resolve("p1")), new LoadedPlugin(d2, root.resolve("p2"))), loader,
Map.of(), false));
mx.quest.runway.storage.StorageProperties props = new mx.quest.runway.storage.StorageProperties();
props.setExternal(root.resolve("external-saved"));
mx.quest.runway.storage.StorageLayout layout = mx.quest.runway.storage.StorageLayout.from(props);
java.nio.file.Path p1File = layout.pluginSettingsFile("p1");
java.nio.file.Files.createDirectories(p1File.getParent());
java.nio.file.Files.writeString(p1File, "runway:\n plugin:\n p1:\n host: saved.example\n"
+ " apiKey: p1-saved\n");
org.springframework.mock.env.MockEnvironment env = new org.springframework.mock.env.MockEnvironment()
.withProperty("runway.plugin.p1.host", "running.example");
PluginScopedServices scoped = new PluginScopedServices(owners,
new SitePluginConfigService(layout, null, event -> { }), null, layout, 1024, env);
PluginSettings p1 = scoped.pluginSettings(pointIn(head("p1", "k", false).getClass(), "key"));
PluginSettings p2 = scoped.pluginSettings(pointIn(head("p2", "k", false).getClass(), "key"));
assertEquals(Optional.of("saved.example"), p1.savedApp("host"), "the file as saved, not the environment");
assertEquals(Optional.of("p1-saved"), p1.savedApp("apiKey"), "its own saved secret (plaintext as written)");
assertEquals(Optional.empty(), p2.savedApp("host"), "p2 has no file of its own: p1's is never read for it");
assertEquals(Optional.empty(), p2.savedApp("apiKey"));
java.nio.file.Files.writeString(p1File, "runway:\n plugin:\n p1:\n host: [unclosed\n");
assertEquals(Optional.empty(), p1.savedApp("host"), "an unparsable file answers empty, never throws");
}
@Test
void anInjectionPointInAPluginsOwnJarBindsToThatPlugin() throws Exception {
assumeTrue(PluginFixture.compilerAvailable());
@@ -273,4 +273,90 @@ class PluginSettingsImplTest {
assertEquals(Optional.empty(), bare.appSecret("password"),
"an implementation written against SPI 1.0 still compiles and answers empty");
}
// ---- saved app-level settings (SPI 1.2.0) -------------------------------------------------------
private void saveAppFile(String plugin, String yaml) throws IOException {
Path file = layout.pluginSettingsFile(plugin);
Files.createDirectories(file.getParent());
Files.writeString(file, yaml);
}
/** As the kernel wires it: the saved values come from the plugin's own settings file. */
private PluginSettingsImpl withSavedApp(String plugin) {
return new PluginSettingsImpl(plugin, SCHEMA, APP_SCHEMA, environment::get,
key -> mx.quest.runway.plugin.PluginSettingsService.saved(layout, plugin).get(key), config, cipher);
}
@Test
void aSavedAppSettingIsReadFromTheFileNotFromTheRunningEnvironment() throws IOException {
environment.put("runway.plugin.database.host", "running.example");
environment.put("runway.plugin.database.password", "running-secret");
saveAppFile("database", "runway:\n plugin:\n database:\n host: saved.example\n password: "
+ cipher.encrypt("saved-secret") + "\n");
PluginSettingsImpl settings = withSavedApp("database");
assertEquals(Optional.of("saved.example"), settings.savedApp("host"));
assertEquals(Optional.of("saved-secret"), settings.savedApp("password"), "a saved secret, decrypted");
assertEquals(Optional.of("running-secret"), settings.appSecret("password"), "appSecret keeps the running one");
}
@Test
void aSaveAfterStartupIsSeenOnTheNextCall() throws IOException {
PluginSettingsImpl settings = withSavedApp("database");
saveAppFile("database", "runway:\n plugin:\n database:\n host: first.example\n");
assertEquals(Optional.of("first.example"), settings.savedApp("host"));
saveAppFile("database", "runway:\n plugin:\n database:\n host: second.example\n");
assertEquals(Optional.of("second.example"), settings.savedApp("host"), "read from the file each time");
}
@Test
void anUnsavedOrBlankSettingFallsBackToTheDeclaredDefaultExceptASecret() throws IOException {
PluginSettingsImpl settings = withSavedApp("database");
assertEquals(Optional.of("localhost"), settings.savedApp("host"), "no file: the declared default");
assertEquals(Optional.empty(), settings.savedApp("password"), "a secret has no default");
saveAppFile("database", "runway:\n plugin:\n database:\n host: ' '\n password: ''\n");
assertEquals(Optional.of("localhost"), settings.savedApp("host"));
assertEquals(Optional.empty(), settings.savedApp("password"));
}
@Test
void onlyTheCallersOwnDeclaredAppKeysAreRead() throws IOException {
saveAppFile("database", "runway:\n plugin:\n database:\n undeclared: x\n smtpPassword: y\n");
saveAppFile("other", "runway:\n plugin:\n other:\n host: not-mine\n");
PluginSettingsImpl settings = withSavedApp("database");
assertEquals(Optional.empty(), settings.savedApp("undeclared"));
assertEquals(Optional.empty(), settings.savedApp("smtpPassword"), "declared only in siteSettings:");
assertEquals(Optional.empty(), settings.savedApp(null));
assertEquals(Optional.of("localhost"), settings.savedApp("host"), "another plugin's file is never read");
}
@Test
void aSavedSecretThatCannotBeDecryptedIsEmptyAndAPlaintextOneIsReturned() throws IOException {
PluginSettingsImpl settings = withSavedApp("database");
saveAppFile("database", "runway:\n plugin:\n database:\n password: hand-written\n");
assertEquals(Optional.of("hand-written"), settings.savedApp("password"));
saveAppFile("database", "runway:\n plugin:\n database:\n password: " + cipher.encrypt("s")
+ "\n");
cipherBroken = true;
assertEquals(Optional.empty(), settings.savedApp("password"));
}
@Test
void theOlderConstructorsAndTheSpiDefaultHaveNoSavedValues() {
environment.put("runway.plugin.database.host", "running.example");
assertEquals(Optional.of("localhost"), withApp("database").savedApp("host"),
"no saved-values lookup: only the declared default");
mx.quest.runway.spi.service.PluginSettings bare = new mx.quest.runway.spi.service.PluginSettings() {
@Override
public SettingsView site(String siteId) {
return new SettingsView(java.util.Map.of());
}
@Override
public Optional<String> secret(String siteId, String key) {
return Optional.empty();
}
};
assertEquals(Optional.empty(), bare.savedApp("host"), "an implementation written before SPI 1.2.0");
}
}