Runway 1.0.0

This commit is contained in:
Runway committed 2026-10-21 11:34:34 -06:00
commit dcf819146b
1372 files changed
+188168

No files matched your search

@@ -0,0 +1,137 @@
package mx.quest.demo;
import java.time.Instant;
import java.util.ArrayDeque;
import java.util.Deque;
import java.util.List;
import java.util.Locale;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import mx.quest.runway.spi.model.CatalogChange;
import mx.quest.runway.spi.model.LocalizedUrl;
import mx.quest.runway.spi.model.SettingsChange;
import mx.quest.runway.spi.model.SiteLifecycleEvent;
import mx.quest.runway.spi.model.SiteView;
import mx.quest.runway.spi.service.SiteEventListener;
import mx.quest.runway.spi.service.Sites;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* {@code SiteEventListener} in the default {@link Phase#CONSUMER CONSUMER} phase — what a plugin that reacts to
* changes it does not own implements (a sitemap, a search index, a change notifier). It replaces listening to the
* host's internal Spring events, whose order against the kernel's caches was never a contract.
*
* <p><b>When each callback is for:</b>
* <ul>
* <li>{@link #onSettingsChanged} — a save of <b>this plugin's own</b> per-site settings (and nothing else);
* {@code PluginSettings.site()} already returns the new values. The demo writes an audit note, as 1.x did —
* but only when {@link SettingsChange#local()} is true: on a cluster every node receives the change (the
* others as a replay, {@code local == false}), and a side effect must happen once, not once per node.</li>
* <li>{@link #onCatalogChanged} — anything that may reshape a site's content surface: a page write ({@code PAGE}),
* a {@code ContentChanges} call ({@code CONTENT}), a lifecycle event ({@code SITE}) or any plugin's settings
* save ({@code SETTINGS}). A {@code PAGE} or {@code CONTENT} change carries the item's URLs <b>before</b>
* ({@code previousUrls}, so a deleted or moved item still names its old address) and <b>after</b>
* ({@code currentUrls}). The demo keeps the last {@value #KEEP} per site in memory and shows them on its
* console screen — an IndexNow-style notifier would submit the union of both lists.</li>
* <li>{@link #onSiteLifecycle} — created, updated, suspended, resumed, deleted, restored. On a <b>wholesale</b>
* event (deleted, restored) drop everything derived from the site's files; here, the recorded activity.</li>
* </ul>
* <b>Guarantees you can rely on:</b> every kernel cache the change affects is already evicted (reads see the new
* state); no host lock is held (calling any service is safe); one throwing callback is logged and counted, never
* propagated. <b>Duty:</b> callbacks run on the writer's thread — evict, record or enqueue; anything slow (a network
* call, an index rebuild) belongs on your own executor. The audit note is one small, bounded file write.
*
* <p>It also shows {@link Sites}: the way code that knows a site only by id — a listener, a background task — gets
* the site's {@link SiteView}, off-request.
*/
public class DemoActivity implements SiteEventListener {
/** How many recent changes are kept per site. */
static final int KEEP = 10;
private static final Logger log = LoggerFactory.getLogger(DemoActivity.class);
/**
* One recorded change, as the console screen shows it.
*
* @param at when this node received it
* @param cause {@code PAGE}, {@code CONTENT}, {@code SITE}, {@code SETTINGS} (lower case)
* @param item {@code <sourceKey>:<id>}, the plugin for a settings change, or {@code ""}
* @param previousUrls the item's paths before the change
* @param currentUrls the item's paths after it
* @param local whether the change happened on this node
*/
public record Entry(Instant at, String cause, String item, List<String> previousUrls, List<String> currentUrls,
boolean local) {
}
private final DemoNotesStore notes;
private final Sites sites;
private final ConcurrentMap<String, Deque<Entry>> recent = new ConcurrentHashMap<>();
public DemoActivity(DemoNotesStore notes, Sites sites) {
this.notes = notes;
this.sites = sites;
}
@Override
public void onSiteLifecycle(SiteLifecycleEvent event) {
String name = sites.find(event.siteId()).map(SiteView::displayName).orElse("(gone)");
log.info("runway-demo saw site '{}' ({}) {}{}", event.siteId(), name, event.kind(),
event.fromBackup() ? " from a backup" : "");
if (event.wholesale()) {
recent.remove(event.siteId());
}
}
@Override
public void onSettingsChanged(SettingsChange change) {
if (!change.local()) {
return; // replayed from another node: that node already wrote the note
}
try {
int count = notes.append(change.siteId(), "Per-site settings saved at " + Instant.now(),
Note.ORIGIN_SYSTEM);
log.info("runway-demo settings changed for site '{}': audit note appended (now {} notes)",
change.siteId(), count);
} catch (RuntimeException e) {
log.warn("runway-demo could not append the settings audit note for site '{}': {}", change.siteId(),
e.toString());
}
}
@Override
public void onCatalogChanged(CatalogChange change) {
String item = switch (change.cause()) {
case PAGE, CONTENT -> (change.sourceKey() == null ? "?" : change.sourceKey()) + ":"
+ (change.id() == null ? "*" : change.id());
case SETTINGS -> change.pluginId() == null ? "" : change.pluginId();
default -> ""; // SITE, and any cause a later SPI adds
};
Entry entry = new Entry(Instant.now(), change.cause().name().toLowerCase(Locale.ROOT), item,
paths(change.previousUrls()), paths(change.currentUrls()), change.local());
Deque<Entry> entries = recent.computeIfAbsent(change.siteId(), id -> new ArrayDeque<>());
synchronized (entries) {
entries.addFirst(entry);
while (entries.size() > KEEP) {
entries.removeLast();
}
}
}
/** The site's recent changes, newest first. */
public List<Entry> recent(String siteId) {
Deque<Entry> entries = recent.get(siteId);
if (entries == null) {
return List.of();
}
synchronized (entries) {
return List.copyOf(entries);
}
}
private static List<String> paths(List<LocalizedUrl> urls) {
return urls.stream().map(LocalizedUrl::path).toList();
}
}
@@ -0,0 +1,98 @@
package mx.quest.demo;
import java.util.List;
import mx.quest.runway.spi.RunwaySpi;
import mx.quest.runway.spi.model.PluginInfo;
import mx.quest.runway.spi.model.SiteView;
import mx.quest.runway.spi.service.PluginSettings;
import mx.quest.runway.spi.service.SitePages;
import mx.quest.runway.spi.service.Sites;
/**
* Backs the plugin's console fragments — the dashboard card ({@code templates/dashboard.*}) and the admin fragment
* under the settings form ({@code templates/admin.*}). The host does not push data into a fragment; the fragment's
* decoupled logic reads this bean by name, {@code ${@runwayDemoAdminModel.noteCount(tenantSiteId)}}, with
* {@code tenantSiteId} supplied by the console (and {@code null} on the application console, so every accessor is
* null-safe and a fragment never errors).
*
* <p>What a fragment may rely on is a contract: the variables {@code tenantSiteId} and {@code _csrf}, the expressions
* {@code ${@<own bean>…}} and {@code ${@authz.may('…')}}, and {@code #{…}} messages. Nothing else in the console's
* model is promised — so anything else a fragment shows comes from a bean like this one.
*
* <p>It shows three services in their read-only roles: {@link Sites} (a site's view from its id, off-request — the
* fragment only has the id), {@link SitePages#pathOf} (where "our" starter page lives now, whatever its state, even
* after an operator moved it) and {@link PluginSettings#secret} (whether a per-site secret is set — answered without
* ever exposing the value). {@link PluginInfo} is this plugin's identity.
*/
public class DemoAdminModel {
private static final int RECENT = 5;
private final DemoNotesStore notes;
private final DemoAppProps props;
private final PluginSettings settings;
private final Sites sites;
private final SitePages pages;
private final PluginInfo self;
public DemoAdminModel(DemoNotesStore notes, DemoAppProps props, PluginSettings settings, Sites sites,
SitePages pages, PluginInfo self) {
this.notes = notes;
this.props = props;
this.settings = settings;
this.sites = sites;
this.pages = pages;
this.self = self;
}
private static boolean noSite(String siteId) {
return siteId == null || siteId.isBlank();
}
public int noteCount(String siteId) {
return noSite(siteId) ? 0 : notes.count(siteId);
}
/** The newest notes, newest first, for the admin fragment's list. */
public List<Note> recentNotes(String siteId) {
return noSite(siteId) ? List.of() : notes.recent(siteId, RECENT);
}
/** The site's display name, from {@link Sites#find}; the id itself when the site is unknown. */
public String siteName(String siteId) {
return noSite(siteId) ? "" : sites.find(siteId).map(SiteView::displayName).orElse(siteId);
}
/** Where the demo's starter page lives now (any state), or {@code ""} when it is not installed. */
public String demoPagePath(String siteId) {
return noSite(siteId) ? "" : pages.pathOf(siteId, DemoConsoleController.STARTER_SLUG).orElse("");
}
/** Whether the per-site {@code analytics.site-token} secret is set; the value itself never leaves the plugin. */
public boolean siteTokenConfigured(String siteId) {
return !noSite(siteId) && settings.secret(siteId, "analytics.site-token").isPresent();
}
/** This plugin's version, from {@code plugin.yml} (via {@link PluginInfo}). */
public String pluginVersion() {
return self.version();
}
/** The SPI version this plugin was compiled against (a constant the compiler inlined). */
public String builtSpi() {
return RunwaySpi.VERSION;
}
/** The SPI version of the kernel this plugin is running on. */
public String runningSpi() {
return RunwaySpi.runtimeVersion();
}
public boolean bannerEnabled() {
return props.getBanner().isEnabled();
}
public boolean analyticsKeyConfigured() {
return props.getAnalytics().hasKey();
}
}
@@ -0,0 +1,76 @@
package mx.quest.demo;
import java.util.List;
import mx.quest.runway.spi.HeadContributor;
import mx.quest.runway.spi.RunwaySpi;
import mx.quest.runway.spi.model.Capabilities;
import mx.quest.runway.spi.model.HeadContext;
import mx.quest.runway.spi.model.SettingsView;
import mx.quest.runway.spi.service.PluginSettings;
/**
* {@code HeadContributor} — splices markup into every page's {@code <head>} at the response edge, so it lands on every
* page without any edit to a tenant's templates. Ordered {@code @Order(200)} in {@link DemoPluginConfig}, after the
* kernel's own SEO ({@code @Order(100)}) and icon ({@code @Order(90)}) contributors.
*
* <p>Emits an escaped {@code <meta name="generator">} from the app-level {@code generator.label} setting, the plugin's
* stylesheet while the per-site notice is enabled, and — only when the per-site {@code analytics.enabled} flag is on
* and the app-level {@code analytics.write-key} secret is set — an inert analytics {@code <script>} (plain
* {@code <script src>}: the kernel stamps the CSP nonce on it). Returns {@code ""}, never {@code null}, when it has
* nothing to add.
*
* <p><b>{@code PluginSettings}</b> is how a plugin reads its own per-site settings: {@code site(siteId)} returns a
* {@link SettingsView} with the {@code siteSettings:} defaults already applied and the saved values over them, so the
* code fallback only matters for undeclared keys. It is bound to this plugin by the jar it was injected into.
*/
public class DemoAnalyticsHead implements HeadContributor {
private final DemoAppProps props;
private final PluginSettings settings;
public DemoAnalyticsHead(DemoAppProps props, PluginSettings settings) {
this.props = props;
this.settings = settings;
}
@Override
public String key() {
return "runway-demo/analytics";
}
@Override
public String render(HeadContext ctx) {
SettingsView site = settings.site(ctx.site().id());
StringBuilder out = new StringBuilder();
// A provenance comment: the SPI this plugin was built against (a constant), and an input the host hands in.
out.append("\n<!-- runway-demo ").append(Html.escape(RunwaySpi.VERSION))
.append(ctx.noindex() ? " (noindex)" : "").append(" -->");
out.append("\n<meta name=\"generator\" content=\"").append(Html.escape(props.getGenerator().getLabel()))
.append("\">");
if (site.bool("notice.enabled", true)) {
// The plugin's own stylesheet, from its static-asset namespace, so the widgets are styled.
out.append("\n<link rel=\"stylesheet\" href=\"/__plugin/runway-demo/static/css/demo.css\">");
}
if (site.bool("analytics.enabled", false) && props.getAnalytics().hasKey()) {
// Inert placeholder — a real plugin would emit its vendor's snippet here. No key goes into the page.
out.append("\n<script data-demo-analytics=\"1\" src=\"/__plugin/runway-demo/static/js/demo-analytics.js\"")
.append(" data-site=\"").append(Html.escape(ctx.site().id())).append("\" defer></script>");
}
return out.toString();
}
@Override
public Capabilities capabilities() {
return Capabilities.of("head.per-locale");
}
/**
* This contributor's whole per-site input: its own settings file. Head markup is spliced in after a page's
* {@code ETag} has been computed, so the host folds the files listed here into the validator — without it, a
* settings change would alter the delivered page but not its {@code ETag}, and clients would keep the old head.
*/
@Override
public List<String> headInputs(String siteId) {
return List.of("plugins/runway-demo.yml");
}
}
@@ -0,0 +1,112 @@
package mx.quest.demo;
import org.springframework.boot.context.properties.NestedConfigurationProperty;
/**
* The demo's <b>app-level</b> settings, bound from {@code external/plugin-settings/runway-demo.yml} (keys under
* {@code runway.plugin.runway-demo.*}) — the plugin.yml {@code settings:} schema. App-level settings are PLATFORM
* concerns and apply on <b>restart</b>; a plugin reads them through its own Spring {@code @ConfigurationProperties}
* binding (descriptor contract), never through host machinery. Field defaults mirror the schema defaults so the
* plugin behaves sensibly when the file is absent.
*
* <p>Registered by the {@code @Bean @ConfigurationProperties("runway.plugin.runway-demo")} method
* {@code DemoPluginConfig#runwayDemoAppProps}, <b>not</b> by {@code @EnableConfigurationProperties}: that annotation
* names the bean {@code "<prefix>-<class name>"}, which breaks the kernel's rule that every plugin bean name starts
* with the plugin id ({@code runwayDemo…}).
*
* <p>The {@code analytics.write-key} is a {@code secret}-typed <i>app-level</i> setting: in the property map it is the
* {@code ENC(...)} ciphertext the host stores, so this demo uses it as presence only. (A <i>per-site</i> secret is
* read in clear with {@code PluginSettings.secret} — see {@link DemoAdminModel#siteTokenConfigured}.)
*/
public class DemoAppProps {
@NestedConfigurationProperty
private final Banner banner = new Banner();
@NestedConfigurationProperty
private final Cache cache = new Cache();
@NestedConfigurationProperty
private final Generator generator = new Generator();
@NestedConfigurationProperty
private final Analytics analytics = new Analytics();
public Banner getBanner() {
return banner;
}
public Cache getCache() {
return cache;
}
public Generator getGenerator() {
return generator;
}
public Analytics getAnalytics() {
return analytics;
}
/** {@code banner.enabled} / {@code banner.text} — a site-wide chrome banner (text is verbatim/multi-line). */
public static class Banner {
private boolean enabled = true;
private String text = "";
public boolean isEnabled() {
return enabled;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = (text == null) ? "" : text;
}
}
/** {@code cache.max-entries} — a platform tuning knob (int, range-checked by the console form). */
public static class Cache {
private int maxEntries = 500;
public int getMaxEntries() {
return maxEntries;
}
public void setMaxEntries(int maxEntries) {
this.maxEntries = maxEntries;
}
}
/** {@code generator.label} — the value emitted in the {@code <meta name="generator">} head tag. */
public static class Generator {
private String label = "Runway Demo";
public String getLabel() {
return label;
}
public void setLabel(String label) {
this.label = (label == null || label.isBlank()) ? "Runway Demo" : label;
}
}
/** {@code analytics.write-key} — a {@code secret}; opaque ENC(...) ciphertext in the property map. */
public static class Analytics {
private String writeKey = "";
public String getWriteKey() {
return writeKey;
}
public void setWriteKey(String writeKey) {
this.writeKey = (writeKey == null) ? "" : writeKey;
}
public boolean hasKey() {
return !writeKey.isBlank();
}
}
}
@@ -0,0 +1,309 @@
package mx.quest.demo;
import java.io.UncheckedIOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import mx.quest.runway.spi.RunwaySpi;
import mx.quest.runway.spi.model.CatalogEntry;
import mx.quest.runway.spi.model.Finding;
import mx.quest.runway.spi.model.InstallResult;
import mx.quest.runway.spi.model.PluginInfo;
import mx.quest.runway.spi.model.SiteView;
import mx.quest.runway.spi.model.StarterPage;
import mx.quest.runway.spi.service.AccessCheck;
import mx.quest.runway.spi.service.ConsoleScreen;
import mx.quest.runway.spi.service.ContentCatalogView;
import mx.quest.runway.spi.service.Messages;
import mx.quest.runway.spi.service.RequestContext;
import mx.quest.runway.spi.service.SitePages;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.server.ResponseStatusException;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
/**
* The demo's own screen inside the tenant console, {@value #BASE} — a {@code @Controller} annotated
* {@link ConsoleScreen}. <b>When to use {@code @ConsoleScreen}:</b> whenever a plugin needs more than the settings form
* and the admin fragment below it — a list to manage, an action to run. The kernel fills the console shell (topbar,
* menus, language switcher, footer) for every request this class handles, so the plugin needs no
* {@code @ControllerAdvice} and no host class. A handler sets {@link ConsoleScreen#CONTENT_TEMPLATE} and
* {@link ConsoleScreen#PAGE_TITLE_KEY} and returns {@link ConsoleScreen#LAYOUT_VIEW}.
*
* <p><b>The rules this class follows:</b>
* <ul>
* <li>Every mapping lies under {@code /__admin/runway-demo} (the kernel refuses a plugin controller elsewhere), so
* the tenant console's sign-in, realm security and CSRF protection apply unchanged.</li>
* <li>Every handler is gated with {@code @PreAuthorize("@authz.may('runway-demo|manage-notes')")} — the
* {@link AccessCheck} bean under its expression name. The menu entry's {@code permission:} only hides the
* link.</li>
* <li>Everything that <b>changes state is a {@code POST}</b> from a form carrying the console's CSRF token
* ({@code ${_csrf}}); the {@code GET} only reads, so a link or an {@code <img>} on another web site can never
* trigger an action through a signed-in operator's browser. Each {@code POST} redirects back (post/redirect/get)
* with a flash message, so a reload never repeats it. Spring MVC binds the form fields, so no SPI type is
* needed to read them.</li>
* </ul>
*
* <p>It is also where four services are used in their natural place:
* <ul>
* <li>{@link RequestContext#site()} — <b>which site this console request manages</b>. A console screen has no
* {@code RouteRequest}; this is how it learns the tenancy. It is empty on the application console
* ({@code /__app}), which this screen does not serve (404).</li>
* <li>{@link Messages#console} — console text in the <b>operator's</b> UI language (the flash messages), as opposed
* to {@link Messages#site}, which is for what a site's visitors read.</li>
* <li>{@link SitePages#install} — "install my starter page" through the site's editorial rules: never overwrites,
* never publishes around an Enforced or Reviewed site, and reports one of four outcomes the operator is told in
* words. The plugin checks the caller may edit pages first ({@link AccessCheck#may} with the kernel permission
* {@code EDIT_PAGES}).</li>
* <li>{@link ContentCatalogView} — <b>the site's published content surface</b> with the URLs the host computed:
* {@code entries} (what a sitemap or search index lists), {@code pageAt} (which published page owns a path),
* {@code servablePath} (may content live at a path at all) and {@code refresh} (a manual reindex).</li>
* </ul>
*/
@Controller
@ConsoleScreen
@RequestMapping(DemoConsoleController.BASE)
public class DemoConsoleController {
static final String BASE = "/__admin/runway-demo";
static final String GATE = "@authz.may('runway-demo|manage-notes')";
static final String CONTENT = "__plugin__/runway-demo/console";
static final String TITLE_KEY = "runwaydemo.console.title";
/** The starter page's slug and path. */
static final String STARTER_SLUG = "runway-demo";
static final String STARTER_PATH = "/demo";
/** The flash attributes this screen renders itself (the shell's own flash region is not promised to plugins). */
static final String FLASH = "runwayDemoFlash";
static final String FLASH_ERROR = "runwayDemoError";
/** The most catalog rows the screen lists. */
static final int CATALOG_ROWS = 50;
private static final Logger log = LoggerFactory.getLogger(DemoConsoleController.class);
/** One row of the content-surface table. */
public record CatalogRow(String source, String id, String path, boolean own) {
}
/** The answer of the path check: servable at all, and the published page that owns it, if any. */
public record PathCheck(String path, boolean safe, boolean servable, String ownerSlug) {
}
/** Everything the screen shows, built per request. */
public record Screen(SiteView site, String pluginVersion, String builtSpi, String runningSpi,
int noteCount, List<Note> notes, String showcaseText, String showcasePath,
String starterPath, int catalogTotal, List<CatalogRow> catalog,
List<DemoActivity.Entry> activity, PathCheck pathCheck) {
}
private final RequestContext request;
private final AccessCheck access;
private final Messages messages;
private final SitePages pages;
private final ContentCatalogView catalog;
private final DemoNotesStore notes;
private final DemoShowcaseStore showcase;
private final DemoActivity activity;
private final PluginInfo self;
public DemoConsoleController(RequestContext request, AccessCheck access, Messages messages, SitePages pages,
ContentCatalogView catalog, DemoNotesStore notes, DemoShowcaseStore showcase,
DemoActivity activity, PluginInfo self) {
this.request = request;
this.access = access;
this.messages = messages;
this.pages = pages;
this.catalog = catalog;
this.notes = notes;
this.showcase = showcase;
this.activity = activity;
this.self = self;
}
/** The screen. Read-only: it changes nothing, so it is a {@code GET}. {@code ?path=} runs the path check. */
@GetMapping
@PreAuthorize(GATE)
public String screen(@RequestParam(name = "path", required = false) String path, Model model) {
SiteView site = boundSite();
String siteId = site.id();
List<CatalogEntry> entries = catalog.entries(siteId);
List<CatalogRow> rows = new ArrayList<>();
for (CatalogEntry entry : entries.subList(0, Math.min(CATALOG_ROWS, entries.size()))) {
rows.add(new CatalogRow(entry.sourceKey(), entry.ref().id(), entry.pathFor(site.defaultLocale()),
DemoShowcaseSource.SOURCE_KEY.equals(entry.sourceKey())));
}
Optional<Showcase> current = showcase.current(siteId);
model.addAttribute("rd", new Screen(site, self.version(), RunwaySpi.VERSION,
RunwaySpi.runtimeVersion(), notes.count(siteId), notes.recent(siteId, 10),
current.map(Showcase::text).orElse(null), DemoShowcaseSource.PATH,
pages.pathOf(siteId, STARTER_SLUG).orElse(""), entries.size(), rows, activity.recent(siteId),
path == null || path.isBlank() ? null : check(site, path.strip())));
model.addAttribute(ConsoleScreen.CONTENT_TEMPLATE, CONTENT);
model.addAttribute(ConsoleScreen.PAGE_TITLE_KEY, TITLE_KEY);
return ConsoleScreen.LAYOUT_VIEW;
}
private PathCheck check(SiteView site, String path) {
try {
boolean servable = catalog.servablePath(site.id(), path);
String owner = catalog.pageAt(site.id(), path, site.defaultLocale()).orElse(null);
return new PathCheck(path, true, servable, owner);
} catch (IllegalArgumentException unsafe) {
return new PathCheck(path, false, false, null);
}
}
/** Adds an operator note (a field of the form body). */
@PostMapping("/notes")
@PreAuthorize(GATE)
public String addNote(@RequestParam(name = "text", defaultValue = "") String text, RedirectAttributes flash) {
String siteId = boundSite().id();
if (text.isBlank()) {
return back(flash, FLASH_ERROR, console("runwaydemo.console.note.blank", "Write something first."));
}
try {
notes.append(siteId, text, Note.ORIGIN_CONSOLE);
} catch (UncheckedIOException e) {
log.warn("runway-demo could not add a note for site {}: {}", siteId, e.toString());
return back(flash, FLASH_ERROR, console("runwaydemo.console.ioError", "The change could not be saved."));
}
return back(flash, FLASH, console("runwaydemo.console.note.added", "Note added."));
}
/** Publishes the showcase page; the store announces the change with {@code ContentChanges}. */
@PostMapping("/showcase")
@PreAuthorize(GATE)
public String publishShowcase(@RequestParam(name = "text", defaultValue = "") String text,
RedirectAttributes flash) {
String siteId = boundSite().id();
if (text.isBlank()) {
return back(flash, FLASH_ERROR, console("runwaydemo.console.showcase.blank", "Write something first."));
}
try {
showcase.publish(siteId, text);
} catch (UncheckedIOException e) {
log.warn("runway-demo could not publish the showcase of site {}: {}", siteId, e.toString());
return back(flash, FLASH_ERROR, console("runwaydemo.console.ioError", "The change could not be saved."));
}
return back(flash, FLASH, console("runwaydemo.console.showcase.published", "Showcase published at {0}.",
DemoShowcaseSource.PATH));
}
/** Unpublishes the showcase page; announced like a publish. */
@PostMapping("/showcase/unpublish")
@PreAuthorize(GATE)
public String unpublishShowcase(RedirectAttributes flash) {
String siteId = boundSite().id();
boolean was;
try {
was = showcase.unpublish(siteId);
} catch (UncheckedIOException e) {
log.warn("runway-demo could not unpublish the showcase of site {}: {}", siteId, e.toString());
return back(flash, FLASH_ERROR, console("runwaydemo.console.ioError", "The change could not be saved."));
}
return was
? back(flash, FLASH, console("runwaydemo.console.showcase.unpublished", "Showcase unpublished."))
: back(flash, FLASH, console("runwaydemo.console.showcase.none", "No showcase was published."));
}
/** Installs the starter page carrying the demo's two widgets, through the site's editorial rules. */
@PostMapping("/install-page")
@PreAuthorize(GATE)
public String installPage(RedirectAttributes flash) {
SiteView site = boundSite();
if (!access.may("EDIT_PAGES")) {
return back(flash, FLASH_ERROR, console("runwaydemo.console.page.forbidden",
"Installing a page needs the permission to edit pages."));
}
String title = messages.site(site.id(), site.defaultLocale(), "runwaydemo.page.title", "Runway demo");
StarterPage page = new StarterPage(STARTER_SLUG, STARTER_PATH,
Map.of(site.defaultLocale().getLanguage(), title), starterHtml(title), starterLogic(), true);
InstallResult result;
try {
result = pages.install(site.id(), page);
} catch (RuntimeException e) {
// IllegalStateException: another page serves the path, the master is missing, a write failed (no stray
// draft is left behind). IllegalArgumentException would mean our own slug/path is unsafe — a bug here.
log.warn("runway-demo starter page install failed for site {}: {}", site.id(), e.toString());
return back(flash, FLASH_ERROR, console("runwaydemo.console.page.failed",
"The demo page could not be installed."));
}
return back(flash, FLASH, describe(result));
}
/** Drops the site's cached content listing — the "reindex" button; ordinary changes never need it. */
@PostMapping("/catalog/refresh")
@PreAuthorize(GATE)
public String refreshCatalog(RedirectAttributes flash) {
catalog.refresh(boundSite().id());
return back(flash, FLASH, console("runwaydemo.console.catalog.refreshed", "Content listing refreshed."));
}
/** The operator's words for each install outcome; an outcome added in a later SPI MINOR gets a neutral line. */
String describe(InstallResult result) {
String path = result.path();
return switch (result.outcome()) {
case PUBLISHED -> console("runwaydemo.console.page.published", "Demo page published at {0}.", path);
case PENDING_REVIEW -> console("runwaydemo.console.page.pending",
"Demo page created at {0} and waiting in the review queue.", path);
case DRAFT_BLOCKED -> {
StringBuilder text = new StringBuilder(console("runwaydemo.console.page.blocked",
"Demo page created at {0} as a draft: the quality checks blocked publishing.", path));
for (Finding finding : result.blocking()) {
text.append(' ').append(finding.code()).append(": ").append(finding.message());
}
yield text.toString();
}
case ALREADY_EXISTS -> console("runwaydemo.console.page.exists",
"A demo page already exists at {0}; nothing changed.", path);
default -> console("runwaydemo.console.page.other", "Demo page install finished: {0} {1}",
result.outcome(), path);
};
}
/** The site this console request manages; 404 when there is none (the application console). */
private SiteView boundSite() {
return request.site().orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND));
}
private String console(String code, String fallback, Object... args) {
return messages.console(code, fallback, args);
}
private static String back(RedirectAttributes flash, String kind, String text) {
flash.addFlashAttribute(kind, text);
return "redirect:" + BASE;
}
/**
* The starter page: the master's chrome seams, a heading, and the two widget anchors (an {@code id} and a
* {@code data-widget} on one element each). An {@code <h1>} keeps the page clear of the demo's own quality check.
*/
static String starterHtml(String title) {
String t = Html.escape(title);
return "<!DOCTYPE html>\n<html>\n<head><title>" + t + "</title></head>\n<body>\n"
+ "<header id=\"site-header\"></header>\n<main id=\"content\">\n"
+ " <h1 id=\"demo-page-title\">" + t + "</h1>\n"
+ " <div id=\"demo-notice\" data-widget=\"demo-notice/page\"></div>\n"
+ " <div id=\"demo-feedback\" data-widget=\"demo-feedback/page\"></div>\n"
+ "</main>\n<footer id=\"site-footer\"></footer>\n</body>\n</html>\n";
}
/** The starter page's decoupled logic: the master's chrome by the {@code ${master}} variable, never a literal. */
static String starterLogic() {
return "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<thlogic>\n"
+ " <attr sel=\"head\" th:replace=\"~{${master} :: head}\"/>\n"
+ " <attr sel=\"#site-header\" th:replace=\"~{${master} :: #site-header}\"/>\n"
+ " <attr sel=\"#site-footer\" th:replace=\"~{${master} :: #site-footer}\"/>\n"
+ " <attr sel=\"#demo-page-title\" th:text=\"${pageTitle}\"/>\n"
+ "</thlogic>\n";
}
}
@@ -0,0 +1,233 @@
package mx.quest.demo;
import java.nio.charset.StandardCharsets;
import java.util.ArrayDeque;
import java.util.Deque;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.TimeUnit;
import java.util.function.LongSupplier;
import mx.quest.runway.spi.EndpointContributor;
import mx.quest.runway.spi.model.Capabilities;
import mx.quest.runway.spi.model.Realm;
import mx.quest.runway.spi.model.Route;
import mx.quest.runway.spi.model.RouteRequest;
import mx.quest.runway.spi.model.RouteResponse;
import mx.quest.runway.spi.model.SurfacePosture;
import mx.quest.runway.spi.service.AccessCheck;
import mx.quest.runway.spi.service.Messages;
import mx.quest.runway.spi.service.PluginSettings;
import tools.jackson.databind.json.JsonMapper;
/**
* {@code EndpointContributor} — plugin HTTP routes on a site's public host, without touching a servlet. The frozen
* {@link RouteRequest} carries the resolved site, the negotiated locale, the query, the form body, lowercase headers,
* the gated client IP and the request origin; each route declares a {@link SurfacePosture}. Routes are exact paths
* on the tenant realm and must avoid the reserved kernel prefixes ({@code /__…}, {@code /login}, …).
*
* <ul>
* <li>{@code GET /demo/hello.txt} — public, {@code discoverable()}: a greeting localized with
* {@link Messages#site} in the request's negotiated locale.</li>
* <li>{@code GET /demo/echo.json} — public: echoes what the host put in the {@code RouteRequest}.</li>
* <li>{@code GET /demo/notes.json} — <b>permission-gated</b> with {@link AccessCheck}: only a signed-in user holding
* {@code runway-demo|manage-notes} gets the notes; anyone else gets {@code 403}. <b>When to use
* {@code AccessCheck}:</b> every time your code must decide whether the current user may do something — the
* menu and dashboard-card {@code permission:} keys only hide UI. It is fail-closed (no request, no principal,
* an undeclared key → {@code false}) and is the same bean as {@code @authz} in {@code @PreAuthorize} and
* templates.</li>
* <li>{@code POST /demo/feedback} — an <b>anonymous form route</b> ({@link Route#anonymousPost}): the public
* feedback form of {@link DemoFeedbackWidget} posts here with <b>no CSRF token</b>. <b>When to use the
* anonymous flag:</b> only for a form any visitor may submit with no account, placed on a page every visitor
* shares, which therefore cannot carry a per-session token (a contact form, a newsletter sign-up). The kernel
* exempts exactly this method and path from CSRF and makes that safe by running the handler with <b>no
* principal</b> ({@code AccessCheck.may} is {@code false} even for a signed-in administrator) and accepting only
* an {@code application/x-www-form-urlencoded} body. Keep your own abuse guards: here a honeypot field, a length
* cap and a per-address rate limit keyed by {@link RouteRequest#clientIp()} (the address after the kernel's
* trusted-proxy gate — never a header). Never use the flag for an action on something a signed-in user owns;
* those are CSRF-checked {@code POST}s (the demo's console screen, {@link DemoConsoleController}).</li>
* </ul>
*/
public class DemoEndpoints implements EndpointContributor {
static final String HELLO_PATH = "/demo/hello.txt";
static final String ECHO_PATH = "/demo/echo.json";
static final String NOTES_PATH = "/demo/notes.json";
static final String FEEDBACK_PATH = "/demo/feedback";
static final String PERMISSION = "runway-demo|manage-notes";
/** Feedback messages one client address may send per {@link #WINDOW_MILLIS}. */
static final int FEEDBACK_PER_WINDOW = 5;
static final long WINDOW_MILLIS = TimeUnit.MINUTES.toMillis(1);
/** Above this many tracked addresses, stale ones are swept (bounds the limiter's memory). */
private static final int MAX_TRACKED = 10_000;
private final AccessCheck access;
private final DemoNotesStore notes;
private final Messages messages;
private final PluginSettings settings;
private final LongSupplier clockMillis;
private final JsonMapper json = JsonMapper.builder().build();
private final ConcurrentMap<String, Deque<Long>> recentFeedback = new ConcurrentHashMap<>();
public DemoEndpoints(AccessCheck access, DemoNotesStore notes, Messages messages, PluginSettings settings) {
this(access, notes, messages, settings, System::currentTimeMillis);
}
DemoEndpoints(AccessCheck access, DemoNotesStore notes, Messages messages, PluginSettings settings,
LongSupplier clockMillis) {
this.access = access;
this.notes = notes;
this.messages = messages;
this.settings = settings;
this.clockMillis = clockMillis;
}
@Override
public String key() {
return "runway-demo/endpoints";
}
@Override
public List<Route> routes() {
return List.of(
new Route("GET", HELLO_PATH, Realm.TENANT, SurfacePosture.discoverable()),
new Route("GET", ECHO_PATH, Realm.TENANT, SurfacePosture.safeDefault()),
new Route("GET", NOTES_PATH, Realm.TENANT, SurfacePosture.safeDefault()),
Route.anonymousPost(FEEDBACK_PATH, SurfacePosture.safeDefault()));
}
@Override
public RouteResponse handle(RouteRequest req) {
// The kernel dispatches by method + path; checking the method again is the second line of defence.
return switch (req.method().toUpperCase(Locale.ROOT) + " " + req.path()) {
case "GET " + HELLO_PATH -> hello(req);
case "GET " + ECHO_PATH -> echo(req);
case "GET " + NOTES_PATH -> notes(req);
case "POST " + FEEDBACK_PATH -> feedback(req);
default -> RouteResponse.notFound();
};
}
private RouteResponse hello(RouteRequest req) {
String greeting = messages.site(req.site().id(), req.locale(), "runwaydemo.hello",
"Hello from the runway-demo plugin!") + "\n"
+ "site: " + req.site().displayName() + " (" + req.site().id() + ")\n"
+ "locale: " + req.locale().toLanguageTag() + "\n"
+ "baseUrl: " + (req.site().baseUrl() == null ? "(derived)" : req.site().baseUrl()) + "\n"
+ "origin: " + (req.origin().isEmpty() ? "(unknown)" : req.origin()) + "\n";
return RouteResponse.text(200, greeting);
}
private RouteResponse echo(RouteRequest req) {
Map<String, Object> payload = new LinkedHashMap<>();
payload.put("method", req.method());
payload.put("path", req.path());
payload.put("site", req.site().id());
payload.put("locale", req.locale().toLanguageTag()); // negotiated: ?lang → cookie → Accept-Language → default
payload.put("query", req.query()); // the URL query string only
payload.put("form", req.form()); // a url-encoded body's fields (empty on a GET)
payload.put("param.q", req.param("q").orElse(null)); // query first, then form
payload.put("headers", req.headers()); // lowercase names; no X-Forwarded-* ever
payload.put("clientIp", req.clientIp()); // after the trusted-proxy gate; null when unknown
payload.put("origin", req.origin()); // scheme://host[:port]; "" when unknown
return jsonResponse(200, payload);
}
private RouteResponse notes(RouteRequest req) {
if (!access.may(PERMISSION)) {
return RouteResponse.text(403, "Forbidden — requires the runway-demo \"manage-notes\" permission.\n");
}
List<Note> siteNotes = notes.list(req.site().id());
Map<String, Object> payload = new LinkedHashMap<>();
payload.put("site", req.site().id());
payload.put("count", siteNotes.size());
payload.put("notes", siteNotes);
return jsonResponse(200, payload);
}
/**
* Keeps a visitor's message as a note, then answers {@code 303} back to the form's page with an outcome flag
* (never a submitted value). Fields are read from the form <b>body</b> only, so personal text never has to
* travel in a URL. A failure to store propagates: the kernel answers {@code 500}, logs and counts it.
*/
private RouteResponse feedback(RouteRequest req) {
String siteId = req.site().id();
if (!settings.site(siteId).bool("feedback.enabled", true)) {
return RouteResponse.notFound();
}
String back = safeLocalPath(formField(req, "return"));
if (!formField(req, "website").isEmpty()) {
return redirect(back, "thanks"); // a bot filled the honeypot: pretend success, keep nothing
}
String message = formField(req, "message");
if (message.isEmpty()) {
return redirect(back, "invalid");
}
if (!allow(req.clientIp())) {
return redirect(back, "limited");
}
notes.append(siteId, message, Note.ORIGIN_VISITOR);
return redirect(back, "thanks");
}
/** A sliding-window limit per gated client address; an unknown address shares one bucket (fail-safe). */
boolean allow(String clientIp) {
long now = clockMillis.getAsLong();
if (recentFeedback.size() > MAX_TRACKED) {
recentFeedback.entrySet().removeIf(e -> {
synchronized (e.getValue()) {
return e.getValue().isEmpty() || now - e.getValue().peekLast() >= WINDOW_MILLIS;
}
});
}
Deque<Long> times = recentFeedback.computeIfAbsent(clientIp == null ? "unknown" : clientIp,
k -> new ArrayDeque<>());
synchronized (times) {
while (!times.isEmpty() && now - times.peekFirst() >= WINDOW_MILLIS) {
times.pollFirst();
}
if (times.size() >= FEEDBACK_PER_WINDOW) {
return false;
}
times.addLast(now);
return true;
}
}
private static String formField(RouteRequest req, String name) {
List<String> values = req.form().get(name);
return values == null || values.isEmpty() ? "" : values.get(0).strip();
}
/** A same-origin local path (one leading "/", no scheme, backslash, whitespace or control character), else "/". */
static String safeLocalPath(String path) {
if (path == null || !path.startsWith("/") || path.startsWith("//") || path.contains("://")) {
return "/";
}
for (int i = 0; i < path.length(); i++) {
char c = path.charAt(i);
if (c <= 0x20 || c == '\\' || c == 0x7f) {
return "/";
}
}
return path;
}
private static RouteResponse redirect(String path, String outcome) {
String location = path + (path.contains("?") ? "&" : "?") + DemoFeedbackWidget.OUTCOME_PARAM + "=" + outcome;
return new RouteResponse(303, Map.of("Location", location), new byte[0]);
}
private RouteResponse jsonResponse(int status, Object payload) {
byte[] body = json.writeValueAsString(payload).getBytes(StandardCharsets.UTF_8);
return new RouteResponse(status, Map.of("Content-Type", "application/json; charset=utf-8"), body);
}
@Override
public Capabilities capabilities() {
return Capabilities.of("endpoint.tenant", "endpoint.json", "endpoint.anonymous-form");
}
}
@@ -0,0 +1,98 @@
package mx.quest.demo;
import java.util.Locale;
import mx.quest.runway.spi.ContentWidget;
import mx.quest.runway.spi.model.Capabilities;
import mx.quest.runway.spi.model.RenderFragment;
import mx.quest.runway.spi.model.WidgetView;
import mx.quest.runway.spi.service.Messages;
import mx.quest.runway.spi.service.PluginSettings;
/**
* {@code ContentWidget} — a public "leave a message" form at a {@code data-widget="demo-feedback/<instance>"} anchor.
* It posts to the demo's <b>anonymous</b> route {@code POST /demo/feedback} ({@link DemoEndpoints}), which stores the
* message as a note and answers {@code 303} back to this page with a {@code ?demo-feedback=<outcome>} flag; the widget
* reads that flag from {@link WidgetView#query()} and shows the outcome (post/redirect/get, so a reload never
* resubmits).
*
* <p>The form carries <b>no CSRF token</b> on purpose: it sits on a page every visitor shares (and caches), and an
* anonymous visitor has no session. That is exactly the case the anonymous-route flag exists for — see
* {@link DemoEndpoints}. Its abuse guards are a honeypot field (hidden from people, filled by naive bots), a length
* cap and a per-address rate limit on the server.
*
* <p>A widget stays a pure function of its view: it only <i>reads</i> the query; storing the message is the
* endpoint's job. All text comes from {@link Messages#site} in the visitor's locale and is escaped here.
*/
public class DemoFeedbackWidget implements ContentWidget {
/** The query flag the endpoint redirects back with. */
static final String OUTCOME_PARAM = "demo-feedback";
private final PluginSettings settings;
private final Messages messages;
public DemoFeedbackWidget(PluginSettings settings, Messages messages) {
this.settings = settings;
this.messages = messages;
}
@Override
public String key() {
return "demo-feedback";
}
@Override
public RenderFragment render(WidgetView view) {
String siteId = view.site().id();
if (!settings.site(siteId).bool("feedback.enabled", true)) {
return RenderFragment.empty();
}
Locale locale = view.locale();
String fieldId = "rw-demo-feedback-" + view.instanceId().replaceAll("[^A-Za-z0-9_-]", "-");
String back = view.path().isBlank() ? "/" : view.path();
StringBuilder html = new StringBuilder()
.append("<link rel=\"stylesheet\" href=\"/__plugin/runway-demo/static/css/demo.css\">")
.append("<div class=\"rw-demo-feedback\">");
String outcome = outcomeText(siteId, locale, view.query().get(OUTCOME_PARAM));
if (!outcome.isEmpty()) {
html.append("<p class=\"rw-demo-notice rw-demo-notice-info\" role=\"status\">")
.append(Html.escape(outcome)).append("</p>");
}
html.append("<form method=\"post\" action=\"").append(DemoEndpoints.FEEDBACK_PATH).append("\">")
.append("<input type=\"hidden\" name=\"return\" value=\"").append(Html.escape(back)).append("\">")
.append("<label for=\"").append(fieldId).append("\">")
.append(Html.escape(text(siteId, locale, "runwaydemo.feedback.label", "Leave a message")))
.append("</label>")
.append("<textarea id=\"").append(fieldId).append("\" name=\"message\" rows=\"3\" maxlength=\"")
.append(DemoNotesStore.MAX_TEXT).append("\" required></textarea>")
// The honeypot: off-screen for people and assistive technology, tempting for a form-filling bot.
.append("<div class=\"rw-demo-hp\" aria-hidden=\"true\"><label>Website <input type=\"text\" ")
.append("name=\"website\" tabindex=\"-1\" autocomplete=\"off\"></label></div>")
.append("<button type=\"submit\">")
.append(Html.escape(text(siteId, locale, "runwaydemo.feedback.send", "Send")))
.append("</button></form></div>");
return RenderFragment.of(html.toString());
}
private String outcomeText(String siteId, Locale locale, String outcome) {
if (outcome == null) {
return "";
}
return switch (outcome) {
case "thanks" -> text(siteId, locale, "runwaydemo.feedback.thanks", "Thank you — your message was kept.");
case "invalid" -> text(siteId, locale, "runwaydemo.feedback.invalid", "Please write a message first.");
case "limited" -> text(siteId, locale, "runwaydemo.feedback.limited",
"Too many messages from your address — please try again in a minute.");
default -> "";
};
}
private String text(String siteId, Locale locale, String code, String fallback) {
return messages.site(siteId, locale, code, fallback);
}
@Override
public Capabilities capabilities() {
return Capabilities.of("widget.form");
}
}
@@ -0,0 +1,44 @@
package mx.quest.demo;
import mx.quest.runway.spi.RunwaySpi;
import mx.quest.runway.spi.model.PluginInfo;
import mx.quest.runway.spi.service.PluginLifecycle;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* {@code PluginLifecycle} — the optional start/stop hook. <b>When to use it:</b> to run code once the platform is up
* (warm a cache, open an index, start your own executor) or when it shuts down (close what you opened). A plugin that
* only contributes beans needs none.
*
* <p>The host collects every {@code PluginLifecycle} bean by type and matches it to its plugin by the jar its class was
* loaded from — there is no {@code id()} to keep in sync with {@code plugin.yml}. {@link #started} runs once, after
* every singleton exists, in plugin load order; {@link #stopping} runs at shutdown in reverse order, only if
* {@code started} returned normally. Both block the host's startup/shutdown thread, so keep them short; a throw is
* logged and counted on the plugins screen and the platform keeps booting.
*
* <p>{@link PluginInfo} is this plugin's own identity — its id, the version from {@code plugin.yml} and its install
* folder. It arrives here and can also be injected into any bean.
*
* <p>{@link RunwaySpi#VERSION} is a compile-time constant, so in plugin code it is the SPI version the plugin was
* <b>built against</b>; {@link RunwaySpi#runtimeVersion()} is the SPI of the kernel it is <b>running on</b>.
*/
public class DemoLifecycle implements PluginLifecycle {
private static final Logger log = LoggerFactory.getLogger(DemoLifecycle.class);
private volatile PluginInfo self;
@Override
public void started(PluginInfo self) {
this.self = self;
log.info("{} {} started — install dir {}; built against SPI {}, running on SPI {}", self.id(),
self.version(), self.installDir(), RunwaySpi.VERSION, RunwaySpi.runtimeVersion());
}
@Override
public void stopping() {
PluginInfo info = self;
log.info("{} stopping", info == null ? "runway-demo" : info.id());
}
}
@@ -0,0 +1,70 @@
package mx.quest.demo;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import mx.quest.runway.spi.PageQualityCheck;
import mx.quest.runway.spi.model.Capabilities;
import mx.quest.runway.spi.model.Finding;
import mx.quest.runway.spi.model.PageView;
import mx.quest.runway.spi.model.SettingsView;
import mx.quest.runway.spi.service.PluginSettings;
/**
* {@code PageQualityCheck} — read-only SEO checks over a page as it would render. Tuned per site through
* {@link PluginSettings}: {@code quality.title-warn-ratio} (a {@code decimal}) scales the 60-character title threshold;
* {@code quality.ignore-codes} (a {@code list}) suppresses finding codes. Returns an empty list (never {@code null})
* for a clean page.
*
* <p>Severity is a decision with consequences: on a site set to <i>Enforced</i> or <i>Reviewed</i> any {@code ERROR}
* refuses publishing. This demo's {@code h1.missing} is an {@code ERROR} on purpose, to show that path; a real plugin
* keeps {@code ERROR} for something clearly broken and uses {@code WARNING} for advice.
*/
public class DemoMetaLengthCheck implements PageQualityCheck {
private static final int BASE_TITLE_LIMIT = 60;
private final PluginSettings settings;
public DemoMetaLengthCheck(PluginSettings settings) {
this.settings = settings;
}
@Override
public String key() {
return "runway-demo/meta-length";
}
@Override
public List<Finding> inspect(PageView page) {
SettingsView site = settings.site(page.site().id());
double ratio = site.decimal("quality.title-warn-ratio", BigDecimal.ONE).doubleValue();
int titleLimit = (int) Math.max(1, Math.round(BASE_TITLE_LIMIT * ratio));
List<String> ignore = site.list("quality.ignore-codes");
List<Finding> findings = new ArrayList<>();
String title = page.page().title();
if (title != null && title.length() > titleLimit) {
findings.add(Finding.warning("title.too-long",
"Title is " + title.length() + " chars; keep it under " + titleLimit + " for search results."));
}
if (page.page().description() == null || page.page().description().isBlank()) {
findings.add(Finding.info("description.missing",
"This page has no meta description; add one for better search snippets."));
}
if (!hasH1(page.resolvedHtml())) {
findings.add(Finding.error("h1.missing", "The rendered page has no <h1> heading."));
}
return findings.stream().filter(f -> !ignore.contains(f.code())).toList();
}
private static boolean hasH1(String html) {
return html != null && html.toLowerCase(Locale.ROOT).contains("<h1");
}
@Override
public Capabilities capabilities() {
return Capabilities.of("quality.seo");
}
}
@@ -0,0 +1,168 @@
package mx.quest.demo;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.time.Instant;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import mx.quest.runway.spi.service.PluginSiteFiles;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import tools.jackson.core.JacksonException;
import tools.jackson.databind.DeserializationFeature;
import tools.jackson.dataformat.yaml.YAMLMapper;
/**
* The demo's per-site "sticky notes" — data the plugin <b>generates for a site</b>, kept in the plugin's own per-site
* folder through the kernel's {@link PluginSiteFiles}: {@value #FILE} under {@code sites/<id>/plugins/runway-demo/}.
*
* <p><b>When to use {@code PluginSiteFiles}.</b> For anything your plugin stores per site. The folder lives inside the
* site's folder, so a full backup carries it, a deleted site takes it along, and nobody else's code can reach it — no
* {@code BackupParticipant} is needed (1.x kept the notes outside the site folder and needed one; 2.0.0 does not).
* The service is bound to <i>this</i> plugin by the jar the injecting class came from, so no method takes a plugin id.
*
* <p><b>Personal data.</b> The notes hold what people typed — an operator's notes from the console and a visitor's
* message from the public feedback form — so {@code plugin.yml} declares {@value #FILE} under
* {@code siteData.personal}: a transfer copy of the site leaves it out. Rule of thumb: any file holding visitor or
* user input is personal.
*
* <p><b>Concurrency.</b> Each kernel write is atomic (readers never see half a file), but an append is a
* read-modify-write, which the service leaves to the plugin: it is serialized here per site. The file is bounded to
* the newest {@value #MAX_NOTES} notes, far below the kernel's per-write cap.
*
* <p><b>A {@code GET} never writes.</b> A site with no notes yet shows a welcome note, but the welcome is not stored
* until something else is: the first {@link #append} (a console note, a visitor's message, the settings audit note)
* writes the welcome and the new note together, so the note an operator saw stays in the list. Until then the site
* has no {@value #FILE} at all. Reads ({@link #list}, {@link #count}, {@link #recent}) never create a file — opening
* a console screen or the settings page must not change a site.
*
* <p><b>Failure.</b> A read failure during {@link #append} aborts the append (rewriting the file from nothing would
* lose every note); the console reads ({@link #list}, {@link #count}) degrade to empty with a warning, so an
* unreadable file never takes a console screen down. The YAML goes through the plugin's own Jackson (a platform
* library), lenient about keys it does not know, so a later version can add fields without breaking this one.
*/
public class DemoNotesStore {
/** The notes file, relative to the plugin's per-site folder; declared personal in {@code plugin.yml}. */
static final String FILE = "notes.yml";
/** The most notes a site keeps (the oldest are dropped). */
static final int MAX_NOTES = 200;
/** The longest note text kept, in characters. */
static final int MAX_TEXT = 1000;
/**
* The welcome note's fixed id (never one {@code newId} makes), so the welcome a site shows is the note its first
* write keeps.
*/
static final String WELCOME_ID = "welcome";
private static final Logger log = LoggerFactory.getLogger(DemoNotesStore.class);
private final PluginSiteFiles files;
private final YAMLMapper yaml = YAMLMapper.builder()
.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)
.build();
private final ConcurrentMap<String, Object> locks = new ConcurrentHashMap<>();
public DemoNotesStore(PluginSiteFiles files) {
this.files = files;
}
private Object lockFor(String siteId) {
return locks.computeIfAbsent(siteId, k -> new Object());
}
/**
* The site's notes, oldest first. A site with no notes yet reads as the one {@linkplain #welcome() welcome note},
* which is <b>not written</b> (see the class comment). Empty, with a warning, when the file cannot be read.
*/
public List<Note> list(String siteId) {
synchronized (lockFor(siteId)) {
NotesFile file;
try {
file = read(siteId);
} catch (IOException | JacksonException e) {
log.warn("runway-demo notes of site {} could not be read: {}", siteId, e.toString());
return List.of();
}
return file.notes().isEmpty() ? List.of(welcome()) : file.notes();
}
}
/**
* The note a site with no notes shows. Its id is fixed and it has no time ({@code createdAt} is empty) while it is
* only shown; the first {@link #append} stores it with that write's time.
*/
static Note welcome() {
return new Note(WELCOME_ID, "Welcome — this note is data the runway-demo plugin keeps for this site in its "
+ "own folder; it travels in full backups and is left out of transfer copies.", "",
Note.ORIGIN_SYSTEM);
}
/**
* Appends a note (its text stripped and capped at {@value #MAX_TEXT} characters) and returns the new count. The
* first append to a site with no notes also stores the {@linkplain #welcome() welcome note}, before the new one.
*
* @param origin who wrote it: {@link Note#ORIGIN_CONSOLE}, {@link Note#ORIGIN_VISITOR} or {@link Note#ORIGIN_SYSTEM}
* @throws UncheckedIOException when the file cannot be read or written (an unreadable file is left untouched)
*/
public int append(String siteId, String text, String origin) {
String clean = text == null ? "" : text.strip();
if (clean.length() > MAX_TEXT) {
clean = clean.substring(0, MAX_TEXT);
}
synchronized (lockFor(siteId)) {
try {
List<Note> notes = new ArrayList<>(read(siteId).notes());
String now = Instant.now().toString();
if (notes.isEmpty()) {
// The first write keeps the welcome the site was showing, stamped with this write's time.
Note shown = welcome();
notes.add(new Note(shown.id(), shown.text(), now, shown.origin()));
}
notes.add(new Note(newId(), clean, now, origin));
if (notes.size() > MAX_NOTES) {
notes = new ArrayList<>(notes.subList(notes.size() - MAX_NOTES, notes.size()));
}
write(siteId, new NotesFile(notes));
return notes.size();
} catch (IOException e) {
throw new UncheckedIOException("storing a runway-demo note for site " + siteId, e);
} catch (JacksonException unparsable) {
// Jackson 3 exceptions are unchecked; an unparsable file is as unreadable as an I/O failure.
throw new UncheckedIOException("storing a runway-demo note for site " + siteId,
new IOException(unparsable));
}
}
}
/** The number of notes the site shows (1, the unsaved welcome, for a site with none yet; as {@link #list}). */
public int count(String siteId) {
return list(siteId).size();
}
/** The newest {@code limit} notes, newest first. */
public List<Note> recent(String siteId, int limit) {
List<Note> all = list(siteId);
return all.subList(Math.max(0, all.size() - limit), all.size()).reversed();
}
private NotesFile read(String siteId) throws IOException {
Optional<String> text = files.readText(siteId, FILE);
if (text.isEmpty() || text.get().isBlank()) {
return NotesFile.empty();
}
NotesFile parsed = yaml.readValue(text.get(), NotesFile.class);
return parsed == null ? NotesFile.empty() : parsed;
}
private void write(String siteId, NotesFile file) throws IOException {
files.writeText(siteId, FILE, yaml.writeValueAsString(file));
}
private static String newId() {
return "n-" + Long.toString(System.nanoTime(), 36);
}
}
@@ -0,0 +1,76 @@
package mx.quest.demo;
import java.util.Set;
import mx.quest.runway.spi.ContentWidget;
import mx.quest.runway.spi.model.Capabilities;
import mx.quest.runway.spi.model.RenderFragment;
import mx.quest.runway.spi.model.SettingsView;
import mx.quest.runway.spi.model.WidgetView;
import mx.quest.runway.spi.service.Messages;
import mx.quest.runway.spi.service.PluginSettings;
/**
* {@code ContentWidget} — renders a styled callout wherever a tenant page carries the anchor
* {@code <div id="..." data-widget="demo-notice/<instance>">} (the {@code id} AND {@code data-widget} on the same
* element). {@link #key()} {@code "demo-notice"} is the {@code <type>} half of that anchor.
*
* <p>Reads the per-site {@code notice.*} settings through {@link PluginSettings}: disabled →
* {@link RenderFragment#empty()}; {@code notice.style} picks the CSS class; {@code notice.max-chars} truncates (read
* with the clamped accessor, so a hand-edited out-of-range value can never break rendering). A chrome-scoped
* instance ({@link WidgetView#isChrome()}) shows the app-level {@code banner.text} instead.
*
* <p><b>{@code Messages.site}</b> is how visitor-facing text is localized: it resolves against the site's own bundle
* first, then every plugin's {@code i18n/} bundle, in the visitor's locale ({@code view.locale()}), and formats the
* arguments. Pure; never throws; owns its HTML escaping (the host splices the fragment unescaped).
*/
public class DemoNoticeWidget implements ContentWidget {
private static final Set<String> STYLES = Set.of("info", "warning", "danger");
private final DemoAppProps props;
private final PluginSettings settings;
private final Messages messages;
public DemoNoticeWidget(DemoAppProps props, PluginSettings settings, Messages messages) {
this.props = props;
this.settings = settings;
this.messages = messages;
}
@Override
public String key() {
return "demo-notice";
}
@Override
public RenderFragment render(WidgetView view) {
SettingsView site = settings.site(view.site().id());
if (!site.bool("notice.enabled", true)) {
return RenderFragment.empty();
}
String style = site.string("notice.style", "info");
if (!STYLES.contains(style)) {
style = "info";
}
int maxChars = (int) site.integer("notice.max-chars", 280, 1, 2000);
String body;
if (view.isChrome() && props.getBanner().isEnabled() && !props.getBanner().getText().isBlank()) {
body = props.getBanner().getText();
} else {
body = messages.site(view.site().id(), view.locale(), "runwaydemo.notice.body",
"This is the runway-demo notice widget (instance \"{0}\") on site \"{1}\".",
view.instanceId(), view.site().displayName());
}
if (body.length() > maxChars) {
body = body.substring(0, maxChars) + "…";
}
return RenderFragment.of("<div class=\"rw-demo-notice rw-demo-notice-" + style + "\" role=\"note\">"
+ Html.escape(body) + "</div>");
}
@Override
public Capabilities capabilities() {
return Capabilities.of("widget.configurable");
}
}
@@ -0,0 +1,139 @@
package mx.quest.demo;
import mx.quest.runway.spi.model.PluginInfo;
import mx.quest.runway.spi.service.AccessCheck;
import mx.quest.runway.spi.service.ContentCatalogView;
import mx.quest.runway.spi.service.ContentChanges;
import mx.quest.runway.spi.service.Messages;
import mx.quest.runway.spi.service.PluginSettings;
import mx.quest.runway.spi.service.PluginSiteFiles;
import mx.quest.runway.spi.service.RequestContext;
import mx.quest.runway.spi.service.SitePages;
import mx.quest.runway.spi.service.Sites;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
/**
* The plugin's {@code mainClass} — the single {@code @Configuration} the host registers into its context before
* refresh (as the bean {@code plugin:runway-demo}). Every bean is declared <b>explicitly</b> here; no
* {@code @ComponentScan} of the plugin's own package. The package ({@code mx.quest.demo}) lies outside
* {@code mx.quest.runway}, so the host never scans it.
*
* <h2>Everything from the kernel arrives as an SPI service</h2>
* The plugin links nothing of the host but {@code mx.quest.runway.spi} (a test proves it on the compiled classes).
* Services are ordinary Spring beans, received as {@code @Bean} method parameters:
* <ul>
* <li><b>plugin-scoped</b> — {@link PluginSettings}, {@link PluginSiteFiles}, {@link ContentChanges},
* {@link PluginInfo}: the host binds each to <i>this</i> plugin by the jar the injecting class
* ({@code DemoPluginConfig}) was loaded from. Inject them in a class of your own jar — never from a {@code lib/}
* jar, and never with a bare {@code getBean}, both of which fail at startup;</li>
* <li><b>kernel singletons</b> — {@link Sites}, {@link RequestContext}, {@link AccessCheck}, {@link Messages},
* {@link SitePages}, {@link ContentCatalogView}.</li>
* </ul>
*
* <h2>Rules the kernel checks</h2>
* <ul>
* <li><b>Bean names start with the plugin id in lowerCamelCase</b> ({@code runway-demo} → {@code runwayDemo…}):
* plugins share one bean namespace with the kernel and each other. The templates follow
* ({@code ${@runwayDemoAdminModel…}}).</li>
* <li><b>Allowed Spring surface</b>: SPI implementations, plain beans, and {@code @Controller}s mapped under
* {@code /__admin/runway-demo} or {@code /__app/runway-demo}. <b>Not allowed</b>: servlet {@code Filter}s (1.x's
* timing filter is gone — servlet filters are outside the 1.0 plugin contract), {@code SecurityFilterChain}s,
* bean (factory) post-processors, unrestricted {@code @ControllerAdvice}.</li>
* <li>Axis implementations ({@code HeadContributor}, {@code ContentWidget}, {@code EndpointContributor},
* {@code PageQualityCheck}, {@code ContentSource}) and callbacks ({@code SiteEventListener},
* {@code PluginLifecycle}) are collected <b>by type</b> — plain {@code @Bean}s, never {@code @Primary}. A bean
* method returns the <b>concrete</b> class, so Spring sees every interface it implements before creating it
* ({@link DemoShowcaseSource} is both a content source and a listener).</li>
* </ul>
*/
@Configuration(proxyBeanMethods = false)
public class DemoPluginConfig {
// --- app-level settings ---------------------------------------------------------------------------------
/** Bound from {@code runway.plugin.runway-demo.*} (the descriptor's {@code settings:}); applied on restart. */
@Bean
@ConfigurationProperties("runway.plugin.runway-demo")
public DemoAppProps runwayDemoAppProps() {
return new DemoAppProps();
}
// --- per-site data -----------------------------------------------------------------------------------------
@Bean
public DemoNotesStore runwayDemoNotesStore(PluginSiteFiles files) {
return new DemoNotesStore(files);
}
@Bean
public DemoShowcaseStore runwayDemoShowcaseStore(PluginSiteFiles files, ContentChanges changes) {
return new DemoShowcaseStore(files, changes);
}
// --- callbacks ---------------------------------------------------------------------------------------------
@Bean
public DemoLifecycle runwayDemoLifecycle() {
return new DemoLifecycle();
}
@Bean
public DemoActivity runwayDemoActivity(DemoNotesStore notes, Sites sites) {
return new DemoActivity(notes, sites);
}
// --- axis implementations ----------------------------------------------------------------------------------
@Bean
@Order(200) // after the kernel's SEO (@Order 100) and icon (@Order 90) head contributors
public DemoAnalyticsHead runwayDemoAnalyticsHead(DemoAppProps props, PluginSettings settings) {
return new DemoAnalyticsHead(props, settings);
}
@Bean
public DemoNoticeWidget runwayDemoNoticeWidget(DemoAppProps props, PluginSettings settings, Messages messages) {
return new DemoNoticeWidget(props, settings, messages);
}
@Bean
public DemoFeedbackWidget runwayDemoFeedbackWidget(PluginSettings settings, Messages messages) {
return new DemoFeedbackWidget(settings, messages);
}
@Bean
public DemoMetaLengthCheck runwayDemoMetaLengthCheck(PluginSettings settings) {
return new DemoMetaLengthCheck(settings);
}
@Bean
public DemoEndpoints runwayDemoEndpoints(AccessCheck access, DemoNotesStore notes, Messages messages,
PluginSettings settings) {
return new DemoEndpoints(access, notes, messages, settings);
}
/** A content source AND a SOURCE-phase listener (it drops its own cache before consumers re-read). */
@Bean
public DemoShowcaseSource runwayDemoShowcaseSource(DemoShowcaseStore store, Messages messages) {
return new DemoShowcaseSource(store, messages);
}
// --- console -------------------------------------------------------------------------------------------------
@Bean
public DemoAdminModel runwayDemoAdminModel(DemoNotesStore notes, DemoAppProps props, PluginSettings settings,
Sites sites, SitePages pages, PluginInfo self) {
return new DemoAdminModel(notes, props, settings, sites, pages, self);
}
@Bean
public DemoConsoleController runwayDemoConsoleController(RequestContext request, AccessCheck access,
Messages messages, SitePages pages,
ContentCatalogView catalog, DemoNotesStore notes,
DemoShowcaseStore showcase, DemoActivity activity,
PluginInfo self) {
return new DemoConsoleController(request, access, messages, pages, catalog, notes, showcase, activity, self);
}
}
@@ -0,0 +1,134 @@
package mx.quest.demo;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Optional;
import mx.quest.runway.spi.ContentSource;
import mx.quest.runway.spi.model.Capabilities;
import mx.quest.runway.spi.model.CatalogChange;
import mx.quest.runway.spi.model.ContentBody;
import mx.quest.runway.spi.model.ContentRef;
import mx.quest.runway.spi.model.SiteLifecycleEvent;
import mx.quest.runway.spi.model.SiteView;
import mx.quest.runway.spi.service.Messages;
import mx.quest.runway.spi.service.SiteEventListener;
/**
* {@code ContentSource} — serves the site's {@link Showcase} as a real public page at {@value #PATH}, through the
* kernel's own routing, the tenant's master chrome, the {@code <head>} treatment, {@code ETag}/{@code 304}, the
* sitemap/llms.txt listing and on-site search. Nothing is served until an operator publishes a showcase from the
* demo's console screen.
*
* <p>It is also a {@link SiteEventListener} in the {@link Phase#SOURCE SOURCE} phase. <b>When to use a
* {@code SOURCE} listener:</b> when you are a content source that keeps derived state of your own (here, the
* {@link DemoShowcaseStore}'s cached read). The kernel runs every {@code SOURCE} listener first, evicts its content
* listing again, and only then runs the {@code CONSUMER}s (sitemaps, search indexes) — so a consumer that re-reads
* the listing never sees a source's stale state. This one drops its cache on:
* <ul>
* <li>a {@code CONTENT} change of its own source — on this node the store already holds the new value, but a change
* <b>replayed from another node</b> ({@code local == false}) is the only way this node learns the file
* changed;</li>
* <li>a <b>wholesale</b> lifecycle event ({@code DELETED}, {@code RESTORED}): the site's files were replaced or
* removed under it.</li>
* </ul>
* A callback only evicts — cheap and synchronous, as the contract asks (heavy work belongs on your own executor).
*/
public class DemoShowcaseSource implements ContentSource, SiteEventListener {
/** This source's key: the namespace of its content ids ({@code runway-demo:showcase}). */
static final String SOURCE_KEY = "runway-demo";
/** The id of the one item this source serves per site. */
static final String ID = "showcase";
/** Where the showcase is served. */
static final String PATH = "/demo/showcase";
/** The body template: this plugin's {@code templates/showcase.html} + {@code .th.xml}. */
static final String BODY_TEMPLATE = "__plugin__/runway-demo/showcase";
private static final int DESCRIPTION_CHARS = 150;
private final DemoShowcaseStore store;
private final Messages messages;
public DemoShowcaseSource(DemoShowcaseStore store, Messages messages) {
this.store = store;
this.messages = messages;
}
@Override
public String key() {
return SOURCE_KEY;
}
/** Metadata only and published only — it runs on anonymous public requests (the sitemap). */
@Override
public List<ContentRef> enumerate(SiteView site) {
return store.current(site.id()).map(showcase -> List.of(ref(site, showcase))).orElse(List.of());
}
/** The cheap routing probe: one string comparison before anything is read. */
@Override
public Optional<ContentRef> resolve(SiteView site, String path, Locale locale) {
if (!PATH.equals(path)) {
return Optional.empty();
}
return enumerate(site).stream().filter(ref -> ref.hasLocale(locale, site.defaultLocale())).findFirst();
}
@Override
public ContentBody body(SiteView site, String id, Locale locale) {
if (!ID.equals(id)) {
return ContentBody.empty();
}
return store.current(site.id()).map(showcase -> ContentBody.of(html(showcase.text())))
.orElse(ContentBody.empty());
}
/** Declared with {@link #CAP_INDEXABLE_TEXT}, so on-site search indexes the showcase's text too. */
@Override
public String indexableText(SiteView site, String id, Locale locale) {
return ID.equals(id) ? store.current(site.id()).map(s -> html(s.text())).orElse("") : "";
}
@Override
public Capabilities capabilities() {
return Capabilities.of(CAP_INDEXABLE_TEXT);
}
private ContentRef ref(SiteView site, Showcase showcase) {
String language = site.defaultLocale().getLanguage();
String title = messages.site(site.id(), site.defaultLocale(), "runwaydemo.showcase.title", "Showcase");
String text = showcase.text().strip();
String description = text.length() > DESCRIPTION_CHARS ? text.substring(0, DESCRIPTION_CHARS) + "…" : text;
// No locales listed: the item exists in the site's default language only. updatedAt moves on every
// publish — the render ETag folds it, so a client revalidating gets the new text, not a stale 304.
return ContentRef.of(ID, PATH, Map.of(), List.of(), Map.of(language, title), Map.of(language, description),
BODY_TEMPLATE, showcase.updatedAt());
}
/** The plain text as HTML: escaped, one paragraph, line breaks kept. */
static String html(String text) {
return "<p>" + Html.escape(text.replace("\r\n", "\n")).replace("\n", "<br>\n") + "</p>";
}
// --- SiteEventListener (SOURCE phase) ----------------------------------------------------------------------
@Override
public Phase phase() {
return Phase.SOURCE;
}
@Override
public void onSiteLifecycle(SiteLifecycleEvent event) {
if (event.wholesale()) {
store.evict(event.siteId());
}
}
@Override
public void onCatalogChanged(CatalogChange change) {
if (change.cause() == CatalogChange.Cause.CONTENT && SOURCE_KEY.equals(change.sourceKey())) {
store.evict(change.siteId());
}
}
}
@@ -0,0 +1,179 @@
package mx.quest.demo;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.time.Duration;
import java.time.Instant;
import java.time.format.DateTimeParseException;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.function.LongSupplier;
import mx.quest.runway.spi.service.ContentChanges;
import mx.quest.runway.spi.service.PluginSiteFiles;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import tools.jackson.core.JacksonException;
import tools.jackson.databind.DeserializationFeature;
import tools.jackson.dataformat.yaml.YAMLMapper;
/**
* Reads and writes the site's {@link Showcase} ({@value #FILE} in the plugin's per-site folder) and — the point of
* this class — <b>announces every write with {@link ContentChanges}</b>.
*
* <p><b>When to use {@code ContentChanges}.</b> After every mutation of content your {@code ContentSource} serves:
* an item created, edited, deleted, published, unpublished, or the whole corpus replaced (pass a {@code null} id).
* The host cannot see your files change; the call evicts routing, the content listing, sitemaps and search indexes on
* every node of a cluster and notifies every {@code SiteEventListener} before it returns. Call it from the code that
* made the change, <b>after</b> the write and outside your own locks (listeners run synchronously on this thread),
* and never from a {@code SiteEventListener} callback — the kernel refuses that. It is plugin-scoped like
* {@code PluginSettings}: it only accepts a source key this plugin contributes.
*
* <p>The parsed file is cached per site, because {@code enumerate} runs on every catalog rebuild and routing miss.
* The cache is dropped by this store's own writes, by {@link DemoShowcaseSource}'s {@code SOURCE}-phase listener
* (a change replayed from another node, a restored or deleted site), and after {@link #TTL} at the latest — the
* backstop for a file edited by hand, which nobody announces.
*/
public class DemoShowcaseStore {
/** The showcase file, relative to the plugin's per-site folder. */
static final String FILE = "showcase.yml";
/** The longest showcase text kept, in characters. */
static final int MAX_TEXT = 2000;
/** How long a cached read is trusted without any announcement. */
static final Duration TTL = Duration.ofSeconds(60);
private static final Logger log = LoggerFactory.getLogger(DemoShowcaseStore.class);
/** The on-disk shape; the instant is written as ISO-8601 text. */
record ShowcaseFile(String text, String updatedAt) {
}
private record Cached(Optional<Showcase> value, long loadedAtNanos) {
}
private final PluginSiteFiles files;
private final ContentChanges changes;
private final LongSupplier nanoClock;
private final YAMLMapper yaml = YAMLMapper.builder()
.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)
.build();
private final ConcurrentMap<String, Cached> cache = new ConcurrentHashMap<>();
private final ConcurrentMap<String, Object> locks = new ConcurrentHashMap<>();
public DemoShowcaseStore(PluginSiteFiles files, ContentChanges changes) {
this(files, changes, System::nanoTime);
}
DemoShowcaseStore(PluginSiteFiles files, ContentChanges changes, LongSupplier nanoClock) {
this.files = files;
this.changes = changes;
this.nanoClock = nanoClock;
}
/** The site's published showcase; empty when none is published or the file cannot be read (logged). */
public Optional<Showcase> current(String siteId) {
Cached cached = cache.get(siteId);
if (fresh(cached)) {
return cached.value();
}
// Load under the site's lock, so a read racing a publish can never put the old file back into the cache.
synchronized (locks.computeIfAbsent(siteId, k -> new Object())) {
cached = cache.get(siteId);
if (fresh(cached)) {
return cached.value();
}
Optional<Showcase> loaded = load(siteId);
cache.put(siteId, new Cached(loaded, nanoClock.getAsLong()));
return loaded;
}
}
private boolean fresh(Cached cached) {
return cached != null && nanoClock.getAsLong() - cached.loadedAtNanos() < TTL.toNanos();
}
/**
* Publishes {@code text} (stripped, capped at {@value #MAX_TEXT} characters) as the site's showcase, replacing
* any previous one, then announces the change.
*
* @throws IllegalArgumentException when the text is blank
* @throws UncheckedIOException when the file cannot be written (nothing is announced)
*/
public Showcase publish(String siteId, String text) {
String clean = text == null ? "" : text.strip();
if (clean.isEmpty()) {
throw new IllegalArgumentException("the showcase text is blank");
}
if (clean.length() > MAX_TEXT) {
clean = clean.substring(0, MAX_TEXT);
}
Showcase showcase = new Showcase(clean, Instant.now());
synchronized (locks.computeIfAbsent(siteId, k -> new Object())) {
try {
files.writeText(siteId, FILE, yaml.writeValueAsString(
new ShowcaseFile(showcase.text(), showcase.updatedAt().toString())));
} catch (IOException e) {
throw new UncheckedIOException("publishing the runway-demo showcase of site " + siteId, e);
}
cache.put(siteId, new Cached(Optional.of(showcase), nanoClock.getAsLong()));
}
// Written; now tell the host — outside our lock, because every listener runs on this thread before it returns.
changes.changed(siteId, DemoShowcaseSource.SOURCE_KEY, DemoShowcaseSource.ID);
return showcase;
}
/**
* Unpublishes the site's showcase (deletes the file) and announces the change, so the page, the sitemap entry
* and any search hit disappear at once.
*
* @return {@code true} if a showcase was published; {@code false} (and nothing announced) when there was none
* @throws UncheckedIOException when the file cannot be deleted
*/
public boolean unpublish(String siteId) {
boolean deleted;
synchronized (locks.computeIfAbsent(siteId, k -> new Object())) {
try {
deleted = files.delete(siteId, FILE);
} catch (IOException e) {
throw new UncheckedIOException("unpublishing the runway-demo showcase of site " + siteId, e);
}
cache.put(siteId, new Cached(Optional.empty(), nanoClock.getAsLong()));
}
if (deleted) {
changes.changed(siteId, DemoShowcaseSource.SOURCE_KEY, DemoShowcaseSource.ID);
}
return deleted;
}
/** Drops the cached read of {@code siteId}, so the next {@link #current} reads the file again. */
public void evict(String siteId) {
cache.remove(siteId);
}
private Optional<Showcase> load(String siteId) {
try {
Optional<String> text = files.readText(siteId, FILE);
if (text.isEmpty() || text.get().isBlank()) {
return Optional.empty();
}
ShowcaseFile file = yaml.readValue(text.get(), ShowcaseFile.class);
if (file == null || file.text() == null || file.text().isBlank()) {
return Optional.empty();
}
return Optional.of(new Showcase(file.text(), parseInstant(file.updatedAt())));
} catch (IOException | JacksonException | IllegalArgumentException e) {
// IllegalArgumentException: an unsafe site id or a path escaping the folder. Serve nothing, never a 500.
log.warn("runway-demo showcase of site {} could not be read: {}", siteId, e.toString());
return Optional.empty();
}
}
private static Instant parseInstant(String value) {
try {
return value == null ? Instant.EPOCH : Instant.parse(value);
} catch (DateTimeParseException e) {
return Instant.EPOCH;
}
}
}
@@ -0,0 +1,23 @@
package mx.quest.demo;
/**
* Minimal HTML-text escaping. Every SPI that returns raw HTML (head markup, widget fragments) OWNS its
* escaping — the host splices the output unescaped. Sufficient for element-text and double-quoted-attribute
* contexts, which is all this demo emits.
*/
final class Html {
private Html() {
}
static String escape(String s) {
if (s == null || s.isEmpty()) {
return "";
}
return s.replace("&", "&amp;")
.replace("<", "&lt;")
.replace(">", "&gt;")
.replace("\"", "&quot;")
.replace("'", "&#39;");
}
}
@@ -0,0 +1,25 @@
package mx.quest.demo;
/**
* One per-site "sticky note". Immutable; serialized to {@code notes.yml} by {@link DemoNotesStore}.
*
* @param id stable note id (a timestamp-derived token)
* @param text the note body (plain text; escaped wherever it is rendered)
* @param createdAt ISO-8601 creation instant
* @param origin who wrote it: {@value #ORIGIN_CONSOLE}, {@value #ORIGIN_VISITOR} or {@value #ORIGIN_SYSTEM}
* ({@code null} in a file written before the field existed reads as {@value #ORIGIN_SYSTEM})
*/
public record Note(String id, String text, String createdAt, String origin) {
/** Written by an operator on the demo's console screen. */
public static final String ORIGIN_CONSOLE = "console";
/** Sent by a visitor through the public feedback form (the anonymous POST route). */
public static final String ORIGIN_VISITOR = "visitor";
/** Written by the plugin itself (the welcome note, the settings-saved audit note). */
public static final String ORIGIN_SYSTEM = "system";
public Note {
text = text == null ? "" : text;
origin = origin == null || origin.isBlank() ? ORIGIN_SYSTEM : origin;
}
}
@@ -0,0 +1,20 @@
package mx.quest.demo;
import java.util.List;
/**
* The on-disk shape of {@code notes.yml} — a wrapper around the note list so the format can grow new top-level keys
* without breaking older readers (the store reads with unknown keys ignored).
*
* @param notes the site's notes, oldest first; never {@code null}
*/
public record NotesFile(List<Note> notes) {
public NotesFile {
notes = (notes == null) ? List.of() : List.copyOf(notes);
}
public static NotesFile empty() {
return new NotesFile(List.of());
}
}
@@ -0,0 +1,20 @@
package mx.quest.demo;
import java.time.Instant;
/**
* The demo's one piece of <b>routable content</b> per site: a short message an operator publishes from the demo's
* console screen, served by {@link DemoShowcaseSource} as a page at {@value DemoShowcaseSource#PATH}. Stored as
* {@code showcase.yml} in the plugin's per-site folder (published content — not personal data).
*
* @param text the message (plain text; escaped when rendered)
* @param updatedAt when it was last published — the {@code ContentRef.updatedAt} the page's {@code ETag} folds, so a
* republished message is never answered with a stale {@code 304}
*/
public record Showcase(String text, Instant updatedAt) {
public Showcase {
text = text == null ? "" : text;
updatedAt = updatedAt == null ? Instant.EPOCH : updatedAt;
}
}
@@ -0,0 +1,133 @@
package mx.quest.demo;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import java.util.Locale;
import java.util.Set;
import mx.quest.runway.spi.model.CatalogChange;
import mx.quest.runway.spi.model.LocalizedUrl;
import mx.quest.runway.spi.model.SettingsChange;
import mx.quest.runway.spi.model.SiteLifecycleEvent;
import mx.quest.runway.spi.model.SiteView;
import mx.quest.runway.spi.service.SiteEventListener;
import mx.quest.runway.spi.testkit.EventDispatch;
import mx.quest.runway.spi.testkit.FakeSiteServices;
import mx.quest.runway.spi.testkit.TempDirSiteFiles;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
/** The CONSUMER listener, driven by the testkit's {@link EventDispatch} in the kernel's order. */
class DemoActivityTest {
@TempDir
Path sites;
private DemoNotesStore notes;
private DemoActivity activity;
private EventDispatch events;
@BeforeEach
void setUp() throws IOException {
Files.createDirectories(sites.resolve("acme"));
notes = new DemoNotesStore(new TempDirSiteFiles(sites, "runway-demo"));
activity = new DemoActivity(notes, new FakeSiteServices()
.site(new SiteView("acme", "Acme", Locale.ENGLISH, List.of(Locale.ENGLISH), null)));
events = new EventDispatch("runway-demo", Set.of("runway-demo")).listener(activity);
}
private static LocalizedUrl url(String path) {
return new LocalizedUrl(Locale.ENGLISH, path, path);
}
@Test
void itIsAConsumer() {
assertEquals(SiteEventListener.Phase.CONSUMER, activity.phase());
}
@Test
void aSaveOfItsOwnSettingsAppendsOneAuditNote() {
int before = notes.count("acme");
events.settings("acme", "runway-demo");
List<Note> after = notes.list("acme");
assertEquals(before + 1, after.size());
assertTrue(after.getLast().text().startsWith("Per-site settings saved at "), after.getLast().text());
assertEquals(Note.ORIGIN_SYSTEM, after.getLast().origin());
assertTrue(events.failures().isEmpty());
}
@Test
void anotherPluginsSettingsSaveWritesNoNoteButIsRecordedAsACatalogChange() {
int before = notes.count("acme");
events.settings("acme", "contact");
assertEquals(before, notes.count("acme"), "onSettingsChanged is for this plugin's own settings only");
DemoActivity.Entry entry = activity.recent("acme").getFirst();
assertEquals("settings", entry.cause());
assertEquals("contact", entry.item());
}
@Test
void aChangeReplayedFromAnotherNodeWritesNoSecondNote() {
int before = notes.count("acme");
activity.onSettingsChanged(new SettingsChange("acme", "runway-demo", false));
assertEquals(before, notes.count("acme"), "the node where the save happened wrote the note");
}
@Test
void aPageChangeIsRecordedWithItsUrlsBeforeAndAfter() {
events.page("acme", "about", List.of(url("/about")), List.of(url("/about-us")));
DemoActivity.Entry entry = activity.recent("acme").getFirst();
assertEquals("page", entry.cause());
assertEquals("pages:about", entry.item());
assertEquals(List.of("/about"), entry.previousUrls());
assertEquals(List.of("/about-us"), entry.currentUrls());
assertTrue(entry.local());
}
@Test
void aDeletionStillNamesTheOldAddressAndAWholeSourceChangeShowsAStar() {
events.page("acme", "gone", List.of(url("/gone")), List.of());
events.catalog(new CatalogChange("acme", CatalogChange.Cause.CONTENT, "blog", null, "blog", null, null,
false));
List<DemoActivity.Entry> recent = activity.recent("acme");
assertEquals("blog:*", recent.get(0).item(), "newest first; a null id is the whole corpus");
assertFalse(recent.get(0).local());
assertEquals(List.of("/gone"), recent.get(1).previousUrls());
assertEquals(List.of(), recent.get(1).currentUrls());
}
@Test
void onlyTheNewestChangesAreKept() {
for (int i = 0; i < DemoActivity.KEEP + 4; i++) {
events.page("acme", "p" + i, List.of(), List.of());
}
List<DemoActivity.Entry> recent = activity.recent("acme");
assertEquals(DemoActivity.KEEP, recent.size());
assertEquals("pages:p" + (DemoActivity.KEEP + 3), recent.getFirst().item());
}
@Test
void aWholesaleEventDropsWhatWasRecordedForTheSite() {
events.page("acme", "about", List.of(), List.of());
events.lifecycle("acme", SiteLifecycleEvent.Kind.DELETED, false);
List<DemoActivity.Entry> recent = activity.recent("acme");
assertEquals(1, recent.size(), "only the deletion's own SITE change remains (lifecycle runs first)");
assertEquals("site", recent.getFirst().cause());
events.lifecycle("acme", SiteLifecycleEvent.Kind.SUSPENDED, false);
assertEquals(2, activity.recent("acme").size(), "a non-wholesale event keeps the record");
assertTrue(events.failures().isEmpty(), "an unknown site in Sites is handled: " + events.failures());
}
@Test
void anUnknownSiteHasNoActivityAndANoteFailureNeverPropagates() {
assertEquals(List.of(), activity.recent("nobody"));
activity.onSettingsChanged(new SettingsChange("ghost", "runway-demo", true)); // no folder: logged only
events.lifecycle("ghost", SiteLifecycleEvent.Kind.CREATED, false); // unknown to Sites
assertTrue(events.failures().isEmpty(), events.failures().toString());
}
}
@@ -0,0 +1,239 @@
package mx.quest.demo;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.flash;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.model;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.redirectedUrl;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.view;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import mx.quest.runway.spi.model.CatalogEntry;
import mx.quest.runway.spi.model.ContentRef;
import mx.quest.runway.spi.model.Finding;
import mx.quest.runway.spi.model.InstallResult;
import mx.quest.runway.spi.model.LocalizedUrl;
import mx.quest.runway.spi.model.PluginInfo;
import mx.quest.runway.spi.model.SiteView;
import mx.quest.runway.spi.model.StarterPage;
import mx.quest.runway.spi.service.ConsoleScreen;
import mx.quest.runway.spi.service.SitePages;
import mx.quest.runway.spi.testkit.EventDispatch;
import mx.quest.runway.spi.testkit.FakeContentCatalog;
import mx.quest.runway.spi.testkit.FakeSiteServices;
import mx.quest.runway.spi.testkit.TempDirSiteFiles;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
/**
* The console screen driven through Spring MVC in-process (MockMvc), over the testkit's fakes. The
* {@code @PreAuthorize} gates are enforced by the host's method security, which a standalone MockMvc does not have:
* {@link DemoPluginConfigTest} proves every handler carries one, and the live verify script proves a request without
* the permission or the CSRF token is refused.
*/
class DemoConsoleControllerTest {
private static final SiteView SITE = new SiteView("acme", "Acme", Locale.ENGLISH, List.of(Locale.ENGLISH), null);
private static final String BASE = "/__admin/runway-demo";
@TempDir
Path sites;
private FakeSiteServices kernel;
private FakeContentCatalog catalog;
private EventDispatch events;
private DemoNotesStore notes;
private DemoShowcaseStore showcase;
private DemoActivity activity;
private MockMvc mvc;
@BeforeEach
void setUp() throws IOException {
Files.createDirectories(sites.resolve("acme"));
kernel = new FakeSiteServices().site(SITE).current("acme");
catalog = new FakeContentCatalog().site("acme");
TempDirSiteFiles files = new TempDirSiteFiles(sites, "runway-demo");
events = new EventDispatch("runway-demo", Set.of("runway-demo"));
notes = new DemoNotesStore(files);
showcase = new DemoShowcaseStore(files, events);
activity = new DemoActivity(notes, kernel);
events.listener(new DemoShowcaseSource(showcase, kernel)).listener(activity);
mvc = mvcFor(kernel);
}
private MockMvc mvcFor(FakeSiteServices services) {
DemoConsoleController controller = new DemoConsoleController(services, services, services, services,
catalog, notes, showcase, activity, new PluginInfo("runway-demo", "2.0.1", sites));
return MockMvcBuilders.standaloneSetup(controller).build();
}
private DemoConsoleController.Screen screen(MvcResult result) {
return (DemoConsoleController.Screen) result.getModelAndView().getModel().get("rd");
}
@Test
void theScreenRendersInsideTheConsoleShell() throws Exception {
catalog.entry("acme", new CatalogEntry("pages", ContentRef.of("about", "/about", Map.of(), List.of(),
Map.of("en", "About"), Map.of(), "about", null), List.of(new LocalizedUrl(Locale.ENGLISH, "/about",
"/about")), "/about"));
MvcResult result = mvc.perform(get(BASE))
.andExpect(status().isOk())
.andExpect(view().name(ConsoleScreen.LAYOUT_VIEW))
.andExpect(model().attribute(ConsoleScreen.CONTENT_TEMPLATE, "__plugin__/runway-demo/console"))
.andExpect(model().attribute(ConsoleScreen.PAGE_TITLE_KEY, "runwaydemo.console.title"))
.andReturn();
DemoConsoleController.Screen screen = screen(result);
assertEquals("acme", screen.site().id(), "the site comes from RequestContext");
assertEquals("2.0.1", screen.pluginVersion());
assertEquals(1, screen.noteCount(), "the welcome note");
assertEquals(1, screen.catalogTotal());
assertEquals("/about", screen.catalog().getFirst().path());
assertNull(screen.showcaseText());
assertEquals("", screen.starterPath());
assertNull(screen.pathCheck());
}
@Test
void openingTheScreenWritesNothingAndTheFirstNoteKeepsTheWelcome() throws Exception {
Path pluginFolder = sites.resolve("acme").resolve("plugins").resolve("runway-demo");
mvc.perform(get(BASE)).andExpect(status().isOk());
mvc.perform(get(BASE)).andExpect(status().isOk());
assertFalse(Files.exists(pluginFolder), "a GET created no notes.yml, not even the plugin's folder");
mvc.perform(post(BASE + "/notes").param("text", "First")).andExpect(redirectedUrl(BASE));
List<Note> stored = notes.list("acme");
assertEquals(List.of(DemoNotesStore.WELCOME_ID, stored.get(1).id()), stored.stream().map(Note::id).toList(),
"the first POST writes the welcome the screen was showing, then the new note");
assertTrue(Files.isRegularFile(pluginFolder.resolve(DemoNotesStore.FILE)));
assertEquals(2, screen(mvc.perform(get(BASE)).andReturn()).noteCount());
}
@Test
void theApplicationConsoleHasNoSiteSoTheScreenIsNotFound() throws Exception {
mvcFor(new FakeSiteServices().site(SITE)).perform(get(BASE)).andExpect(status().isNotFound());
mvcFor(new FakeSiteServices().site(SITE)).perform(post(BASE + "/notes").param("text", "x"))
.andExpect(status().isNotFound());
assertEquals(1, notes.count("acme"), "nothing was written");
}
@Test
void addANote() throws Exception {
mvc.perform(post(BASE + "/notes").param("text", "Remember the milk"))
.andExpect(redirectedUrl(BASE))
.andExpect(flash().attribute(DemoConsoleController.FLASH, "Note added."));
Note last = notes.list("acme").getLast();
assertEquals("Remember the milk", last.text());
assertEquals(Note.ORIGIN_CONSOLE, last.origin());
mvc.perform(post(BASE + "/notes").param("text", " "))
.andExpect(redirectedUrl(BASE))
.andExpect(flash().attribute(DemoConsoleController.FLASH_ERROR, "Write something first."));
}
@Test
void publishAndUnpublishTheShowcaseAnnounceAndReachTheListener() throws Exception {
mvc.perform(post(BASE + "/showcase").param("text", "Fresh"))
.andExpect(flash().attribute(DemoConsoleController.FLASH, "Showcase published at /demo/showcase."));
assertEquals(1, events.announced().size(), "ContentChanges.changed was called");
assertEquals("content", activity.recent("acme").getFirst().cause(), "…and the CONSUMER listener saw it");
assertEquals("Fresh", screen(mvc.perform(get(BASE)).andReturn()).showcaseText());
mvc.perform(post(BASE + "/showcase/unpublish"))
.andExpect(flash().attribute(DemoConsoleController.FLASH, "Showcase unpublished."));
mvc.perform(post(BASE + "/showcase/unpublish"))
.andExpect(flash().attribute(DemoConsoleController.FLASH, "No showcase was published."));
assertEquals(2, events.announced().size(), "an unpublish of nothing announces nothing");
mvc.perform(post(BASE + "/showcase").param("text", ""))
.andExpect(flash().attribute(DemoConsoleController.FLASH_ERROR, "Write something first."));
}
@Test
void installingTheStarterPageNeedsEditPagesAndReportsTheOutcome() throws Exception {
mvc.perform(post(BASE + "/install-page"))
.andExpect(flash().attribute(DemoConsoleController.FLASH_ERROR,
"Installing a page needs the permission to edit pages."));
assertTrue(kernel.installs().isEmpty(), "nothing installed without EDIT_PAGES");
kernel.grant("EDIT_PAGES");
mvc.perform(post(BASE + "/install-page"))
.andExpect(flash().attribute(DemoConsoleController.FLASH, "Demo page published at /demo."));
StarterPage page = kernel.installs().getFirst();
assertEquals("runway-demo", page.slug());
assertEquals("/demo", page.path());
assertTrue(page.noindex(), "a demo page is kept out of search engines");
assertTrue(page.html().contains("data-widget=\"demo-notice/page\"")
&& page.html().contains("data-widget=\"demo-feedback/page\""), page.html());
assertTrue(page.logic().contains("~{${master} :: head}"), "chrome by the ${master} variable");
mvc.perform(post(BASE + "/install-page"))
.andExpect(flash().attribute(DemoConsoleController.FLASH,
"A demo page already exists at /demo; nothing changed."));
assertEquals("/demo", screen(mvc.perform(get(BASE)).andReturn()).starterPath());
}
@Test
void everyInstallOutcomeHasWords() {
DemoConsoleController controller = new DemoConsoleController(kernel, kernel, kernel, kernel, catalog, notes,
showcase, activity, new PluginInfo("runway-demo", "2.0.1", sites));
assertEquals("Demo page created at /demo and waiting in the review queue.", controller.describe(
new InstallResult(InstallResult.Outcome.PENDING_REVIEW, "/demo", List.of())));
assertEquals("Demo page created at /demo as a draft: the quality checks blocked publishing."
+ " h1.missing: No heading", controller.describe(new InstallResult(
InstallResult.Outcome.DRAFT_BLOCKED, "/demo", List.of(Finding.error("h1.missing", "No heading")))));
}
@Test
void aFailedInstallIsReportedNotThrown() throws Exception {
kernel.grant("EDIT_PAGES");
SitePages failing = new SitePages() {
@Override
public Optional<String> pathOf(String siteId, String slug) {
return Optional.empty();
}
@Override
public InstallResult install(String siteId, StarterPage page) {
throw new IllegalStateException("another page serves /demo");
}
};
DemoConsoleController controller = new DemoConsoleController(kernel, kernel, kernel, failing, catalog, notes,
showcase, activity, new PluginInfo("runway-demo", "2.0.1", sites));
MockMvcBuilders.standaloneSetup(controller).build().perform(post(BASE + "/install-page"))
.andExpect(flash().attribute(DemoConsoleController.FLASH_ERROR, "The demo page could not be installed."));
}
@Test
void thePathCheckAsksTheCatalog() throws Exception {
catalog.page("acme", "/about", Locale.ENGLISH, "about").route("/sitemap.xml");
DemoConsoleController.PathCheck owned = screen(mvc.perform(get(BASE).param("path", " /about "))
.andReturn()).pathCheck();
assertEquals(new DemoConsoleController.PathCheck("/about", true, true, "about"), owned);
DemoConsoleController.PathCheck route = screen(mvc.perform(get(BASE).param("path", "/sitemap.xml"))
.andReturn()).pathCheck();
assertEquals(new DemoConsoleController.PathCheck("/sitemap.xml", true, false, null), route);
DemoConsoleController.PathCheck reserved = screen(mvc.perform(get(BASE).param("path", "/__admin"))
.andReturn()).pathCheck();
assertEquals(false, reserved.servable());
}
@Test
void refreshDropsTheCachedListing() throws Exception {
mvc.perform(post(BASE + "/catalog/refresh"))
.andExpect(flash().attribute(DemoConsoleController.FLASH, "Content listing refreshed."));
assertEquals(List.of("acme"), catalog.refreshed());
}
}
@@ -0,0 +1,134 @@
package mx.quest.demo;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import mx.quest.runway.spi.testkit.TempDirSiteFiles;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
/** The notes store over the kernel's per-site files (the testkit's {@code TempDirSiteFiles}, with its confinement). */
class DemoNotesStoreTest {
@TempDir
Path sites;
private DemoNotesStore store;
@BeforeEach
void setUp() throws IOException {
Files.createDirectories(sites.resolve("acme"));
store = new DemoNotesStore(new TempDirSiteFiles(sites, "runway-demo"));
}
private Path file(String site) {
return sites.resolve(site).resolve("plugins").resolve("runway-demo").resolve(DemoNotesStore.FILE);
}
@Test
void theNotesLiveInThePluginsOwnFolderOfTheSite() {
store.append("acme", "hello", Note.ORIGIN_CONSOLE);
assertTrue(Files.isRegularFile(file("acme")), "sites/acme/plugins/runway-demo/notes.yml");
}
@Test
void readsShowTheWelcomeNoteButNeverWriteAFile() {
assertEquals(1, store.count("acme"));
Note welcome = store.list("acme").getFirst();
assertEquals(DemoNotesStore.WELCOME_ID, welcome.id());
assertEquals(Note.ORIGIN_SYSTEM, welcome.origin());
assertEquals("", welcome.createdAt(), "a note that is only shown has no time");
assertEquals(List.of(welcome), store.recent("acme", 10));
assertFalse(Files.exists(file("acme")), "a read wrote nothing");
assertFalse(Files.exists(file("acme").getParent()), "not even the plugin's folder");
}
@Test
void theFirstAppendKeepsTheWelcomeNoteTheSiteWasShowing() {
assertEquals(2, store.append("acme", "first", Note.ORIGIN_CONSOLE), "the welcome and the new note");
assertTrue(Files.isRegularFile(file("acme")));
List<Note> notes = store.list("acme");
assertEquals(2, notes.size());
Note welcome = notes.getFirst();
assertEquals(DemoNotesStore.WELCOME_ID, welcome.id(), "the same note the site was showing");
assertEquals(DemoNotesStore.welcome().text(), welcome.text());
assertFalse(welcome.createdAt().isEmpty(), "stored with the time of the first write");
assertEquals(welcome.createdAt(), notes.get(1).createdAt());
assertEquals("first", notes.get(1).text());
assertEquals(3, store.append("acme", "second", Note.ORIGIN_CONSOLE), "the welcome is written once");
}
@Test
void appendKeepsOrderOriginAndStripsAndCapsTheText() {
store.append("acme", " first ", Note.ORIGIN_CONSOLE);
store.append("acme", "x".repeat(DemoNotesStore.MAX_TEXT + 50), Note.ORIGIN_VISITOR);
List<Note> notes = store.list("acme");
assertEquals(3, notes.size(), "the welcome, then the two notes");
assertEquals("first", notes.get(1).text());
assertEquals(Note.ORIGIN_CONSOLE, notes.get(1).origin());
assertEquals(DemoNotesStore.MAX_TEXT, notes.get(2).text().length());
assertEquals(Note.ORIGIN_VISITOR, notes.get(2).origin());
assertEquals(List.of(notes.get(2), notes.get(1), notes.get(0)), store.recent("acme", 5),
"recent is newest first");
assertEquals(List.of(notes.get(2)), store.recent("acme", 1));
}
@Test
void theFileIsBoundedToTheNewestNotes() {
for (int i = 0; i < DemoNotesStore.MAX_NOTES + 3; i++) {
store.append("acme", "note " + i, Note.ORIGIN_CONSOLE);
}
List<Note> notes = store.list("acme");
assertEquals(DemoNotesStore.MAX_NOTES, notes.size());
assertEquals("note 3", notes.getFirst().text(), "the oldest were dropped");
}
@Test
void sitesAreIsolated() throws IOException {
Files.createDirectories(sites.resolve("other"));
store.append("acme", "only acme", Note.ORIGIN_CONSOLE);
assertFalse(store.list("other").stream().anyMatch(n -> n.text().equals("only acme")));
}
@Test
void anUnknownKeyInTheFileIsIgnoredAndAMissingOriginReadsAsSystem() throws IOException {
Files.createDirectories(file("acme").getParent());
Files.writeString(file("acme"), "notes:\n- id: n-1\n text: old\n createdAt: '2026-01-01T00:00:00Z'\n"
+ " colour: blue\nfutureKey: 1\n", StandardCharsets.UTF_8);
List<Note> notes = store.list("acme");
assertEquals(1, notes.size());
assertEquals("old", notes.getFirst().text());
assertEquals(Note.ORIGIN_SYSTEM, notes.getFirst().origin());
}
@Test
void anUnreadableFileDegradesReadsButNeverLetsAnAppendOverwriteIt() throws IOException {
Files.createDirectories(file("acme").getParent());
Files.writeString(file("acme"), "notes: [ this is: not: valid", StandardCharsets.UTF_8);
assertEquals(List.of(), store.list("acme"), "a console read degrades to empty");
assertEquals(0, store.count("acme"));
assertThrows(UncheckedIOException.class, () -> store.append("acme", "x", Note.ORIGIN_CONSOLE),
"an append refuses rather than rewriting the file from nothing");
assertEquals("notes: [ this is: not: valid", Files.readString(file("acme")), "the file is untouched");
}
@Test
void aSiteWhoseFolderIsGoneCannotBeWrittenAndReadsTheUnsavedWelcome() {
assertThrows(UncheckedIOException.class, () -> store.append("ghost", "x", Note.ORIGIN_CONSOLE));
assertEquals(List.of(DemoNotesStore.welcome()), store.list("ghost"), "the welcome is shown, unsaved");
assertFalse(Files.exists(sites.resolve("ghost")), "nothing was created for a site that does not exist");
}
@Test
void anUnsafeSiteIdIsRefusedBeforeAnyIo() {
assertThrows(IllegalArgumentException.class, () -> store.append("../acme", "x", Note.ORIGIN_CONSOLE));
}
}
@@ -0,0 +1,369 @@
package mx.quest.demo;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertInstanceOf;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.io.IOException;
import java.io.Reader;
import java.lang.reflect.Method;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Deque;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.TreeSet;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import mx.quest.runway.spi.ContentSource;
import mx.quest.runway.spi.ContentWidget;
import mx.quest.runway.spi.EndpointContributor;
import mx.quest.runway.spi.HeadContributor;
import mx.quest.runway.spi.PageQualityCheck;
import mx.quest.runway.spi.model.PluginInfo;
import mx.quest.runway.spi.model.SiteView;
import mx.quest.runway.spi.service.ConsoleScreen;
import mx.quest.runway.spi.service.ContentChanges;
import mx.quest.runway.spi.service.PluginLifecycle;
import mx.quest.runway.spi.service.PluginSettings;
import mx.quest.runway.spi.service.PluginSiteFiles;
import mx.quest.runway.spi.service.SiteEventListener;
import mx.quest.runway.spi.testkit.EventDispatch;
import mx.quest.runway.spi.testkit.FakeContentCatalog;
import mx.quest.runway.spi.testkit.FakePluginSettings;
import mx.quest.runway.spi.testkit.FakeSiteServices;
import mx.quest.runway.spi.testkit.TempDirSiteFiles;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.core.annotation.AnnotatedElementUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.yaml.snakeyaml.Yaml;
/**
* The plugin's contract with the host, checked at build time — the same things the kernel's load-time checks warn
* about (and refuse from Runway 1.0): wiring over SPI services only, the bean-name rule, the allowed Spring surface,
* the console controller's mappings and gates, the bean names the templates reference, the descriptor (SPI floor,
* release version, personal data), the i18n bundles, and that the compiled classes link nothing of the host but the
* SPI.
*/
class DemoPluginConfigTest {
private static final String PREFIX = "runwayDemo";
private static Set<String> beanMethodNames() {
return Arrays.stream(DemoPluginConfig.class.getDeclaredMethods())
.filter(m -> m.isAnnotationPresent(Bean.class))
.map(Method::getName)
.collect(Collectors.toCollection(TreeSet::new));
}
@SuppressWarnings("unchecked")
private static Map<String, Object> descriptor() throws IOException {
try (Reader in = Files.newBufferedReader(Path.of("plugin.yml"), StandardCharsets.UTF_8)) {
return (Map<String, Object>) new Yaml().load(in);
}
}
@Test
void wiresEverythingFromSpiServicesAlone(@TempDir Path sites) throws IOException {
Files.createDirectories(sites.resolve("acme"));
FakeSiteServices kernel = new FakeSiteServices()
.site(new SiteView("acme", "Acme", Locale.ENGLISH, List.of(Locale.ENGLISH), null))
.page("acme", DemoConsoleController.STARTER_SLUG, "/demo-moved");
try (AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext()) {
ctx.registerBean(PluginSettings.class, () -> new FakePluginSettings()
.secret("acme", "analytics.site-token", "t0k3n"));
ctx.registerBean(PluginSiteFiles.class, () -> new TempDirSiteFiles(sites, "runway-demo"));
ctx.registerBean(ContentChanges.class, () -> new EventDispatch("runway-demo", Set.of("runway-demo")));
ctx.registerBean(PluginInfo.class, () -> new PluginInfo("runway-demo", "2.0.1", sites));
ctx.registerBean(FakeSiteServices.class, () -> kernel);
ctx.registerBean(FakeContentCatalog.class, () -> new FakeContentCatalog().site("acme"));
ctx.register(DemoPluginConfig.class);
ctx.refresh();
assertEquals(Set.of("runwayDemoAnalyticsHead"), ctx.getBeansOfType(HeadContributor.class).keySet());
assertEquals(Set.of("runwayDemoNoticeWidget", "runwayDemoFeedbackWidget"),
ctx.getBeansOfType(ContentWidget.class).keySet());
assertEquals(Set.of("runwayDemoMetaLengthCheck"), ctx.getBeansOfType(PageQualityCheck.class).keySet());
assertEquals(Set.of("runwayDemoEndpoints"), ctx.getBeansOfType(EndpointContributor.class).keySet());
assertEquals(Set.of("runwayDemoShowcaseSource"), ctx.getBeansOfType(ContentSource.class).keySet());
assertEquals(Set.of("runwayDemoShowcaseSource", "runwayDemoActivity"),
ctx.getBeansOfType(SiteEventListener.class).keySet(), "one SOURCE and one CONSUMER listener");
assertEquals(Set.of("runwayDemoLifecycle"), ctx.getBeansOfType(PluginLifecycle.class).keySet());
assertNotNull(ctx.getBean("runwayDemoConsoleController", DemoConsoleController.class));
assertNotNull(ctx.getBean("runwayDemoAppProps", DemoAppProps.class));
DemoAdminModel model = ctx.getBean("runwayDemoAdminModel", DemoAdminModel.class);
assertEquals(1, model.noteCount("acme"), "the notes store works over the injected site files");
assertEquals("Acme", model.siteName("acme"), "…the site name comes from Sites");
assertEquals("/demo-moved", model.demoPagePath("acme"), "…the page path from SitePages");
assertTrue(model.siteTokenConfigured("acme"), "…the secret's presence from PluginSettings");
assertEquals("2.0.1", model.pluginVersion(), "…the version from PluginInfo");
}
}
@Test
void theAdminModelIsNullSafeForTheApplicationConsole(@TempDir Path sites) {
DemoAdminModel model = new DemoAdminModel(new DemoNotesStore(new TempDirSiteFiles(sites, "runway-demo")),
new DemoAppProps(), new FakePluginSettings(), new FakeSiteServices(), new FakeSiteServices(),
new PluginInfo("runway-demo", "2.0.1", sites));
assertEquals(0, model.noteCount(null));
assertEquals(List.of(), model.recentNotes(" "));
assertEquals("", model.siteName(null));
assertEquals("", model.demoPagePath(null));
assertFalse(model.siteTokenConfigured(null));
assertEquals("ghost", model.siteName("ghost"), "an unknown site shows its id");
assertEquals(mx.quest.runway.spi.RunwaySpi.VERSION, model.builtSpi());
assertEquals(mx.quest.runway.spi.RunwaySpi.runtimeVersion(), model.runningSpi());
}
@Test
void everyBeanNameStartsWithThePluginIdInLowerCamelCase() {
Set<String> names = beanMethodNames();
assertEquals(Set.of("runwayDemoAppProps", "runwayDemoNotesStore", "runwayDemoShowcaseStore",
"runwayDemoLifecycle", "runwayDemoActivity", "runwayDemoAnalyticsHead", "runwayDemoNoticeWidget",
"runwayDemoFeedbackWidget", "runwayDemoMetaLengthCheck", "runwayDemoEndpoints",
"runwayDemoShowcaseSource", "runwayDemoAdminModel", "runwayDemoConsoleController"), names);
for (Method m : DemoPluginConfig.class.getDeclaredMethods()) {
Bean bean = m.getAnnotation(Bean.class);
if (bean != null) {
assertEquals(0, bean.name().length + bean.value().length, "the method name is the bean name: " + m);
}
}
assertFalse(AnnotatedElementUtils.hasAnnotation(DemoPluginConfig.class,
org.springframework.boot.context.properties.EnableConfigurationProperties.class),
"@EnableConfigurationProperties would register a '<prefix>-<class>' bean name");
}
/** Servlet filters, security chains and post-processors are outside what a plugin may contribute. */
@Test
void noBeanIsOfAForbiddenSpringType() {
Set<String> forbidden = Set.of("jakarta.servlet.Filter", "org.springframework.security.web.SecurityFilterChain",
"org.springframework.boot.web.servlet.FilterRegistrationBean",
"org.springframework.beans.factory.config.BeanPostProcessor",
"org.springframework.beans.factory.config.BeanFactoryPostProcessor");
for (Method m : DemoPluginConfig.class.getDeclaredMethods()) {
if (!m.isAnnotationPresent(Bean.class)) {
continue;
}
Deque<Class<?>> queue = new ArrayDeque<>(List.of(m.getReturnType()));
Set<Class<?>> seen = new HashSet<>();
while (!queue.isEmpty()) {
Class<?> type = queue.pop();
if (!seen.add(type)) {
continue;
}
assertFalse(forbidden.contains(type.getName()), m.getName() + " is a " + type.getName());
if (type.getSuperclass() != null) {
queue.add(type.getSuperclass());
}
queue.addAll(List.of(type.getInterfaces()));
}
assertFalse(AnnotatedElementUtils.hasAnnotation(m.getReturnType(),
org.springframework.web.bind.annotation.ControllerAdvice.class), "no @ControllerAdvice needed");
}
}
@Test
void theConsoleControllerIsAConsoleScreenGatedAndMappedUnderItsOwnPrefix() {
Class<?> type = DemoConsoleController.class;
assertTrue(AnnotatedElementUtils.hasAnnotation(type, Controller.class));
assertTrue(type.isAnnotationPresent(ConsoleScreen.class), "the kernel fills the console shell for it");
assertEquals(List.of("/__admin/runway-demo"),
List.of(AnnotatedElementUtils.findMergedAnnotation(type, RequestMapping.class).path()));
int handlers = 0;
int gets = 0;
for (Method m : type.getDeclaredMethods()) {
RequestMapping mapping = AnnotatedElementUtils.findMergedAnnotation(m, RequestMapping.class);
if (mapping == null) {
continue;
}
handlers++;
PreAuthorize gate = m.getAnnotation(PreAuthorize.class);
assertNotNull(gate, m.getName() + " must be gated");
assertEquals("@authz.may('runway-demo|manage-notes')", gate.value());
for (String path : mapping.path()) {
assertTrue(path.isEmpty() || path.startsWith("/"), path);
}
if (m.isAnnotationPresent(GetMapping.class)) {
gets++;
assertEquals("screen", m.getName(), "only the read-only screen answers GET");
}
}
assertEquals(6, handlers, "the screen and five POST actions");
assertEquals(1, gets);
}
@Test
void theTemplatesReferenceOnlyOurOwnBeansAndAuthz() throws IOException {
Set<String> referenced = new TreeSet<>();
try (Stream<Path> files = Files.list(Path.of("templates"))) {
for (Path file : files.filter(p -> p.toString().endsWith(".th.xml")).toList()) {
String live = Files.readString(file, StandardCharsets.UTF_8).replaceAll("(?s)<!--.*?-->", "");
Matcher m = Pattern.compile("@(\\w+)\\.").matcher(live);
while (m.find()) {
referenced.add(m.group(1));
}
}
}
assertEquals(Set.of("authz", "runwayDemoAdminModel"), referenced);
assertTrue(beanMethodNames().contains("runwayDemoAdminModel"));
}
@Test
void theDescriptorDeclaresTheSpiFloorTheReleaseVersionAndTheConsoleMenu() throws IOException {
Map<String, Object> yml = descriptor();
assertEquals(">=1.0.0", yml.get("requiresSpi"), "built for the frozen SPI 1.0.0 contract");
String pom = Files.readString(Path.of("pom.xml"), StandardCharsets.UTF_8);
Matcher version = Pattern.compile("<artifactId>runway-plugin-runway-demo</artifactId>\\s*<version>([^<]+)")
.matcher(pom);
assertTrue(version.find());
assertEquals("2.1.0", version.group(1));
assertEquals(version.group(1), String.valueOf(yml.get("version")), "plugin.yml and pom.xml agree");
assertFalse(pom.contains("<artifactId>runway-app</artifactId>"), "no runway-app dependency in any scope");
assertTrue(pom.contains("<project.build.outputTimestamp>2026-10-21T17:23:00Z</project.build.outputTimestamp>"));
@SuppressWarnings("unchecked")
List<Map<String, Object>> menu = (List<Map<String, Object>>) yml.get("menu");
assertEquals(DemoConsoleController.BASE, menu.get(0).get("path"), "the menu opens the console screen");
assertEquals(DemoEndpoints.PERMISSION, menu.get(0).get("permission"), "the FULL namespaced key");
}
@Test
void theReleaseZipIsNamedAfterThePluginIdLikeEveryOtherPluginAndTheJarKeepsItsName() throws IOException {
String id = String.valueOf(descriptor().get("id"));
String pom = Files.readString(Path.of("pom.xml"), StandardCharsets.UTF_8).replaceAll("(?s)<!--.*?-->", "");
// publish-plugin-release.sh uploads target/runway-plugin-<id>-<version>.zip under the tag <id>-<version>.
assertTrue(pom.contains("<artifactId>runway-plugin-" + id + "</artifactId>"), "artifactId runway-plugin-" + id);
assertTrue(pom.contains("<zip destfile=\"${project.build.directory}/${project.artifactId}-${project.version}"
+ ".zip\">"), "the zip is named after the artifactId");
// The kernel loads every *.jar in the plugin's folder: a renamed jar copied over a 2.0.0 folder would load
// beside the old one. So the jar keeps the name 2.0.0 shipped.
assertTrue(pom.contains("<finalName>runway-plugin-demo</finalName>"), "the jar keeps its 2.0.0 name");
}
@Test
@SuppressWarnings("unchecked")
void theNotesFileIsDeclaredPersonalDataSoTransferCopiesLeaveItOut() throws IOException {
Map<String, Object> siteData = (Map<String, Object>) descriptor().get("siteData");
assertNotNull(siteData, "plugin.yml declares siteData");
assertEquals(List.of(DemoNotesStore.FILE), siteData.get("personal"),
"exactly the file holding what people typed; the showcase is published content");
}
@Test
@SuppressWarnings("unchecked")
void theSiteTokenIsDeclaredASecretAndEveryReadSettingIsDeclared() throws IOException {
List<Map<String, Object>> schema = (List<Map<String, Object>>) descriptor().get("siteSettings");
Map<String, Object> types = schema.stream()
.collect(Collectors.toMap(s -> (String) s.get("key"), s -> s.get("type")));
assertEquals("secret", types.get("analytics.site-token"),
"PluginSettings.secret hands out only keys declared type: secret");
String code = readAll(Path.of("src/main/java"));
Matcher reads = Pattern.compile("\\.(?:bool|string|integer|decimal|list)\\(\"([a-z.-]+)\"").matcher(code);
int count = 0;
while (reads.find()) {
count++;
assertTrue(types.containsKey(reads.group(1)), "read but not declared: " + reads.group(1));
}
assertTrue(count >= 8, "the per-site reads were found (" + count + ")");
}
private static String readAll(Path root) throws IOException {
StringBuilder all = new StringBuilder();
try (Stream<Path> files = Files.walk(root)) {
for (Path f : files.filter(Files::isRegularFile).toList()) {
all.append(Files.readString(f, StandardCharsets.UTF_8)).append('\n');
}
}
return all.toString();
}
@Test
void theEnglishAndSpanishBundlesDefineTheSameKeysAndEveryKeyUsedExists() throws IOException {
Set<String> en = keys("i18n/messages.properties");
assertEquals(en, keys("i18n/messages_es.properties"));
Set<String> used = new TreeSet<>();
Matcher code = Pattern.compile("\"(runwaydemo\\.[A-Za-z.]+)\"").matcher(readAll(Path.of("src/main/java")));
while (code.find()) {
used.add(code.group(1));
}
Matcher template = Pattern.compile("#\\{(runwaydemo\\.[A-Za-z.]+)").matcher(readAll(Path.of("templates")));
while (template.find()) {
used.add(template.group(1));
}
Matcher descriptor = Pattern.compile("label: (runwaydemo\\.[A-Za-z.]+)")
.matcher(Files.readString(Path.of("plugin.yml"), StandardCharsets.UTF_8));
while (descriptor.find()) {
used.add(descriptor.group(1));
}
used.removeIf(en::contains);
assertEquals(Set.of(), used, "keys used but missing from the bundle");
}
private static Set<String> keys(String file) throws IOException {
Properties p = new Properties();
try (Reader in = Files.newBufferedReader(Path.of(file), StandardCharsets.UTF_8)) {
p.load(in);
}
return new TreeSet<>(p.stringPropertyNames());
}
@Test
void theCompiledClassesLinkNoHostInternals() throws IOException {
Path classes = Path.of("target", "classes");
Pattern host = Pattern.compile("mx[/.]quest[/.]runway[/.](?!spi[/.])[\\w/.$]*");
List<String> problems = new ArrayList<>();
int scanned = 0;
try (Stream<Path> files = Files.walk(classes)) {
for (Path file : files.filter(p -> p.toString().endsWith(".class")).toList()) {
scanned++;
String rel = classes.relativize(file).toString().replace('\\', '/');
if (rel.startsWith("mx/quest/runway/")) {
problems.add(rel + " lives under mx.quest.runway");
}
// The constant pool holds class names and descriptors as (modified) UTF-8; Latin-1 keeps every byte
// as one char, so an ASCII pattern finds them without parsing the class file.
Matcher m = host.matcher(new String(Files.readAllBytes(file), StandardCharsets.ISO_8859_1));
while (m.find()) {
problems.add(rel + " → " + m.group());
}
}
}
assertTrue(scanned >= 18, "the compiled classes were found (" + scanned + ")");
assertTrue(problems.isEmpty(), "host linkage: " + problems);
}
@Test
void theRemovedSeamsAreGone() {
for (String gone : List.of("DemoTimingFilter", "DemoNotesBackup", "DemoConfigReactor", "SiteConfig")) {
assertNull(classOrNull("mx.quest.demo." + gone), gone + " was removed in 2.0.0");
}
assertInstanceOf(PluginLifecycle.class, new DemoLifecycle());
}
private static Class<?> classOrNull(String name) {
try {
return Class.forName(name);
} catch (ClassNotFoundException e) {
return null;
}
}
}
@@ -0,0 +1,202 @@
package mx.quest.demo;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import java.util.Locale;
import java.util.Set;
import java.util.concurrent.atomic.AtomicLong;
import mx.quest.runway.spi.ContentSource;
import mx.quest.runway.spi.model.CatalogChange;
import mx.quest.runway.spi.model.ContentRef;
import mx.quest.runway.spi.model.SiteLifecycleEvent;
import mx.quest.runway.spi.model.SiteView;
import mx.quest.runway.spi.service.SiteEventListener;
import mx.quest.runway.spi.testkit.EventDispatch;
import mx.quest.runway.spi.testkit.FakeSiteServices;
import mx.quest.runway.spi.testkit.TempDirSiteFiles;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
/**
* The showcase content source and its store: writes are announced with {@code ContentChanges} (the testkit's
* {@link EventDispatch}, which applies the kernel's refusal rules and phase order), the source serves what was
* published, and its {@code SOURCE}-phase listener drops the cache on the events that mean the file changed under it.
*/
class DemoShowcaseTest {
private static final SiteView SITE = new SiteView("acme", "Acme", Locale.ENGLISH, List.of(Locale.ENGLISH), null);
@TempDir
Path sites;
private EventDispatch events;
private AtomicLong nanos;
private DemoShowcaseStore store;
private DemoShowcaseSource source;
private FakeSiteServices kernel;
@BeforeEach
void setUp() throws IOException {
Files.createDirectories(sites.resolve("acme"));
events = new EventDispatch("runway-demo", Set.of(DemoShowcaseSource.SOURCE_KEY));
nanos = new AtomicLong();
store = new DemoShowcaseStore(new TempDirSiteFiles(sites, "runway-demo"), events, nanos::get);
kernel = new FakeSiteServices().site(SITE);
source = new DemoShowcaseSource(store, kernel);
events.listener(source);
}
private Path file() {
return sites.resolve("acme/plugins/runway-demo").resolve(DemoShowcaseStore.FILE);
}
@Test
void nothingIsServedUntilAShowcaseIsPublished() {
assertEquals(List.of(), source.enumerate(SITE));
assertTrue(source.resolve(SITE, DemoShowcaseSource.PATH, Locale.ENGLISH).isEmpty());
assertTrue(source.body(SITE, DemoShowcaseSource.ID, Locale.ENGLISH).bodyHtml().isEmpty());
}
@Test
void publishWritesTheFileThenAnnouncesTheChangeOfItsOwnSource() {
store.publish("acme", " Hello <world> ");
assertTrue(Files.isRegularFile(file()));
List<CatalogChange> announced = events.announced();
assertEquals(1, announced.size());
assertEquals(CatalogChange.Cause.CONTENT, announced.getFirst().cause());
assertEquals("runway-demo", announced.getFirst().sourceKey());
assertEquals("showcase", announced.getFirst().id());
assertEquals("runway-demo", announced.getFirst().pluginId());
assertTrue(events.failures().isEmpty(), events.failures().toString());
}
@Test
void thePublishedShowcaseIsServedAsAPageOfTheSite() {
kernel.message("acme", "runwaydemo.showcase.title", "Our showcase");
store.publish("acme", "Line one\r\nLine <two> & three");
List<ContentRef> refs = source.enumerate(SITE);
assertEquals(1, refs.size());
ContentRef ref = refs.getFirst();
assertEquals("showcase", ref.id());
assertEquals("/demo/showcase", ref.path());
assertEquals("__plugin__/runway-demo/showcase", ref.bodyTemplate());
assertTrue(ref.published());
assertEquals("Our showcase", ref.titleFor(Locale.ENGLISH), "the title comes from Messages.site");
assertEquals("Line one\r\nLine <two> & three", ref.descriptionFor(Locale.ENGLISH));
assertEquals(ref, source.resolve(SITE, "/demo/showcase", Locale.ENGLISH).orElseThrow());
assertTrue(source.resolve(SITE, "/demo/showcase", Locale.of("es")).isEmpty(), "default language only");
assertTrue(source.resolve(SITE, "/demo/other", Locale.ENGLISH).isEmpty());
assertEquals("<p>Line one<br>\nLine &lt;two&gt; &amp; three</p>",
source.body(SITE, "showcase", Locale.ENGLISH).bodyHtml(), "escaped; line breaks kept");
assertEquals("", source.body(SITE, "other", Locale.ENGLISH).bodyHtml());
assertTrue(source.indexableText(SITE, "showcase", Locale.ENGLISH).contains("Line &lt;two&gt;"));
assertTrue(source.capabilities().has(ContentSource.CAP_INDEXABLE_TEXT), "search indexes it");
}
@Test
void aRepublishMovesUpdatedAtSoTheEtagChanges() throws InterruptedException {
store.publish("acme", "one");
ContentRef first = source.enumerate(SITE).getFirst();
Thread.sleep(5);
store.publish("acme", "two");
ContentRef second = source.enumerate(SITE).getFirst();
assertTrue(second.updatedAt().isAfter(first.updatedAt()), first.updatedAt() + " → " + second.updatedAt());
}
@Test
void aLongDescriptionIsCutAndALongTextCapped() {
store.publish("acme", "y".repeat(DemoShowcaseStore.MAX_TEXT + 10));
ContentRef ref = source.enumerate(SITE).getFirst();
assertEquals(151, ref.descriptionFor(Locale.ENGLISH).length(), "150 chars and an ellipsis");
assertEquals(DemoShowcaseStore.MAX_TEXT + 7,
source.body(SITE, "showcase", Locale.ENGLISH).bodyHtml().length(), "<p>…</p> around the capped text");
}
@Test
void aBlankShowcaseIsRefusedAndAnnouncesNothing() {
assertThrows(IllegalArgumentException.class, () -> store.publish("acme", " "));
assertTrue(events.announced().isEmpty());
}
@Test
void unpublishDeletesAndAnnouncesOnlyWhenSomethingWasPublished() {
assertFalse(store.unpublish("acme"), "nothing to unpublish");
assertTrue(events.announced().isEmpty(), "and nothing announced");
store.publish("acme", "live");
assertTrue(store.unpublish("acme"));
assertEquals(2, events.announced().size());
assertFalse(Files.exists(file()));
assertEquals(List.of(), source.enumerate(SITE));
}
@Test
void theCacheServesWithinTheTtlAndRereadsAfterIt() throws IOException {
store.publish("acme", "cached");
store.current("acme"); // the own announcement evicted the cache; this read fills it again
Files.writeString(file(), "text: edited by hand\nupdatedAt: '2026-01-01T00:00:00Z'\n", StandardCharsets.UTF_8);
source.onCatalogChanged(noChange()); // an unrelated change does not evict
assertEquals("cached", store.current("acme").orElseThrow().text(), "no announcement: the cache holds");
nanos.addAndGet(DemoShowcaseStore.TTL.toNanos());
assertEquals("edited by hand", store.current("acme").orElseThrow().text(), "the TTL is the backstop");
}
private static CatalogChange noChange() {
return new CatalogChange("acme", CatalogChange.Cause.PAGE, "pages", "about", null, null, null, true);
}
@Test
void aChangeReplayedFromAnotherNodeEvictsThisNodesCache() throws IOException {
store.publish("acme", "before");
Files.writeString(file(), "text: from the peer\nupdatedAt: '2026-01-01T00:00:00Z'\n", StandardCharsets.UTF_8);
events.catalog(new CatalogChange("acme", CatalogChange.Cause.CONTENT, "runway-demo", "showcase",
"runway-demo", null, null, false));
assertEquals("from the peer", store.current("acme").orElseThrow().text());
}
@Test
void aWholesaleLifecycleEventEvictsAndOthersDoNot() throws IOException {
store.publish("acme", "before");
store.current("acme");
Files.writeString(file(), "text: restored\nupdatedAt: '2026-01-01T00:00:00Z'\n", StandardCharsets.UTF_8);
source.onSiteLifecycle(new SiteLifecycleEvent("acme", SiteLifecycleEvent.Kind.UPDATED, false, true));
assertEquals("before", store.current("acme").orElseThrow().text(), "an UPDATED site keeps its files");
events.lifecycle("acme", SiteLifecycleEvent.Kind.RESTORED, true);
assertEquals("restored", store.current("acme").orElseThrow().text(), "a RESTORED site replaced them");
}
@Test
void theSourceListensInTheSourcePhase() {
assertEquals(SiteEventListener.Phase.SOURCE, source.phase());
}
@Test
void aCorruptOrForeignFileServesNothing() throws IOException {
Files.createDirectories(file().getParent());
Files.writeString(file(), "text: [ unclosed", StandardCharsets.UTF_8);
assertTrue(store.current("acme").isEmpty());
assertTrue(store.current("../x").isEmpty(), "an unsafe id answers nothing rather than throwing on a request");
}
@Test
void announcingFromInsideACallbackIsRefusedByTheKernelRule() {
EventDispatch strict = new EventDispatch("runway-demo", Set.of("runway-demo"));
DemoShowcaseStore inner = new DemoShowcaseStore(new TempDirSiteFiles(sites, "runway-demo"), strict);
strict.listener(new SiteEventListener() {
@Override
public void onSiteLifecycle(SiteLifecycleEvent event) {
inner.publish("acme", "from a callback");
}
});
strict.lifecycle("acme", SiteLifecycleEvent.Kind.UPDATED, false);
assertEquals(1, strict.failures().size());
assertTrue(strict.failures().getFirst() instanceof IllegalStateException);
}
}
@@ -0,0 +1,352 @@
package mx.quest.demo;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.atomic.AtomicLong;
import mx.quest.runway.spi.model.Finding;
import mx.quest.runway.spi.model.HeadContext;
import mx.quest.runway.spi.model.PageMeta;
import mx.quest.runway.spi.model.PageView;
import mx.quest.runway.spi.model.RenderFragment;
import mx.quest.runway.spi.model.Route;
import mx.quest.runway.spi.model.RouteRequest;
import mx.quest.runway.spi.model.RouteResponse;
import mx.quest.runway.spi.model.SiteView;
import mx.quest.runway.spi.model.WidgetView;
import mx.quest.runway.spi.testkit.FakePluginSettings;
import mx.quest.runway.spi.testkit.FakeSiteServices;
import mx.quest.runway.spi.testkit.TempDirSiteFiles;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
/**
* The demo's axis implementations as pure functions of their SPI inputs: no Spring, no host — the services come from
* {@code runway-spi-testkit}, whose fakes apply the kernel's input rules.
*/
class DemoSpiUnitTest {
private static final SiteView SITE = new SiteView("acme", "Acme", Locale.ENGLISH, List.of(Locale.ENGLISH),
"https://acme.test");
private static final PageMeta PAGE = new PageMeta("about", "About us", "A description",
List.of(Locale.ENGLISH), Locale.ENGLISH, true, false);
@TempDir
Path sites;
private DemoNotesStore notes;
private FakeSiteServices kernel;
@BeforeEach
void setUp() throws IOException {
Files.createDirectories(sites.resolve("acme"));
notes = new DemoNotesStore(new TempDirSiteFiles(sites, "runway-demo"));
kernel = new FakeSiteServices().site(SITE);
}
private static FakePluginSettings settings(Map<String, ?> stored) {
return new FakePluginSettings().site("acme", stored);
}
// --- HeadContributor -------------------------------------------------------------------------------
@Test
void headEmitsGeneratorAndGatesAnalyticsOnTheSiteFlagAndTheAppKey() {
DemoAppProps props = new DemoAppProps();
props.getGenerator().setLabel("My Site");
props.getAnalytics().setWriteKey("ENC(opaque)");
HeadContext ctx = new HeadContext(SITE, PAGE, Locale.ENGLISH, "https://acme.test/about", null,
List.of(), false, false);
String on = new DemoAnalyticsHead(props, settings(Map.of("analytics.enabled", true))).render(ctx);
assertTrue(on.contains("<meta name=\"generator\" content=\"My Site\">"), on);
assertTrue(on.contains("data-demo-analytics") && on.contains("demo-analytics.js"), on);
assertFalse(on.contains("ENC(opaque)"), "the key never reaches the page");
String off = new DemoAnalyticsHead(props, settings(Map.of())).render(ctx);
assertFalse(off.contains("data-demo-analytics"), "analytics script absent when the site flag is off");
assertTrue(off.contains("demo.css"), "stylesheet linked (the notice defaults on)");
DemoAppProps noKey = new DemoAppProps();
assertFalse(new DemoAnalyticsHead(noKey, settings(Map.of("analytics.enabled", true))).render(ctx)
.contains("data-demo-analytics"), "no app-level key, no script");
assertFalse(new DemoAnalyticsHead(props, settings(Map.of("notice.enabled", false))).render(ctx)
.contains("demo.css"), "notice off, no stylesheet");
}
@Test
void headEscapesTheGeneratorLabelAndDeclaresItsSettingsFile() {
DemoAppProps props = new DemoAppProps();
props.getGenerator().setLabel("<script>x</script>");
HeadContext ctx = new HeadContext(SITE, PAGE, Locale.ENGLISH, null, null, List.of(), false, false);
DemoAnalyticsHead head = new DemoAnalyticsHead(props, settings(Map.of()));
String out = head.render(ctx);
assertTrue(out.contains("&lt;script&gt;"), "label escaped");
assertFalse(out.contains("<script>x</script>"), "raw label not emitted");
assertEquals(List.of("plugins/runway-demo.yml"), head.headInputs("acme"));
}
// --- ContentWidget: notice -------------------------------------------------------------------------
@Test
void noticeRendersWhenEnabledAndIsEmptyWhenDisabled() {
WidgetView view = new WidgetView(SITE, PAGE, Locale.ENGLISH, "n1", false, Map.of());
RenderFragment f = new DemoNoticeWidget(new DemoAppProps(),
settings(Map.of("notice.enabled", true, "notice.style", "warning")), kernel).render(view);
assertFalse(f.isEmpty());
assertTrue(f.html().contains("rw-demo-notice-warning"), f.html());
assertTrue(f.html().contains("instance &quot;n1&quot;") && f.html().contains("site &quot;Acme&quot;"),
"the fallback text formats its arguments: " + f.html());
assertTrue(new DemoNoticeWidget(new DemoAppProps(), settings(Map.of("notice.enabled", false)), kernel)
.render(view).isEmpty(), "disabled notice renders empty");
}
@Test
void noticeUsesTheSitesMessageInTheVisitorsLocaleAndEscapesIt() {
kernel.message("acme", "runwaydemo.notice.body", "<b>Aviso</b> {0} en {1}");
WidgetView view = new WidgetView(SITE, PAGE, Locale.of("es"), "n1", false, Map.of());
String html = new DemoNoticeWidget(new DemoAppProps(), settings(Map.of()), kernel).render(view).html();
assertTrue(html.contains("&lt;b&gt;Aviso&lt;/b&gt; n1 en Acme"), html);
}
@Test
void noticeFallsBackToInfoForAnUnknownStyleAndClampsMaxChars() {
WidgetView view = new WidgetView(SITE, PAGE, Locale.ENGLISH, "n1", false, Map.of());
String bad = new DemoNoticeWidget(new DemoAppProps(), settings(Map.of("notice.style", "x\" onclick=\"y")),
kernel).render(view).html();
assertTrue(bad.contains("rw-demo-notice-info\""), bad);
String truncated = new DemoNoticeWidget(new DemoAppProps(), settings(Map.of("notice.max-chars", 10L)), kernel)
.render(view).html();
assertTrue(truncated.contains(">This is th…<"), "truncated with an ellipsis: " + truncated);
String clamped = new DemoNoticeWidget(new DemoAppProps(), settings(Map.of("notice.max-chars", -5L)), kernel)
.render(view).html();
assertTrue(clamped.contains(">T…<"), "a hand-edited negative cap is clamped to 1: " + clamped);
}
@Test
void aChromeNoticeShowsTheAppLevelBanner() {
DemoAppProps props = new DemoAppProps();
props.getBanner().setText("Maintenance tonight");
WidgetView chrome = new WidgetView(SITE, PAGE, Locale.ENGLISH, "top", true, Map.of());
assertTrue(new DemoNoticeWidget(props, settings(Map.of()), kernel).render(chrome).html()
.contains("Maintenance tonight"));
props.getBanner().setEnabled(false);
assertFalse(new DemoNoticeWidget(props, settings(Map.of()), kernel).render(chrome).html()
.contains("Maintenance tonight"), "a disabled banner leaves the ordinary notice text");
}
// --- ContentWidget: feedback form ------------------------------------------------------------------
private static WidgetView feedbackView(Map<String, String> query, String path) {
return new WidgetView(SITE, PAGE, Locale.ENGLISH, "page", false, Map.of(), query, path);
}
@Test
void feedbackFormPostsToTheAnonymousRouteWithReturnPathHoneypotAndNoCsrfField() {
String html = new DemoFeedbackWidget(settings(Map.of()), kernel).render(feedbackView(Map.of(), "/demo"))
.html();
assertTrue(html.contains("<form method=\"post\" action=\"/demo/feedback\">"), html);
assertTrue(html.contains("name=\"return\" value=\"/demo\""), html);
assertTrue(html.contains("name=\"message\""), html);
assertTrue(html.contains("name=\"website\"") && html.contains("rw-demo-hp"), "honeypot present");
assertFalse(html.contains("_csrf"), "a shared, cacheable page carries no per-session token");
assertFalse(html.contains("role=\"status\""), "no outcome without the flag");
}
@Test
void feedbackShowsTheOutcomeFlagAndEscapesTheReturnPath() {
DemoFeedbackWidget widget = new DemoFeedbackWidget(settings(Map.of()), kernel);
assertTrue(widget.render(feedbackView(Map.of("demo-feedback", "thanks"), "/x")).html()
.contains("Thank you"));
assertTrue(widget.render(feedbackView(Map.of("demo-feedback", "invalid"), "/x")).html()
.contains("Please write a message first."));
assertTrue(widget.render(feedbackView(Map.of("demo-feedback", "limited"), "/x")).html()
.contains("Too many messages"));
assertFalse(widget.render(feedbackView(Map.of("demo-feedback", "<b>"), "/x")).html()
.contains("role=\"status\""), "an unknown flag shows nothing");
String html = widget.render(feedbackView(Map.of(), "/a\"b")).html();
assertTrue(html.contains("value=\"/a&quot;b\""), html);
assertTrue(widget.render(feedbackView(Map.of(), "")).html().contains("name=\"return\" value=\"/\""),
"an unknown path returns to the home page");
}
@Test
void feedbackIsEmptyWhenTheSiteTurnedItOff() {
assertTrue(new DemoFeedbackWidget(settings(Map.of("feedback.enabled", false)), kernel)
.render(feedbackView(Map.of(), "/demo")).isEmpty());
}
// --- PageQualityCheck ------------------------------------------------------------------------------
@Test
void qualityFlagsLongTitleMissingDescriptionAndMissingH1() {
PageMeta longTitle = new PageMeta("p", "x".repeat(80), "", List.of(Locale.ENGLISH), Locale.ENGLISH, true, false);
PageView page = new PageView(SITE, longTitle, Locale.ENGLISH, "u", "<html><body>no heading</body></html>");
List<String> codes = new DemoMetaLengthCheck(settings(Map.of())).inspect(page).stream()
.map(Finding::code).toList();
assertEquals(List.of("title.too-long", "description.missing", "h1.missing"), codes);
}
@Test
void qualityRatioScalesTheTitleLimitAndIgnoreCodesSuppress() {
PageMeta title70 = new PageMeta("p", "x".repeat(70), "d", List.of(Locale.ENGLISH), Locale.ENGLISH, true, false);
PageView page = new PageView(SITE, title70, Locale.ENGLISH, "u", "<h1>t</h1>");
assertTrue(new DemoMetaLengthCheck(settings(Map.of("quality.title-warn-ratio", "1.5"))).inspect(page)
.isEmpty(), "70 chars is under 60 × 1.5");
assertEquals(1, new DemoMetaLengthCheck(settings(Map.of())).inspect(page).size());
PageView noH1 = new PageView(SITE, title70, Locale.ENGLISH, "u", "<p>no h1</p>");
List<String> codes = new DemoMetaLengthCheck(settings(Map.of("quality.ignore-codes",
"title.too-long, h1.missing"))).inspect(noH1).stream().map(Finding::code).toList();
assertTrue(codes.isEmpty(), "a comma-separated ignore list (with spaces) suppresses both: " + codes);
}
@Test
void qualityCleanPageHasNoFindings() {
PageView page = new PageView(SITE, PAGE, Locale.ENGLISH, "u", "<html><H1>About</H1></html>");
assertTrue(new DemoMetaLengthCheck(settings(Map.of())).inspect(page).isEmpty());
}
// --- EndpointContributor ---------------------------------------------------------------------------
private DemoEndpoints endpoints(FakePluginSettings settings, AtomicLong clock) {
return new DemoEndpoints(kernel, notes, kernel, settings, clock::get);
}
private static RouteRequest get(String path) {
return new RouteRequest(SITE, Locale.ENGLISH, "GET", path, Map.of("q", List.of("1")),
Map.of("X-Test", "yes"), null, null, "203.0.113.9", "https://acme.test");
}
private static RouteRequest post(String path, Map<String, List<String>> form, String clientIp) {
return new RouteRequest(SITE, Locale.ENGLISH, "POST", path, Map.of(), Map.of(), null, form, clientIp,
"https://acme.test");
}
private static String body(RouteResponse r) {
return new String(r.body(), StandardCharsets.UTF_8);
}
@Test
void routesAreThreeGetsAndOneAnonymousPost() {
List<Route> routes = endpoints(settings(Map.of()), new AtomicLong()).routes();
assertEquals(List.of("GET /demo/hello.txt", "GET /demo/echo.json", "GET /demo/notes.json",
"POST /demo/feedback"), routes.stream().map(r -> r.method() + " " + r.pathPattern()).toList());
assertEquals(List.of(false, false, false, true), routes.stream().map(Route::anonymous).toList(),
"only the visitor form is anonymous");
}
@Test
void helloIsLocalizedForTheRequestLocale() {
kernel.message("acme", "runwaydemo.hello", "¡Hola!");
RouteResponse hello = endpoints(settings(Map.of()), new AtomicLong()).handle(get("/demo/hello.txt"));
assertEquals(200, hello.status());
assertTrue(body(hello).startsWith("¡Hola!\nsite: Acme (acme)"), body(hello));
assertTrue(body(hello).contains("origin: https://acme.test"), body(hello));
}
@Test
void echoShowsWhatTheHostPutInTheRequestWithLowercaseHeaderNames() {
RouteResponse echo = endpoints(settings(Map.of()), new AtomicLong()).handle(get("/demo/echo.json"));
assertEquals(200, echo.status());
String json = body(echo);
assertTrue(json.contains("\"path\":\"/demo/echo.json\""), json);
// Since SPI 0.5.0 the host hands header names in lower case (lookups ignore case).
assertTrue(json.contains("\"x-test\":\"yes\""), "headers echoed by their lowercase name: " + json);
assertFalse(json.contains("X-Test"), json);
assertTrue(json.contains("\"clientIp\":\"203.0.113.9\"") && json.contains("\"origin\":\"https://acme.test\""),
json);
assertTrue(json.contains("\"form\":{}") && json.contains("\"param.q\":\"1\""), json);
}
@Test
void notesEndpointIsPermissionGated() {
DemoEndpoints ep = endpoints(settings(Map.of()), new AtomicLong());
assertEquals(403, ep.handle(get("/demo/notes.json")).status(), "denied without the permission");
kernel.grant("runway-demo|manage-notes");
RouteResponse ok = ep.handle(get("/demo/notes.json"));
assertEquals(200, ok.status());
assertTrue(body(ok).contains("\"count\":1"), "the welcome note: " + body(ok));
}
@Test
void aWrongMethodOrUnknownPathIsNotFound() {
DemoEndpoints ep = endpoints(settings(Map.of()), new AtomicLong());
assertEquals(404, ep.handle(post("/demo/hello.txt", Map.of(), null)).status());
assertEquals(404, ep.handle(get("/demo/feedback")).status(), "a GET submits nothing");
assertEquals(404, ep.handle(get("/demo/other")).status());
}
@Test
void feedbackStoresTheMessageAsAVisitorNoteAndRedirectsWithOnlyTheOutcome() {
DemoEndpoints ep = endpoints(settings(Map.of()), new AtomicLong());
RouteResponse r = ep.handle(post("/demo/feedback", Map.of("message", List.of(" Nice site! "),
"return", List.of("/demo"), "website", List.of("")), "198.51.100.1"));
assertEquals(303, r.status());
assertEquals("/demo?demo-feedback=thanks", r.headers().get("Location"));
Note last = notes.list("acme").getLast();
assertEquals("Nice site!", last.text());
assertEquals(Note.ORIGIN_VISITOR, last.origin());
}
@Test
void feedbackHoneypotBlankAndForeignReturnAreHandled() {
DemoEndpoints ep = endpoints(settings(Map.of()), new AtomicLong());
int before = notes.count("acme");
RouteResponse bot = ep.handle(post("/demo/feedback", Map.of("message", List.of("spam"),
"website", List.of("http://spam")), "198.51.100.2"));
assertEquals("/?demo-feedback=thanks", bot.headers().get("Location"), "a bot is told it worked");
RouteResponse blank = ep.handle(post("/demo/feedback", Map.of("message", List.of(" "),
"return", List.of("//evil.example/x")), "198.51.100.2"));
assertEquals("/?demo-feedback=invalid", blank.headers().get("Location"), "never an off-site redirect");
assertEquals(before, notes.count("acme"), "neither was stored");
}
@Test
void feedbackReadsTheBodyOnlyNeverTheQueryString() {
DemoEndpoints ep = endpoints(settings(Map.of()), new AtomicLong());
RouteRequest viaQuery = new RouteRequest(SITE, Locale.ENGLISH, "POST", "/demo/feedback",
Map.of("message", List.of("in the URL")), Map.of(), null, Map.of(), "198.51.100.3", "");
assertEquals("/?demo-feedback=invalid", ep.handle(viaQuery).headers().get("Location"));
}
@Test
void feedbackIsRateLimitedPerClientAddressWithASlidingWindow() {
AtomicLong clock = new AtomicLong(1_000_000);
DemoEndpoints ep = endpoints(settings(Map.of()), clock);
Map<String, List<String>> form = Map.of("message", List.of("hi"));
for (int i = 0; i < DemoEndpoints.FEEDBACK_PER_WINDOW; i++) {
assertEquals("/?demo-feedback=thanks", ep.handle(post("/demo/feedback", form, "192.0.2.7"))
.headers().get("Location"));
}
assertEquals("/?demo-feedback=limited", ep.handle(post("/demo/feedback", form, "192.0.2.7"))
.headers().get("Location"), "the sixth in the window is refused");
assertEquals("/?demo-feedback=thanks", ep.handle(post("/demo/feedback", form, "192.0.2.8"))
.headers().get("Location"), "another address has its own budget");
clock.addAndGet(DemoEndpoints.WINDOW_MILLIS);
assertEquals("/?demo-feedback=thanks", ep.handle(post("/demo/feedback", form, "192.0.2.7"))
.headers().get("Location"), "the window slides");
}
@Test
void feedbackIsNotFoundWhenTheSiteTurnedItOff() {
RouteResponse r = endpoints(settings(Map.of("feedback.enabled", false)), new AtomicLong())
.handle(post("/demo/feedback", Map.of("message", List.of("hi")), "192.0.2.9"));
assertEquals(404, r.status());
}
@Test
void safeLocalPathRefusesEverythingButALocalPath() {
assertEquals("/a/b?c=1", DemoEndpoints.safeLocalPath("/a/b?c=1"));
for (String bad : new String[] {null, "", "a", "//x", "/x://y", "/a b", "/a\\b", "/a\nb", "https://x"}) {
assertEquals("/", DemoEndpoints.safeLocalPath(bad), String.valueOf(bad));
}
}
}
@@ -0,0 +1,120 @@
package mx.quest.demo;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.io.IOException;
import java.lang.reflect.Method;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.HashSet;
import java.util.Set;
import java.util.TreeSet;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Stream;
import org.junit.jupiter.api.Test;
import org.springframework.web.bind.annotation.PostMapping;
/**
* The shipped templates as files: every state-changing action of the console screen is reached by a
* {@code <form method="post">} that carries the console session's CSRF token, no link points at one (a link is a
* {@code GET}), every form action is a real handler, and no decoupled template repeats an {@code id} (a hard
* Thymeleaf error that would 500 the screen).
*/
class DemoTemplatesTest {
private static final Pattern FORM = Pattern.compile("(?s)<form\\b([^>]*)>(.*?)</form>");
private static final String TOKEN_BINDING =
"th:attr=\"name=${_csrf != null ? _csrf.parameterName : '_csrf'},value=${_csrf != null ? _csrf.token : ''}\"";
private static String read(String file) throws IOException {
return Files.readString(Path.of("templates", file), StandardCharsets.UTF_8).replaceAll("(?s)<!--.*?-->", "");
}
private static Set<String> postActions() {
Set<String> paths = new TreeSet<>();
for (Method m : DemoConsoleController.class.getDeclaredMethods()) {
PostMapping post = m.getAnnotation(PostMapping.class);
if (post != null) {
for (String p : post.value()) {
paths.add(DemoConsoleController.BASE + p);
}
}
}
return paths;
}
@Test
void everyPostActionHasAPostFormCarryingTheCsrfToken() throws IOException {
assertEquals(Set.of("/__admin/runway-demo/notes", "/__admin/runway-demo/showcase",
"/__admin/runway-demo/showcase/unpublish", "/__admin/runway-demo/install-page",
"/__admin/runway-demo/catalog/refresh"), postActions());
String html = read("console.html");
Set<String> formed = new HashSet<>();
Matcher form = FORM.matcher(html);
while (form.find()) {
String attrs = form.group(1);
Matcher action = Pattern.compile("action=\"([^\"]+)\"").matcher(attrs);
assertTrue(action.find(), "every form names its action: " + attrs);
if (attrs.contains("method=\"get\"")) {
assertEquals(DemoConsoleController.BASE, action.group(1), "the only GET form is the read-only check");
assertFalse(form.group(2).contains("_csrf"), "a GET form must not put the token in a URL");
continue;
}
assertTrue(attrs.contains("method=\"post\""), attrs);
assertTrue(postActions().contains(action.group(1)), "a form posts to a real handler: " + action.group(1));
assertTrue(form.group(2).contains("class=\"rd-csrf\" type=\"hidden\" name=\"_csrf\""),
action.group(1) + "'s form carries the hidden CSRF field");
formed.add(action.group(1));
}
assertEquals(postActions(), formed, "every action is reachable from the screen");
assertTrue(read("console.th.xml").contains("<attr sel=\".rd-csrf\"\n " + TOKEN_BINDING + "/>"),
"the .rd-csrf fields are bound to the console session's token");
}
@Test
void noLinkPointsAtAnAction() throws IOException {
try (Stream<Path> files = Files.list(Path.of("templates"))) {
for (Path file : files.filter(p -> p.toString().endsWith(".html")).toList()) {
String html = read(file.getFileName().toString());
for (String action : postActions()) {
assertFalse(html.contains("href=\"" + action), file + " links to " + action);
}
}
}
}
@Test
void noTemplateRepeatsAnId() throws IOException {
try (Stream<Path> files = Files.list(Path.of("templates"))) {
for (Path file : files.filter(p -> p.toString().endsWith(".html")).toList()) {
Matcher ids = Pattern.compile("\\bid=\"([^\"]+)\"").matcher(read(file.getFileName().toString()));
Set<String> seen = new HashSet<>();
while (ids.find()) {
assertTrue(seen.add(ids.group(1)), file + ": duplicate id " + ids.group(1));
}
}
}
}
@Test
void everySelectorInTheLogicMatchesTheMarkup() throws IOException {
try (Stream<Path> files = Files.list(Path.of("templates"))) {
for (Path logic : files.filter(p -> p.toString().endsWith(".th.xml")).toList()) {
String name = logic.getFileName().toString().replace(".th.xml", "");
String html = read(name + ".html");
Matcher sel = Pattern.compile("sel=\"([^\"]+)\"").matcher(read(name + ".th.xml"));
while (sel.find()) {
for (String part : sel.group(1).split("//")) {
String token = part.startsWith("#") ? "id=\"" + part.substring(1) + "\""
: part.startsWith(".") ? part.substring(1) : "<" + part;
assertTrue(html.contains(token), name + ": selector " + sel.group(1) + " matches nothing");
}
}
}
}
}
}