Runway 1.1.0

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

No files matched your search

@@ -0,0 +1,44 @@
package mx.quest.demodatabase;
import mx.quest.database.spi.Databases;
import mx.quest.runway.spi.CaptchaService;
import mx.quest.runway.spi.service.Messages;
import mx.quest.runway.spi.service.PluginSettings;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* The worked example of a database consumer. {@link Databases} arrives by type from the database plugin; this
* plugin's {@code plugin.yml} declares {@code requires: database}, so it never loads without it.
*/
@Configuration(proxyBeanMethods = false)
public class DemoDatabaseConfig {
@Bean
public GuestbookConsumer runwayDemoDatabaseConsumer() {
return new GuestbookConsumer();
}
@Bean
public GuestbookStore runwayDemoDatabaseStore(Databases databases, GuestbookConsumer runwayDemoDatabaseConsumer) {
return new GuestbookStore(databases, runwayDemoDatabaseConsumer);
}
@Bean
public GuestbookEndpoints runwayDemoDatabaseEndpoints(GuestbookStore runwayDemoDatabaseStore,
PluginSettings settings, CaptchaService captcha) {
return new GuestbookEndpoints(runwayDemoDatabaseStore, settings, captcha);
}
@Bean
public GuestbookWidget runwayDemoDatabaseWidget(PluginSettings settings, Messages messages,
CaptchaService captcha) {
return new GuestbookWidget(settings, messages, captcha);
}
@Bean
public GuestbookConsoleController runwayDemoDatabaseConsoleController(GuestbookStore runwayDemoDatabaseStore,
Messages messages) {
return new GuestbookConsoleController(runwayDemoDatabaseStore, messages);
}
}
@@ -0,0 +1,82 @@
package mx.quest.demodatabase;
import mx.quest.database.spi.DatabaseException;
import mx.quest.database.spi.PluginDatabase;
import mx.quest.runway.spi.service.ConsoleScreen;
import mx.quest.runway.spi.service.Messages;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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.servlet.mvc.support.RedirectAttributes;
/**
* The site console's guestbook screen: the entries a page at a time, and a delete button for each. Gated by
* {@code runway-demo-database|manage}; the site is always the one the console manages ({@code currentSite()}), and
* deleting is a CSRF-checked POST.
*/
@Controller
@ConsoleScreen
@RequestMapping(GuestbookConsoleController.BASE)
public class GuestbookConsoleController {
static final String BASE = "/__admin/runway-demo-database";
static final String GATE = "@authz.may('runway-demo-database|manage')";
static final String FLASH = "guestbookFlash";
static final String FLASH_ERROR = "guestbookError";
private static final Logger log = LoggerFactory.getLogger(GuestbookConsoleController.class);
/** What the screen shows. */
public record Screen(boolean available, GuestbookStore.Page page, int count) {
}
private final GuestbookStore store;
private final Messages messages;
public GuestbookConsoleController(GuestbookStore store, Messages messages) {
this.store = store;
this.messages = messages;
}
@GetMapping
@PreAuthorize(GATE)
public String list(@RequestParam(name = "page", defaultValue = "0") int page, Model model) {
PluginDatabase db = store.db();
Screen screen = new Screen(false, new GuestbookStore.Page(java.util.List.of(), 0, false), 0);
if (db.available()) {
try {
screen = new Screen(true, store.page(db.currentSite(), Math.max(0, page), 50),
store.count(db.currentSite()));
} catch (DatabaseException e) {
log.warn("runway-demo-database: the guestbook could not be read: {}", e.getMessage());
}
}
model.addAttribute("gb", screen);
model.addAttribute(ConsoleScreen.CONTENT_TEMPLATE, "__plugin__/runway-demo-database/console");
model.addAttribute(ConsoleScreen.PAGE_TITLE_KEY, "guestbook.console.title");
return ConsoleScreen.LAYOUT_VIEW;
}
@PostMapping("/delete")
@PreAuthorize(GATE)
public String delete(@RequestParam(name = "id") long id, RedirectAttributes flash) {
PluginDatabase db = store.db();
try {
boolean deleted = db.available() && store.delete(db.currentSite(), id);
flash.addFlashAttribute(deleted ? FLASH : FLASH_ERROR, deleted
? messages.console("guestbook.console.deleted", "Entry deleted.")
: messages.console("guestbook.console.gone", "That entry is no longer there."));
} catch (DatabaseException e) {
log.warn("runway-demo-database: a guestbook entry could not be deleted: {}", e.getMessage());
flash.addFlashAttribute(FLASH_ERROR, messages.console("guestbook.console.failed",
"The database could not be reached."));
}
return "redirect:" + BASE;
}
}
@@ -0,0 +1,24 @@
package mx.quest.demodatabase;
import java.util.Set;
import mx.quest.database.spi.DatabaseConsumer;
import mx.quest.database.spi.Scope;
/**
* Declares that this plugin keeps data in the database: per site only. The database plugin checks the claim against
* the jar this class was loaded from and reads the migration scripts under {@code db/runway-demo-database/} from it.
*/
public class GuestbookConsumer implements DatabaseConsumer {
public static final String PLUGIN_ID = "runway-demo-database";
@Override
public String pluginId() {
return PLUGIN_ID;
}
@Override
public Set<Scope.Kind> scopes() {
return Set.of(Scope.Kind.SITE);
}
}
@@ -0,0 +1,244 @@
package mx.quest.demodatabase;
import java.util.ArrayDeque;
import java.util.ArrayList;
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.database.spi.DatabaseException;
import mx.quest.database.spi.PluginDatabase;
import mx.quest.runway.spi.CaptchaService;
import mx.quest.runway.spi.EndpointContributor;
import mx.quest.runway.spi.model.CaptchaWidget;
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.SiteRef;
import mx.quest.runway.spi.model.SurfacePosture;
import mx.quest.runway.spi.service.PluginSettings;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import tools.jackson.databind.json.JsonMapper;
/**
* The guestbook's two public routes.
*
* <ul>
* <li>{@code POST /guestbook/sign} — an anonymous form route (no CSRF token: the form sits on a page every visitor
* shares). Its guards: a honeypot field, length caps, the site's CAPTCHA through {@link CaptchaService} when the
* site has one, a per-address sliding window keyed by the gated client address, and the per-site row cap the
* store applies in the same transaction. Fields come from the form body
* only; the answer is a {@code 303} back to the page with an outcome flag, never a submitted value.</li>
* <li>{@code GET /guestbook/entries.json} — the entries, a page at a time, with {@code Cache-Control: no-store}.
* The page itself renders only a static shell (the widget's output never depends on the rows), so the page
* stays cacheable and its ETag honest while new entries show at once.</li>
* </ul>
*
* The site always comes from the request ({@link RouteRequest#site()}), never from a parameter.
*/
public class GuestbookEndpoints implements EndpointContributor {
private static final Logger log = LoggerFactory.getLogger(GuestbookEndpoints.class);
static final String SIGN_PATH = "/guestbook/sign";
static final String ENTRIES_PATH = "/guestbook/entries.json";
static final String OUTCOME_PARAM = "guestbook";
static final int PAGE_SIZE = 20;
static final int PAGE_MAX = 500;
static final int SIGN_PER_WINDOW = 5;
static final long WINDOW_MILLIS = TimeUnit.MINUTES.toMillis(1);
private static final int MAX_TRACKED = 10_000;
private final GuestbookStore store;
private final PluginSettings settings;
private final CaptchaService captcha;
private final LongSupplier clockMillis;
private final JsonMapper json = JsonMapper.builder().build();
private final ConcurrentMap<String, Deque<Long>> recent = new ConcurrentHashMap<>();
public GuestbookEndpoints(GuestbookStore store, PluginSettings settings, CaptchaService captcha) {
this(store, settings, captcha, System::currentTimeMillis);
}
GuestbookEndpoints(GuestbookStore store, PluginSettings settings, CaptchaService captcha,
LongSupplier clockMillis) {
this.store = store;
this.settings = settings;
this.captcha = captcha;
this.clockMillis = clockMillis;
}
@Override
public String key() {
return "runway-demo-database/guestbook";
}
@Override
public List<Route> routes() {
return List.of(new Route("GET", ENTRIES_PATH, Realm.TENANT, SurfacePosture.safeDefault()),
Route.anonymousPost(SIGN_PATH, SurfacePosture.safeDefault()));
}
@Override
public RouteResponse handle(RouteRequest req) {
return switch (req.method().toUpperCase(Locale.ROOT) + " " + req.path()) {
case "GET " + ENTRIES_PATH -> entries(req);
case "POST " + SIGN_PATH -> sign(req);
default -> RouteResponse.notFound();
};
}
static boolean enabled(PluginSettings settings, String siteId) {
return settings.site(siteId).bool("enabled", true);
}
static int cap(PluginSettings settings, String siteId) {
return (int) settings.site(siteId).integer("maxEntries", 500, 10, GuestbookStore.ENTRIES_CEILING);
}
private RouteResponse entries(RouteRequest req) {
String siteId = req.site().id();
if (!enabled(settings, siteId)) {
return RouteResponse.notFound();
}
PluginDatabase db = store.db();
Map<String, Object> payload = new LinkedHashMap<>();
if (!db.available()) {
payload.put("available", false);
return json(503, payload);
}
int page = 0;
try {
page = Math.min(PAGE_MAX, Math.max(0, Integer.parseInt(req.param("page").orElse("0"))));
} catch (NumberFormatException ignored) {
// the first page
}
try {
GuestbookStore.Page p = store.page(db.site(new SiteRef(siteId)), page, PAGE_SIZE);
List<Map<String, Object>> entries = new ArrayList<>();
for (GuestbookStore.Entry e : p.entries()) {
entries.add(Map.of("name", e.name(), "message", e.message(), "at", e.at().toString()));
}
payload.put("available", true);
payload.put("page", p.page());
payload.put("more", p.more());
payload.put("entries", entries);
return json(200, payload);
} catch (DatabaseException e) {
log.warn("runway-demo-database: the guestbook of site '{}' could not be read: {}", siteId,
e.getMessage());
payload.put("available", false);
return json(503, payload);
}
}
private RouteResponse sign(RouteRequest req) {
String siteId = req.site().id();
if (!enabled(settings, siteId)) {
return RouteResponse.notFound();
}
String back = safeLocalPath(field(req, "return"));
if (!field(req, "website").isEmpty()) {
return redirect(back, "thanks"); // a bot filled the honeypot: pretend success, keep nothing
}
String name = field(req, "name");
String message = field(req, "message");
if (name.isEmpty() || message.isEmpty() || name.length() > GuestbookStore.NAME_MAX
|| message.length() > GuestbookStore.MESSAGE_MAX || hasControl(name)
|| hasControlBesidesLines(message)) {
return redirect(back, "invalid");
}
// The site's challenge, when it has one (the kernel's default answers "inactive"); verified with the gated
// client address, as the provider expects the visitor's.
CaptchaWidget challenge = captcha.widgetForSite(siteId);
if (challenge.active() && !captcha.verify(siteId, field(req, challenge.tokenField()), req.clientIp())) {
return redirect(back, "captcha");
}
if (!allow(req.clientIp())) {
return redirect(back, "limited");
}
PluginDatabase db = store.db();
if (!db.available()) {
return redirect(back, "unavailable");
}
try {
store.add(db.site(new SiteRef(siteId)), name, message, cap(settings, siteId));
} catch (DatabaseException e) {
log.warn("runway-demo-database: a guestbook entry for site '{}' was not kept: {}", siteId, e.getMessage());
return redirect(back, "unavailable");
}
return redirect(back, "thanks");
}
/** A sliding-window limit per gated client address; an unknown address shares one bucket. */
boolean allow(String clientIp) {
long now = clockMillis.getAsLong();
if (recent.size() > MAX_TRACKED) {
recent.entrySet().removeIf(e -> {
synchronized (e.getValue()) {
return e.getValue().isEmpty() || now - e.getValue().peekLast() >= WINDOW_MILLIS;
}
});
}
Deque<Long> times = recent.computeIfAbsent(clientIp == null ? "unknown" : clientIp, k -> new ArrayDeque<>());
synchronized (times) {
while (!times.isEmpty() && now - times.peekFirst() >= WINDOW_MILLIS) {
times.pollFirst();
}
if (times.size() >= SIGN_PER_WINDOW) {
return false;
}
times.addLast(now);
return true;
}
}
private static boolean hasControl(String s) {
return s.chars().anyMatch(Character::isISOControl);
}
/**
* A control character other than a line break or a tab. A message may span lines; anything else is refused
* here, as "invalid", before the database: PostgreSQL rejects U+0000 in text, and the visitor would otherwise
* be told the database is unavailable.
*/
private static boolean hasControlBesidesLines(String s) {
return s.chars().anyMatch(c -> Character.isISOControl(c) && c != '\n' && c != '\r' && c != '\t');
}
private static String field(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, 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("?") ? "&" : "?") + OUTCOME_PARAM + "=" + outcome;
return new RouteResponse(303, Map.of("Location", location, "Cache-Control", "no-store"), new byte[0]);
}
private RouteResponse json(int status, Object payload) {
return new RouteResponse(status, Map.of("Content-Type", "application/json; charset=utf-8",
"Cache-Control", "no-store"), json.writeValueAsBytes(payload));
}
}
@@ -0,0 +1,139 @@
package mx.quest.demodatabase;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.TimeZone;
import mx.quest.database.spi.Databases;
import mx.quest.database.spi.Dialect;
import mx.quest.database.spi.PluginDatabase;
import mx.quest.database.spi.Scope;
/**
* The guestbook's SQL: the one place this plugin touches its table. Plain JDBC through the database plugin's scopes:
* one connection and one transaction per call, so reading back the new id with {@link Dialect#lastValue} is reliable.
*
* <p>The same SQL runs on PostgreSQL and MariaDB: ids from {@link Dialect#nextValue}, paging with
* {@link Dialect#limitOffset}, times written by the server ({@code CURRENT_TIMESTAMP(6)}, in UTC on both) and read
* as instants.
*/
public class GuestbookStore {
static final String TABLE = "runway_demo_database__entry";
static final String SEQUENCE = "runway_demo_database__entry_seq";
static final int NAME_MAX = 80;
static final int MESSAGE_MAX = 1000;
private static final Calendar UTC = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
/** One entry, as visitors see it. */
public record Entry(long id, String name, String message, Instant at) {
}
/** A page of entries, newest first, and whether an older page exists. */
public record Page(List<Entry> entries, int page, boolean more) {
}
private final Databases databases;
private final GuestbookConsumer consumer;
private volatile PluginDatabase db;
public GuestbookStore(Databases databases, GuestbookConsumer consumer) {
this.databases = databases;
this.consumer = consumer;
}
/** This plugin's handle, asked for on first use (never while the platform is starting). */
public PluginDatabase db() {
PluginDatabase handle = db;
if (handle == null) {
handle = databases.of(consumer);
db = handle;
}
return handle;
}
/**
* Adds an entry and, in the same transaction, deletes the oldest ones beyond {@code cap}, so a busy or abused
* guestbook never grows past its limit.
*
* @return the new entry's id
*/
public long add(Scope site, String name, String message, int cap) {
Dialect d = db().dialect();
return site.transaction(c -> {
try (PreparedStatement ps = c.prepareStatement("INSERT INTO " + TABLE + " (id, version, name, message, "
+ "created_at, updated_at, updater) VALUES (" + d.nextValue(SEQUENCE) + ", 0, ?, ?, "
+ "CURRENT_TIMESTAMP(6), CURRENT_TIMESTAMP(6), 'visitor')")) {
ps.setString(1, name);
ps.setString(2, message);
ps.executeUpdate();
}
long id = d.lastValue(c, SEQUENCE);
Long cutoff = null;
try (PreparedStatement ps = c.prepareStatement("SELECT id FROM " + TABLE + " ORDER BY id DESC "
+ d.limitOffset(1, cap)); ResultSet rs = ps.executeQuery()) {
if (rs.next()) {
cutoff = rs.getLong(1);
}
}
if (cutoff != null) {
try (PreparedStatement ps = c.prepareStatement("DELETE FROM " + TABLE + " WHERE id <= ?")) {
ps.setLong(1, cutoff);
ps.executeUpdate();
}
}
return id;
});
}
/** The most entries a site can hold (the top of the {@code maxEntries} setting's range). */
static final int ENTRIES_CEILING = 10_000;
/**
* One page of entries, newest first. A page past {@link #ENTRIES_CEILING} is empty without a query: the offset is
* computed in {@code long}, so a huge page number from a URL cannot overflow into a negative offset.
*/
public Page page(Scope site, int page, int size) {
Dialect d = db().dialect();
int p = Math.max(0, page);
if ((long) p * size >= ENTRIES_CEILING) {
return new Page(List.of(), p, false);
}
return site.read(c -> {
List<Entry> entries = new ArrayList<>();
try (PreparedStatement ps = c.prepareStatement("SELECT id, name, message, created_at FROM " + TABLE
+ " ORDER BY id DESC " + d.limitOffset(size + 1, p * size)); ResultSet rs = ps.executeQuery()) {
while (rs.next()) {
entries.add(new Entry(rs.getLong(1), rs.getString(2), rs.getString(3),
rs.getTimestamp(4, UTC).toInstant()));
}
}
boolean more = entries.size() > size;
return new Page(more ? List.copyOf(entries.subList(0, size)) : List.copyOf(entries), p, more);
});
}
/** Deletes one entry; false when it was not there. */
public boolean delete(Scope site, long id) {
return site.transaction(c -> {
try (PreparedStatement ps = c.prepareStatement("DELETE FROM " + TABLE + " WHERE id = ?")) {
ps.setLong(1, id);
return ps.executeUpdate() > 0;
}
});
}
/** How many entries a site has. */
public int count(Scope site) {
return site.read(c -> {
try (PreparedStatement ps = c.prepareStatement("SELECT COUNT(*) FROM " + TABLE);
ResultSet rs = ps.executeQuery()) {
rs.next();
return rs.getInt(1);
}
});
}
}
@@ -0,0 +1,111 @@
package mx.quest.demodatabase;
import java.util.Locale;
import mx.quest.runway.spi.CaptchaService;
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;
/**
* The guestbook widget ({@code data-widget="guestbook/<instance>"}): the signing form and an empty list that the
* plugin's script fills from {@code /guestbook/entries.json}.
*
* <p><b>Why the list is not rendered here.</b> A widget's output must depend only on what the page is rendered from
* (the site, the locale, the query, the widget's settings): the kernel caches pages and answers {@code 304} while
* their ETag holds. Rows read from the database here would hide new entries behind cached pages. So the page carries
* a static shell and the entries arrive from an endpoint that is never cached.
*/
public class GuestbookWidget implements ContentWidget {
static final String STATIC = "/__plugin/runway-demo-database/static";
private final PluginSettings settings;
private final Messages messages;
private final CaptchaService captcha;
public GuestbookWidget(PluginSettings settings, Messages messages, CaptchaService captcha) {
this.settings = settings;
this.messages = messages;
this.captcha = captcha;
}
@Override
public String key() {
return "guestbook";
}
@Override
public RenderFragment render(WidgetView view) {
String siteId = view.site().id();
if (!GuestbookEndpoints.enabled(settings, siteId)) {
return RenderFragment.empty();
}
Locale locale = view.locale();
String id = "rw-guestbook-" + view.instanceId().replaceAll("[^A-Za-z0-9_-]", "-");
String back = view.path().isBlank() ? "/" : view.path();
StringBuilder html = new StringBuilder()
.append("<link rel=\"stylesheet\" href=\"").append(STATIC).append("/guestbook.css\">")
.append("<section class=\"rw-guestbook\">");
String outcome = outcome(siteId, locale, view.query().get(GuestbookEndpoints.OUTCOME_PARAM));
if (!outcome.isEmpty()) {
html.append("<p class=\"rw-guestbook-notice\" role=\"status\">").append(Html.escape(outcome))
.append("</p>");
}
html.append("<form method=\"post\" action=\"").append(GuestbookEndpoints.SIGN_PATH).append("\">")
.append("<input type=\"hidden\" name=\"return\" value=\"").append(Html.escape(back)).append("\">")
.append("<label for=\"").append(id).append("-name\">")
.append(Html.escape(text(siteId, locale, "guestbook.name", "Your name"))).append("</label>")
.append("<input id=\"").append(id).append("-name\" name=\"name\" type=\"text\" maxlength=\"")
.append(GuestbookStore.NAME_MAX).append("\" required>")
.append("<label for=\"").append(id).append("-message\">")
.append(Html.escape(text(siteId, locale, "guestbook.message", "Message"))).append("</label>")
.append("<textarea id=\"").append(id).append("-message\" name=\"message\" rows=\"3\" maxlength=\"")
.append(GuestbookStore.MESSAGE_MAX).append("\" required></textarea>")
// The honeypot: off-screen for people and assistive technology, tempting for a form-filling bot.
.append("<div class=\"rw-guestbook-hp\" aria-hidden=\"true\"><label>Website <input type=\"text\" ")
.append("name=\"website\" tabindex=\"-1\" autocomplete=\"off\"></label></div>")
// The site's CAPTCHA challenge when it has one: trusted markup from the platform, empty otherwise.
.append(captcha.widgetForSite(siteId).html())
.append("<button type=\"submit\">")
.append(Html.escape(text(siteId, locale, "guestbook.sign", "Sign the guestbook")))
.append("</button></form>")
.append("<ol class=\"rw-guestbook-list\" data-src=\"").append(GuestbookEndpoints.ENTRIES_PATH)
.append("\" data-empty=\"").append(Html.escape(text(siteId, locale, "guestbook.empty",
"No entries yet. Be the first!")))
.append("\" data-unavailable=\"").append(Html.escape(text(siteId, locale, "guestbook.unavailable",
"This example needs the database, which is not available right now.")))
.append("\" data-more=\"").append(Html.escape(text(siteId, locale, "guestbook.more", "Older entries")))
.append("\" data-lang=\"").append(Html.escape(locale.toLanguageTag())).append("\"></ol>")
.append("</section><script src=\"").append(STATIC).append("/guestbook.js\" defer></script>");
return RenderFragment.of(html.toString());
}
private String outcome(String siteId, Locale locale, String outcome) {
if (outcome == null) {
return "";
}
return switch (outcome) {
case "thanks" -> text(siteId, locale, "guestbook.thanks", "Thank you for signing the guestbook.");
case "invalid" -> text(siteId, locale, "guestbook.invalid",
"Please give your name and a message (up to 80 and 1000 characters).");
case "limited" -> text(siteId, locale, "guestbook.limited",
"Too many entries from your address — please try again in a minute.");
case "captcha" -> text(siteId, locale, "guestbook.captcha", "Please complete the challenge and try again.");
case "unavailable" -> text(siteId, locale, "guestbook.unavailable",
"This example needs the database, which is not available right now.");
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,27 @@
package mx.quest.demodatabase;
/** HTML escaping for the little markup this plugin writes. */
final class Html {
private Html() {
}
static String escape(String value) {
if (value == null) {
return "";
}
StringBuilder out = new StringBuilder(value.length());
for (int i = 0; i < value.length(); i++) {
char c = value.charAt(i);
switch (c) {
case '&' -> out.append("&amp;");
case '<' -> out.append("&lt;");
case '>' -> out.append("&gt;");
case '"' -> out.append("&quot;");
case '\'' -> out.append("&#39;");
default -> out.append(c);
}
}
return out.toString();
}
}
@@ -0,0 +1,15 @@
-- The guestbook (MariaDB): the same table, columns and nullability as the PostgreSQL script, so a backup moves
-- between the two. TIMESTAMP(6) holds an instant (the session time zone is pinned to UTC).
CREATE SEQUENCE runway_demo_database__entry_seq
-- runway:next
CREATE TABLE runway_demo_database__entry (
id BIGINT PRIMARY KEY,
version INT NOT NULL DEFAULT 0,
name VARCHAR(80) NOT NULL,
message VARCHAR(1000) NOT NULL,
created_at TIMESTAMP(6) NOT NULL,
updated_at TIMESTAMP(6) NOT NULL,
updater VARCHAR(80) NOT NULL
) ENGINE=InnoDB
-- runway:next
CREATE INDEX runway_demo_database__entry_created ON runway_demo_database__entry (created_at)
@@ -0,0 +1,15 @@
-- The guestbook (PostgreSQL). Every object carries the plugin's prefix, runway_demo_database__.
-- Ids come from a sequence, never an identity column; the entity columns follow the house convention.
CREATE SEQUENCE runway_demo_database__entry_seq
-- runway:next
CREATE TABLE runway_demo_database__entry (
id BIGINT PRIMARY KEY,
version INTEGER NOT NULL DEFAULT 0,
name VARCHAR(80) NOT NULL,
message VARCHAR(1000) NOT NULL,
created_at TIMESTAMPTZ NOT NULL,
updated_at TIMESTAMPTZ NOT NULL,
updater VARCHAR(80) NOT NULL
)
-- runway:next
CREATE INDEX runway_demo_database__entry_created ON runway_demo_database__entry (created_at)
@@ -0,0 +1,83 @@
package mx.quest.demodatabase;
import static org.assertj.core.api.Assertions.assertThat;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Stream;
import mx.quest.database.spi.Databases;
import mx.quest.runway.spi.CaptchaService;
import mx.quest.runway.spi.ContentWidget;
import mx.quest.runway.spi.EndpointContributor;
import mx.quest.runway.spi.model.PageMeta;
import mx.quest.runway.spi.model.SiteView;
import mx.quest.runway.spi.model.WidgetView;
import mx.quest.runway.spi.service.PluginSettings;
import mx.quest.runway.spi.testkit.FakePluginSettings;
import mx.quest.runway.spi.testkit.FakeSiteServices;
import org.junit.jupiter.api.Test;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
class DemoDatabaseConfigTest {
@Test
void theConfigurationWiresFromTheDatabaseSpiAndKernelServicesAlone() {
try (AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext()) {
ctx.registerBean(PluginSettings.class, FakePluginSettings::new);
ctx.registerBean(FakeSiteServices.class, FakeSiteServices::new);
ctx.registerBean(CaptchaService.class, () -> GuestbookEndpointsTest.captcha(false, ""));
ctx.registerBean("databaseDatabases", Databases.class, GuestbookEndpointsTest::unavailable);
ctx.register(DemoDatabaseConfig.class);
ctx.refresh();
for (String name : ctx.getBeanDefinitionNames()) {
if (ctx.getBeanDefinition(name).getFactoryMethodName() != null
&& !name.equals("databaseDatabases")) {
assertThat(name).startsWith("runwayDemoDatabase");
}
}
assertThat(ctx.getBeansOfType(EndpointContributor.class)).hasSize(1);
assertThat(ctx.getBeansOfType(ContentWidget.class)).hasSize(1);
}
}
@Test
void theWidgetRendersAStaticShellWithEscapedTextAndNoRows() {
GuestbookWidget widget = new GuestbookWidget(new FakePluginSettings(), new FakeSiteServices(),
GuestbookEndpointsTest.captcha(true, "solved"));
SiteView site = new SiteView("acme", "Acme", Locale.ENGLISH, List.of(Locale.ENGLISH), null);
PageMeta page = new PageMeta("guests", "Guests", "", List.of(Locale.ENGLISH), Locale.ENGLISH, true, false);
WidgetView view = new WidgetView(site, page, Locale.ENGLISH, "g1", false, Map.of(),
Map.of("guestbook", "thanks"), "/guests\"<x>");
String html = widget.render(view).html();
assertThat(html).contains("action=\"/guestbook/sign\"", "data-src=\"/guestbook/entries.json\"",
"name=\"website\"", "guestbook.js", "role=\"status\"", "<div class=\"challenge\"></div>")
.contains("value=\"/guests&quot;&lt;x&gt;\"").doesNotContain("<x>");
}
@Test
void theCompiledClassesLinkNoHostInternals() throws Exception {
Path classes = Path.of("target", "classes");
Pattern host = Pattern.compile("mx[/.]quest[/.]runway[/.](?!spi[/.])[\\w/.$]*");
Pattern internal = Pattern.compile("mx[/.]quest[/.]database[/.](?!spi[/.])[\\w/.$]*");
List<String> problems = new ArrayList<>();
try (Stream<Path> files = Files.walk(classes)) {
for (Path f : files.filter(x -> x.toString().endsWith(".class")).toList()) {
String text = new String(Files.readAllBytes(f), StandardCharsets.ISO_8859_1);
for (Pattern p : List.of(host, internal)) {
Matcher m = p.matcher(text);
while (m.find()) {
problems.add(f + " → " + m.group());
}
}
}
}
assertThat(problems).as("only the Runway SPI and the database SPI").isEmpty();
}
}
@@ -0,0 +1,157 @@
package mx.quest.demodatabase;
import static org.assertj.core.api.Assertions.assertThat;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.atomic.AtomicLong;
import mx.quest.database.spi.DatabaseConsumer;
import mx.quest.database.spi.Databases;
import mx.quest.database.spi.Dialect;
import mx.quest.database.spi.PluginDatabase;
import mx.quest.database.spi.Scope;
import mx.quest.runway.spi.CaptchaService;
import mx.quest.runway.spi.model.CaptchaWidget;
import mx.quest.runway.spi.model.RouteRequest;
import mx.quest.runway.spi.model.RouteResponse;
import mx.quest.runway.spi.model.SiteRef;
import mx.quest.runway.spi.model.SiteView;
import mx.quest.runway.spi.testkit.FakePluginSettings;
import org.junit.jupiter.api.Test;
class GuestbookEndpointsTest {
/** A site's CAPTCHA: inactive, or active and accepting one token only. */
static CaptchaService captcha(boolean active, String accepted) {
return new CaptchaService() {
@Override
public CaptchaWidget widgetForSite(String siteId) {
return active ? new CaptchaWidget(true, "g-recaptcha-response", "<div class=\"challenge\"></div>")
: CaptchaWidget.inactive();
}
@Override
public boolean verify(String siteId, String token, String clientIp) {
return !active || accepted.equals(token);
}
};
}
static final SiteView SITE = new SiteView("acme", "Acme", Locale.ENGLISH, List.of(Locale.ENGLISH), null);
/** A database that is not available and fails the test if anything tries to use a scope. */
static Databases unavailable() {
PluginDatabase db = new PluginDatabase() {
public boolean available() {
return false;
}
public Dialect dialect() {
throw new AssertionError("no dialect while unavailable");
}
public String prefix() {
return "runway_demo_database__";
}
public Scope currentSite() {
throw new AssertionError("no scope expected");
}
public Scope site(SiteRef site) {
throw new AssertionError("no scope expected");
}
public Scope siteInBackground(String siteId) {
throw new AssertionError("no scope expected");
}
public Scope app() {
throw new AssertionError("no scope expected");
}
};
return (DatabaseConsumer me) -> db;
}
static GuestbookStore store() {
return new GuestbookStore(unavailable(), new GuestbookConsumer());
}
static RouteRequest post(Map<String, List<String>> form, String ip) {
return new RouteRequest(SITE, Locale.ENGLISH, "POST", GuestbookEndpoints.SIGN_PATH, Map.of(), Map.of(),
new byte[0], form, ip, "https://acme.test");
}
static String location(RouteResponse r) {
assertThat(r.status()).isEqualTo(303);
assertThat(r.headers()).containsEntry("Cache-Control", "no-store");
return r.headers().get("Location");
}
@Test
void theGuardsAnswerBeforeTheDatabaseIsTouched() {
AtomicLong clock = new AtomicLong(1_000_000);
GuestbookEndpoints endpoints = new GuestbookEndpoints(store(),
new FakePluginSettings(), captcha(false, ""), clock::get);
assertThat(location(endpoints.handle(post(Map.of("name", List.of("Bot"), "message", List.of("x"),
"website", List.of("spam"), "return", List.of("/hello")), "1.1.1.1"))))
.isEqualTo("/hello?guestbook=thanks");
assertThat(location(endpoints.handle(post(Map.of("name", List.of(""), "message", List.of("x")), "1.1.1.1"))))
.isEqualTo("/?guestbook=invalid");
assertThat(location(endpoints.handle(post(Map.of("name", List.of("n".repeat(81)), "message",
List.of("x")), "1.1.1.1")))).endsWith("invalid");
assertThat(location(endpoints.handle(post(Map.of("name", List.of("Ana"), "message", List.of("a\u0000b")),
"1.1.1.1")))).as("a NUL byte is invalid, not a database outage").endsWith("invalid");
assertThat(location(endpoints.handle(post(Map.of("name", List.of("Ana"), "message", List.of("a\u001bb")),
"1.1.1.1")))).endsWith("invalid");
assertThat(location(endpoints.handle(post(Map.of("name", List.of("Ana"), "message",
List.of("line one\r\nline\ttwo")), "3.3.3.3")))).as("line breaks and tabs are a message's own")
.endsWith("unavailable");
assertThat(location(endpoints.handle(post(Map.of("name", List.of("Ana"), "message", List.of("x"),
"return", List.of("https://evil.example/")), "1.1.1.1")))).isEqualTo("/?guestbook=unavailable");
for (int i = 0; i < GuestbookEndpoints.SIGN_PER_WINDOW - 1; i++) {
endpoints.handle(post(Map.of("name", List.of("Ana"), "message", List.of("x")), "1.1.1.1"));
}
assertThat(location(endpoints.handle(post(Map.of("name", List.of("Ana"), "message", List.of("x")),
"1.1.1.1")))).endsWith("limited");
assertThat(location(endpoints.handle(post(Map.of("name", List.of("Ana"), "message", List.of("x")),
"2.2.2.2")))).endsWith("unavailable");
clock.addAndGet(GuestbookEndpoints.WINDOW_MILLIS);
assertThat(location(endpoints.handle(post(Map.of("name", List.of("Ana"), "message", List.of("x")),
"1.1.1.1")))).endsWith("unavailable");
}
@Test
void aSiteWithACaptchaRefusesASignatureWithoutTheSolvedChallenge() {
GuestbookEndpoints endpoints = new GuestbookEndpoints(store(), new FakePluginSettings(),
captcha(true, "solved"));
assertThat(location(endpoints.handle(post(Map.of("name", List.of("Ana"), "message", List.of("x")),
"1.1.1.1")))).endsWith("guestbook=captcha");
assertThat(location(endpoints.handle(post(Map.of("name", List.of("Ana"), "message", List.of("x"),
"g-recaptcha-response", List.of("wrong")), "1.1.1.1")))).endsWith("guestbook=captcha");
// Solved: on to the database (unavailable in this test).
assertThat(location(endpoints.handle(post(Map.of("name", List.of("Ana"), "message", List.of("x"),
"g-recaptcha-response", List.of("solved")), "1.1.1.1")))).endsWith("guestbook=unavailable");
}
@Test
void theEntriesEndpointIsNeverCachedAndSaysWhenTheDatabaseIsAway() {
GuestbookEndpoints endpoints = new GuestbookEndpoints(store(),
new FakePluginSettings(), captcha(false, ""));
RouteResponse r = endpoints.handle(new RouteRequest(SITE, Locale.ENGLISH, "GET",
GuestbookEndpoints.ENTRIES_PATH, Map.of(), Map.of(), new byte[0]));
assertThat(r.status()).isEqualTo(503);
assertThat(r.headers()).containsEntry("Cache-Control", "no-store");
assertThat(new String(r.body(), StandardCharsets.UTF_8)).contains("\"available\":false");
}
@Test
void aSiteThatTurnedTheGuestbookOffAnswersNotFound() {
GuestbookEndpoints endpoints = new GuestbookEndpoints(store(),
new FakePluginSettings().site("acme", Map.of("enabled", false)), captcha(false, ""));
assertThat(endpoints.handle(post(Map.of("name", List.of("Ana"), "message", List.of("x")), "1.1.1.1"))
.status()).isEqualTo(404);
}
}
@@ -0,0 +1,159 @@
package mx.quest.demodatabase;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assumptions.assumeTrue;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.sql.Connection;
import java.time.Duration;
import java.time.Instant;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Optional;
import java.util.TimeZone;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import mx.quest.database.internal.DatabaseConfig;
import mx.quest.database.internal.DatabaseCore;
import mx.quest.database.internal.DatabaseProps;
import mx.quest.database.internal.DatabaseRuntime;
import mx.quest.database.internal.DatabasesImpl;
import mx.quest.database.internal.Engine;
import mx.quest.database.internal.Migrator;
import mx.quest.database.internal.ScriptSource;
import mx.quest.database.internal.SiteSchemas;
import mx.quest.database.mariadb.MariaDbProvider;
import mx.quest.database.postgresql.PostgresProvider;
import mx.quest.database.spi.DatabaseProvider;
import mx.quest.database.spi.Scope;
import mx.quest.runway.spi.model.SiteView;
import mx.quest.runway.spi.testkit.FakeSiteServices;
import mx.quest.runway.spi.testkit.TempDirSiteFiles;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.io.TempDir;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
/**
* The guestbook's SQL and scripts on real PostgreSQL and MariaDB, through the real database plugin and providers.
* Servers come from {@code -Ddb.it.postgresql=host:port}, {@code -Ddb.it.mariadb=host:port} and
* {@code -Ddb.it.password-file=…}; without them the tests are skipped.
*/
class GuestbookStoreRealServerTest {
@TempDir
Path work;
private final List<AutoCloseable> closing = new ArrayList<>();
@AfterEach
void close() throws Exception {
for (AutoCloseable c : closing) {
c.close();
}
}
private GuestbookStore store(String engine, String siteId) throws Exception {
String hostPort = System.getProperty("db.it." + engine);
String file = System.getProperty("db.it.password-file");
assumeTrue(hostPort != null && file != null, "no " + engine + " server configured");
String[] hp = hostPort.split(":");
String password = Files.readString(Path.of(file)).strip();
DatabaseProps props = new DatabaseProps();
props.setProvider(engine);
props.setNamespace("itd" + (System.nanoTime() % 100_000_000L));
props.setHost(hp[0]);
props.setPort(Integer.parseInt(hp[1]));
props.setDatabase("runway");
props.setUsername("runway");
props.setTls("disable");
DatabaseProvider provider = engine.equals("postgresql") ? new PostgresProvider() : new MariaDbProvider();
ScheduledExecutorService executor = Executors.newScheduledThreadPool(2);
DatabaseRuntime runtime = new DatabaseRuntime(() -> DatabaseConfig.from(props, Optional.of(password)),
() -> List.of(provider), work.resolve("run"), executor);
FakeSiteServices sites = new FakeSiteServices()
.site(new SiteView(siteId, siteId, Locale.ENGLISH, List.of(Locale.ENGLISH), null));
Files.createDirectories(work.resolve("sites").resolve(siteId));
SiteSchemas schemas = new SiteSchemas(runtime, new TempDirSiteFiles(work.resolve("sites"), "database"), sites);
DatabaseCore core = new DatabaseCore(runtime, schemas, new Migrator(runtime), sites, sites);
DatabasesImpl databases = new DatabasesImpl(core, (cls, id) -> new ClasspathScripts(id));
closing.add(() -> {
runtime.stop();
executor.shutdownNow();
Engine e = DatabaseRuntime.engineFor(engine);
try (Connection c = provider.dataSource(new mx.quest.database.spi.ConnectionSettings(hp[0],
Integer.parseInt(hp[1]), "runway", "runway", password,
mx.quest.database.spi.ConnectionSettings.Tls.DISABLE, null, Duration.ofSeconds(5),
Duration.ofSeconds(30))).getConnection()) {
for (String s : e.listSchemas(c, props.getNamespace())) {
e.dropSchema(c, s);
}
}
});
runtime.start();
long deadline = System.nanoTime() + Duration.ofSeconds(30).toNanos();
while (!runtime.available() && System.nanoTime() < deadline) {
Thread.sleep(50);
}
assertThat(runtime.available()).as(runtime.health().detail()).isTrue();
return new GuestbookStore(databases, new GuestbookConsumer());
}
/** The plugin's own scripts, read from the compiled resources as the database plugin reads them from the jar. */
record ClasspathScripts(String pluginId) implements ScriptSource {
@Override
public Optional<byte[]> read(String entry) throws IOException {
try (InputStream in = GuestbookStore.class.getResourceAsStream("/" + entry)) {
return in == null ? Optional.empty() : Optional.of(in.readAllBytes());
}
}
}
@ParameterizedTest
@ValueSource(strings = {"postgresql", "mariadb"})
void entriesAreAddedPagedCappedAndDeleted(String engine) throws Exception {
// A JVM that is not on UTC, so a time read or written in the JVM's zone shows as hours off below.
TimeZone zone = TimeZone.getDefault();
TimeZone.setDefault(TimeZone.getTimeZone("America/Mexico_City"));
try {
entriesAreAddedPagedCappedAndDeletedIn(engine);
} finally {
TimeZone.setDefault(zone);
}
}
private void entriesAreAddedPagedCappedAndDeletedIn(String engine) throws Exception {
GuestbookStore store = store(engine, "acme");
Scope site = store.db().siteInBackground("acme");
Instant before = Instant.now();
long first = store.add(site, "Ana", "Hola ñ €", 10);
long second = store.add(site, "Bo", "Hi <b>there</b>", 10);
assertThat(second).isGreaterThan(first);
GuestbookStore.Page page = store.page(site, 0, 20);
assertThat(page.entries()).extracting(GuestbookStore.Entry::name).containsExactly("Bo", "Ana");
assertThat(page.entries().get(1).message()).isEqualTo("Hola ñ €");
assertThat(page.entries().get(0).at()).as("the entry's time, in UTC, from either side")
.isBetween(before.minusSeconds(5), Instant.now().plusSeconds(5));
for (int i = 0; i < 13; i++) {
store.add(site, "n" + i, "m" + i, 10);
}
assertThat(store.count(site)).isEqualTo(10);
GuestbookStore.Page newest = store.page(site, 0, 4);
assertThat(newest.more()).isTrue();
assertThat(newest.entries()).extracting(GuestbookStore.Entry::name).containsExactly("n12", "n11", "n10", "n9");
GuestbookStore.Page last = store.page(site, 2, 4);
assertThat(last.more()).isFalse();
assertThat(last.entries()).extracting(GuestbookStore.Entry::name).containsExactly("n4", "n3");
GuestbookStore.Page far = store.page(site, Integer.MAX_VALUE, 50);
assertThat(far.entries()).as("a huge page number is an empty page, not an overflowed offset").isEmpty();
assertThat(far.more()).isFalse();
long id = newest.entries().get(0).id();
assertThat(store.delete(site, id)).isTrue();
assertThat(store.delete(site, id)).isFalse();
assertThat(store.count(site)).isEqualTo(9);
}
}