Runway 1.2.0
This commit is contained in:
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>
|
||||
|
||||
Reference in new issue
Block a user