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

+10
View File
@@ -0,0 +1,10 @@
# Changelog
All notable changes are recorded here. Versions follow [Semantic Versioning](https://semver.org/).
## [1.0.0] — 2026-10-29
First public release of `runway-demo-database`: a per-site guestbook on the `database` plugin, the worked example of
a plugin that keeps its data in the database (migrations for both products, transactions, the site's CAPTCHA on a
public form, backup and restore). Requires SPI `1.1.0` (Runway `1.1.0` or later) and `database` `1.0.0`. Licensed
under the Apache License 2.0 (`LICENSE`, `NOTICE`), so a plugin started from a copy of it may carry any license.
+202
View File
@@ -0,0 +1,202 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
+9
View File
@@ -0,0 +1,9 @@
runway-demo-database — the Runway database example plugin
Copyright 2026 Quest ICT SAS de CV
Licensed under the Apache License, Version 2.0 (the file LICENSE). Unlike the Runway kernel and the database
plugin, which are licensed under the GNU Affero General Public License version 3 with an additional permission for
plugins, this example is offered under a permissive license so that it can be copied as the starting point of a
plugin under any terms. The exception is the test GuestbookStoreRealServerTest, which links the database plugin's
internal classes and its providers (AGPL-3.0, outside the plugin permission): a copy under other terms should
delete it and its two test-scope provider dependencies.
+39
View File
@@ -0,0 +1,39 @@
# Runway demo — database
The worked example of a plugin that keeps its data in the database: a **per-site guestbook** on PostgreSQL or
MariaDB, through the [`database`](../database) plugin. It uses each part of the database SPI once, the way a real
plugin would.
- **Plugin id:** `runway-demo-database` (v`1.0.0`) — install folder `external/plugins/runway-demo-database/`
- **Requires:** `database >= 1.0.0` (without it the plugin shows as **Blocked**), Runway SPI `1.1.0` or later
- **Links:** only the Runway SPI and the database SPI (`mx.quest.database.spi`)
## Try it
1. Install `database`, a provider and this plugin; set the database up (ADMINISTRATION §11.1); restart.
2. Put the widget on a page: `<div id="guestbook" data-widget="guestbook/main"></div>`.
3. Sign it as a visitor; manage the entries under **Guestbook** in the site console (permission
`runway-demo-database|manage`).
Per-site settings: `enabled` and `maxEntries` (10–10000, default 500: the oldest entries beyond it are deleted).
Read [`docs/DEMO-DATABASE-PLUGIN.md`](docs/DEMO-DATABASE-PLUGIN.md) for the walkthrough and
[`../docs/PLUGIN-AUTHORING-GUIDE.md`](../docs/PLUGIN-AUTHORING-GUIDE.md) §7.14 for the rules it follows.
## Build and verify
```bash
mvn -o install # tests; the store's real-server tests run with -Ddb.it.postgresql / -Ddb.it.mariadb / -Ddb.it.password-file
PROVIDER=mariadb DB_HOST=127.0.0.1 DB_PORT=53306 DB_PASSWORD_FILE=/path/pw scripts/verify-against-host.sh
```
See [`CHANGELOG.md`](CHANGELOG.md).
## License
Apache License 2.0 (`LICENSE`, `NOTICE`), copyright Quest ICT SAS de CV. You are free to copy this example as the
start of your own plugin and to release yours under any terms. One exception: `GuestbookStoreRealServerTest` builds
a real database layer from the `database` plugin's internal classes (`mx.quest.database.internal`) and the two
providers, which are AGPL-3.0 and outside the plugin permission. A copy released under other terms should delete
that test and its two test-scope provider dependencies, and test against a running Runway instead
(`scripts/verify-against-host.sh` does).
@@ -0,0 +1,32 @@
# The guestbook example — a walkthrough
Each class shows one thing a database consumer does.
| Class | Shows |
|---|---|
| `GuestbookConsumer` | The one `DatabaseConsumer` bean: the plugin id and the `SITE` scope. |
| `DemoDatabaseConfig` | `Databases` injected by type from the database plugin; every bean named `runwayDemoDatabase…`. |
| `GuestbookStore` | The only SQL: `databases.of(consumer)` on first use; `nextValue` in the insert and `lastValue` after it in one `transaction`; paging with `limitOffset` in a `read`; the row cap applied in the insert's transaction. The same SQL on both products. |
| `GuestbookEndpoints` | An anonymous `POST` with a honeypot, length caps, the site's CAPTCHA (`CaptchaService`, when the site has one) and a per-address window; the site always from the request; `/guestbook/entries.json` with `Cache-Control: no-store`; `available()` checked and failures answered as "unavailable", never as an error page. |
| `GuestbookWidget` | A static shell — the form and an empty list — so the page's output never depends on database rows and stays cacheable. |
| `static/guestbook.js` | Fills the list from the endpoint, inserting text, never HTML. |
| `GuestbookConsoleController` | `currentSite()` in the site console; delete as a CSRF-checked `POST`. |
| `src/main/resources/db/runway-demo-database/…` | The migration scripts: an `index` and `V1__guestbook.sql` per product, every object starting with `runway_demo_database__`, the same table on both. |
**Why the list is not in the page.** The kernel caches rendered pages and answers `304` while a page's ETag holds. A
widget that read rows would freeze a page with its first entries. The verify script checks the design: after a new
entry, the page still answers `304`, while the entries endpoint answers `200` with the entry.
**What travels.** The entries are per site, so they are in the site's full backups and restore with it, on either
product. A transfer copy carries none: they are visitors' personal data, which a transfer may leave behind.
**Without the database.** Without the `database` plugin, this one is Blocked with the kernel's reason and its routes
do not exist. With the plugin but no reachable server, the page still renders, the list says "This example needs the
database", and signing answers "unavailable".
**Tests.** `GuestbookEndpointsTest` (the guards answer before the database is touched), `DemoDatabaseConfigTest`
(wiring, the widget's shell, linkage: only the Runway SPI and the database SPI), `GuestbookStoreRealServerTest` (the
SQL and the scripts on real PostgreSQL and MariaDB, through the real database plugin and providers), and
`scripts/verify-against-host.sh` (25 checks in a real Runway). `GuestbookStoreRealServerTest` uses the database
plugin's internal classes, which are AGPL-3.0 and not covered by the plugin permission: a copy of this example under
other terms should delete it (and its two test-scope provider dependencies) and keep the end-to-end script.
@@ -0,0 +1,27 @@
# Runway demo — database (guestbook) — English
guestbook.menu=Guestbook
guestbook.perm.manage=Manage the guestbook
guestbook.set.enabled=Guestbook on
guestbook.set.maxEntries=Most entries kept
guestbook.set.maxEntries.help=When a new entry would go past this, the oldest ones are deleted.
guestbook.name=Your name
guestbook.message=Message
guestbook.sign=Sign the guestbook
guestbook.empty=No entries yet. Be the first!
guestbook.more=Older entries
guestbook.thanks=Thank you for signing the guestbook.
guestbook.invalid=Please give your name and a message (up to 80 and 1000 characters).
guestbook.limited=Too many entries from your address — please try again in a minute.
guestbook.captcha=Please complete the challenge and try again.
guestbook.unavailable=This example needs the database, which is not available right now.
guestbook.console.title=Guestbook
guestbook.console.count=Entries
guestbook.console.empty=No entries yet.
guestbook.console.at=When
guestbook.console.delete=Delete
guestbook.console.deleted=Entry deleted.
guestbook.console.gone=That entry is no longer there.
guestbook.console.failed=The database could not be reached.
guestbook.console.unavailable=The database is not available, so the guestbook cannot be shown.
guestbook.console.newer=Newer
guestbook.console.older=Older
@@ -0,0 +1,27 @@
# Runway demo — base de datos (libro de visitas) — español
guestbook.menu=Libro de visitas
guestbook.perm.manage=Administrar el libro de visitas
guestbook.set.enabled=Libro de visitas activo
guestbook.set.maxEntries=Máximo de entradas guardadas
guestbook.set.maxEntries.help=Cuando una entrada nueva supera este número, se borran las más antiguas.
guestbook.name=Su nombre
guestbook.message=Mensaje
guestbook.sign=Firmar el libro de visitas
guestbook.empty=Aún no hay entradas. ¡Sea el primero!
guestbook.more=Entradas anteriores
guestbook.thanks=Gracias por firmar el libro de visitas.
guestbook.invalid=Escriba su nombre y un mensaje (hasta 80 y 1000 caracteres).
guestbook.limited=Demasiadas entradas desde su dirección; inténtelo de nuevo en un minuto.
guestbook.captcha=Complete el desafío e inténtelo de nuevo.
guestbook.unavailable=Este ejemplo necesita la base de datos, que ahora no está disponible.
guestbook.console.title=Libro de visitas
guestbook.console.count=Entradas
guestbook.console.empty=Aún no hay entradas.
guestbook.console.at=Fecha
guestbook.console.delete=Borrar
guestbook.console.deleted=Entrada borrada.
guestbook.console.gone=Esa entrada ya no existe.
guestbook.console.failed=No se pudo contactar con la base de datos.
guestbook.console.unavailable=La base de datos no está disponible, así que no se puede mostrar el libro de visitas.
guestbook.console.newer=Más recientes
guestbook.console.older=Anteriores
+36
View File
@@ -0,0 +1,36 @@
# =============================================================================
# Runway demo — database
# The worked example of a plugin that keeps its data in the database: a
# per-site guestbook. Place it on any page with <div id="guestbook" data-widget="guestbook/main"></div>.
#
# - Visitors sign through an anonymous form (honeypot, length caps, a
# per-address limit); each site keeps at most `maxEntries` entries.
# - The page carries a static shell; the entries load from
# /guestbook/entries.json, which is never cached, so pages stay cacheable.
# - Its tables are per site, so they travel in the site's full backups
# (not in transfer copies: visitors' entries are personal data).
#
# The install folder name MUST equal this `id`: external/plugins/runway-demo-database/.
# =============================================================================
id: runway-demo-database
name: Runway demo — database
version: 1.0.0
mainClass: mx.quest.demodatabase.DemoDatabaseConfig
# Without the database plugin this example is Blocked, with the kernel's reason.
requires: [ "database >= 1.0.0" ]
requiresSpi: ">=1.1.0"
permissions:
- { id: manage, realm: tenant, label: guestbook.perm.manage, defaultRoles: [] }
siteSettings:
- { key: enabled, type: boolean, default: true, label: guestbook.set.enabled }
- { key: maxEntries, type: int, default: 500, range: "10..10000", label: guestbook.set.maxEntries,
help: guestbook.set.maxEntries.help }
menu:
- { realm: tenant, region: menu, order: 62, label: guestbook.menu,
path: "/__admin/runway-demo-database", permission: "runway-demo-database|manage", icon: "fa-solid fa-book-open" }
+167
View File
@@ -0,0 +1,167 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<!--
The guestbook example. Links the Runway SPI and the database plugin's published SPI (provided: the shared
plugin class loader supplies it). Bundles nothing in lib/.
-->
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>4.0.6</version>
<relativePath/>
</parent>
<groupId>mx.quest</groupId>
<artifactId>runway-plugin-runway-demo-database</artifactId>
<version>1.0.0</version>
<packaging>jar</packaging>
<name>Runway demo — database</name>
<licenses>
<license>
<name>Apache License, Version 2.0</name>
<url>https://www.apache.org/licenses/LICENSE-2.0.txt</url>
<distribution>repo</distribution>
</license>
</licenses>
<description>
The worked example of a Runway plugin that keeps its data in the database: a per-site guestbook on
PostgreSQL or MariaDB through the database plugin, with an anonymous signing form, a never-cached entries
endpoint and a console screen.
</description>
<properties>
<java.version>25</java.version>
<maven.compiler.release>25</maven.compiler.release>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<!-- Reproducible builds: pins every archive entry's timestamp. Bump at each release. -->
<project.build.outputTimestamp>2026-10-29T00:00:00Z</project.build.outputTimestamp>
<!-- The runway-spi this plugin compiles against: SPI 1.1.0 adds PluginSettings.appSecret. -->
<runway.version>1.1.0</runway.version>
<!-- The database plugin whose SPI this example uses (provided; install ../database first). -->
<database.version>1.0.0</database.version>
</properties>
<dependencies>
<dependency>
<groupId>mx.quest</groupId>
<artifactId>runway-spi</artifactId>
<version>${runway.version}</version>
</dependency>
<dependency>
<groupId>mx.quest</groupId>
<artifactId>runway-spi-testkit</artifactId>
<version>${runway.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>mx.quest</groupId>
<artifactId>runway-plugin-database</artifactId>
<version>${database.version}</version>
<scope>provided</scope>
</dependency>
<!-- The kernel supplies these at runtime; never bundled. -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-core</artifactId>
<scope>provided</scope>
</dependency>
<!-- Jackson 3 (tools.jackson), the kernel's JSON library: the entries endpoint's answer. -->
<dependency>
<groupId>tools.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!-- The real providers (and so the real drivers), for the store's tests against real servers. -->
<dependency>
<groupId>mx.quest</groupId>
<artifactId>runway-plugin-database-postgresql</artifactId>
<version>${database.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>mx.quest</groupId>
<artifactId>runway-plugin-database-mariadb</artifactId>
<version>${database.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>jakarta.servlet</groupId>
<artifactId>jakarta.servlet-api</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<finalName>runway-plugin-runway-demo-database</finalName>
<plugins>
<!-- Assemble target/runway-demo-database/ (folder) and the UI zip. -->
<plugin>
<artifactId>maven-antrun-plugin</artifactId>
<executions>
<execution>
<id>assemble-plugin-folder</id>
<phase>package</phase>
<goals>
<goal>run</goal>
</goals>
<configuration>
<target>
<property name="stage" value="${project.build.directory}/runway-demo-database"/>
<delete dir="${stage}"/>
<mkdir dir="${stage}"/>
<copy file="${project.basedir}/plugin.yml" todir="${stage}"/>
<copy file="${project.basedir}/LICENSE" todir="${stage}"/>
<copy file="${project.basedir}/NOTICE" todir="${stage}"/>
<copy file="${project.build.directory}/runway-plugin-runway-demo-database.jar" todir="${stage}"/>
<copy todir="${stage}/templates">
<fileset dir="${project.basedir}/templates"/>
</copy>
<copy todir="${stage}/static">
<fileset dir="${project.basedir}/static"/>
</copy>
<copy todir="${stage}/i18n">
<fileset dir="${project.basedir}/i18n"/>
</copy>
<touch datetime="${project.build.outputTimestamp}"
pattern="yyyy-MM-dd'T'HH:mm:ss'Z'">
<fileset dir="${stage}"/>
<dirset dir="${stage}"/>
<dirset dir="${project.build.directory}" includes="runway-demo-database"/>
</touch>
<!-- The stamped files predate any earlier zip, so <zip> would skip the rebuild. -->
<delete file="${project.build.directory}/runway-plugin-runway-demo-database-${project.version}.zip"/>
<zip destfile="${project.build.directory}/runway-plugin-runway-demo-database-${project.version}.zip">
<zipfileset dir="${project.build.directory}" includes="runway-demo-database/**"/>
</zip>
<echo message="Staged install folder: ${stage}"/>
<echo message="UI-uploadable archive: ${project.build.directory}/runway-plugin-runway-demo-database-${project.version}.zip"/>
</target>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
+163
View File
@@ -0,0 +1,163 @@
#!/usr/bin/env bash
# =============================================================================
# Verify the guestbook example inside a real Runway, end to end.
#
# Boots a throwaway Runway with database, the chosen provider and runway-demo-database, places the guestbook on a
# page, and checks: signing, the never-cached entries endpoint (a page answered 304 still shows the new entry),
# the honeypot, the per-address limit, the console screen and its delete, and the two ways the database can be
# missing — the database plugin absent (the example is Blocked) and the server unreachable (the page says so).
#
# Usage:
# PROVIDER=postgresql DB_HOST=127.0.0.1 DB_PORT=55432 DB_PASSWORD_FILE=/path/pw scripts/verify-against-host.sh
# Needs JAVA_HOME (a JDK 25). Optional: MVN (default mvn on the PATH), DB_NAME, DB_USER (default runway), HOST_TARGET
# (default the Runway this folder sits in, else ../runway), HOST_JAR, --keep, --port N.
# Each run uses a fresh namespace; its schemas stay on the server, so point it at a throwaway one.
# =============================================================================
set -u
HERE="$(cd "$(dirname "$0")/.." && pwd)"
REPO="$(cd "$HERE/.." && pwd)"
# The kernel build: the Runway this plugin folder sits in (the public layout, plugins/ inside the kernel), else a
# runway checkout beside this repository.
if [ -z "${HOST_TARGET:-}" ]; then
if [ -f "$REPO/../runway-app/pom.xml" ]; then HOST_TARGET="$REPO/../runway-app/target"
else HOST_TARGET="$REPO/../runway/runway-app/target"; fi
fi
MVN="${MVN:-mvn}"
if [ -z "${JAVA_HOME:-}" ] || [ ! -x "$JAVA_HOME/bin/java" ]; then echo "set JAVA_HOME to a JDK 25"; exit 2; fi
export JAVA_HOME
JAVA="$JAVA_HOME/bin/java"
: "${PROVIDER:?set PROVIDER=postgresql or mariadb}"
: "${DB_HOST:?set DB_HOST}"; : "${DB_PORT:?set DB_PORT}"; : "${DB_PASSWORD_FILE:?set DB_PASSWORD_FILE}"
DB_NAME="${DB_NAME:-runway}"; DB_USER="${DB_USER:-runway}"
DB_PASSWORD="$(cat "$DB_PASSWORD_FILE")"
KEEP="no"; PORT=""
while [ $# -gt 0 ]; do
case "$1" in
--keep) KEEP="yes"; shift ;;
--port) PORT="${2:?}"; shift 2 ;;
*) echo "unknown argument $1"; exit 2 ;;
esac
done
free_port() { python3 -I -c 'import socket;s=socket.socket();s.bind(("127.0.0.1",0));print(s.getsockname()[1]);s.close()'; }
[ -n "$PORT" ] || PORT="$(free_port)"
BASE="http://localhost:$PORT"
APP_USER=root; APP_PW=Guestbook-Admin-2026; SITE_USER=owner; SITE_PW=Guestbook-Site-2026
NS="hv$(date +%s | tail -c 9)"
echo "[verify] packaging the database plugins and this example ..."
( cd "$REPO/database" && "$MVN" -o -q -DskipTests install ) || { echo "database build failed"; exit 1; }
( cd "$REPO/database-$PROVIDER" && "$MVN" -o -q -DskipTests package ) || { echo "provider build failed"; exit 1; }
( cd "$HERE" && "$MVN" -o -q -DskipTests package ) || { echo "example build failed"; exit 1; }
if [ -n "${HOST_JAR:-}" ]; then JAR="$HOST_JAR"; else
HOST_VERSION="$(sed -n 's:.*<version>\(.*\)</version>.*:\1:p' "$HOST_TARGET/../pom.xml" | head -1)"
JAR="$HOST_TARGET/runway-app-$HOST_VERSION-exec.jar"
fi
[ -f "$JAR" ] || { echo "no host exec jar $JAR"; exit 1; }
echo "[verify] host jar: $JAR; provider $PROVIDER; namespace $NS"
mkdir -p "$HERE/target"
SCRATCH="$(mktemp -d "$HERE/target/guestbook-verify.XXXXXX")"
PID=""
stop_host() { [ -z "$PID" ] || { kill "$PID" 2>/dev/null; wait "$PID" 2>/dev/null; PID=""; }; }
cleanup() { stop_host; [ "$KEEP" = "yes" ] && echo "[verify] kept $SCRATCH" || rm -rf "$SCRATCH"; }
trap cleanup EXIT
wait_for() { for _ in $(seq 1 "$3"); do grep -q "$2" "$1" 2>/dev/null && return 0; sleep 1; done; return 1; }
PASS=0; FAIL=0
ck() { if eval "$2" >/dev/null 2>&1; then echo " PASS $1"; PASS=$((PASS+1)); else echo " FAIL $1"; FAIL=$((FAIL+1)); fi; }
code() { curl -s -o /dev/null -w '%{http_code}' "$@"; }
token() { grep -o 'name="_csrf" value="[^"]*"' | head -1 | sed 's/.*value="//; s/"$//'; }
EXT="$SCRATCH/external"; SITES="$EXT/sites"
mkdir -p "$EXT/plugins" "$EXT/plugin-settings"
cp -r "$REPO/database/target/database" "$EXT/plugins/database"
cp -r "$REPO/database-$PROVIDER/target/database-$PROVIDER" "$EXT/plugins/database-$PROVIDER"
cp -r "$HERE/target/runway-demo-database" "$EXT/plugins/runway-demo-database"
boot() { ( cd "$SCRATCH" && exec "$JAVA" -jar "$JAR" --server.port="$PORT" --runway.storage.external="$EXT" ) >"$1" 2>&1 & PID=$!; }
settings() { # port
umask 077
printf 'runway:\n plugin:\n database:\n provider: %s\n namespace: %s\n host: "%s"\n port: %s\n database: "%s"\n username: "%s"\n password: "%s"\n tls: disable\n' \
"$PROVIDER" "$NS" "$DB_HOST" "$1" "$DB_NAME" "$DB_USER" "$DB_PASSWORD" > "$EXT/plugin-settings/database.yml"
umask 022
}
echo "[verify] booting host (wizard) on :$PORT ..."
boot "$SCRATCH/wizard.log"
wait_for "$SCRATCH/wizard.log" "Started RunwayApplication" 90 || { echo "wizard did not start"; exit 1; }
curl -s -o /dev/null -X POST "$BASE/setup" --data-urlencode "username=$APP_USER" --data-urlencode "password=$APP_PW" \
--data-urlencode "displayName=Root" --data-urlencode "siteAdminUsername=$SITE_USER" \
--data-urlencode "siteAdminPassword=$SITE_PW"
for _ in $(seq 1 30); do kill -0 "$PID" 2>/dev/null || break; sleep 1; done
stop_host
T="$SITES/default/templates"
[ -f "$T/about.th.xml" ] || { echo "the wizard did not seed the default site"; exit 1; }
printf 'path: /guests\ntemplate: _master\ntitle:\n en: "Guests"\ndescription:\n en: "Sign our guestbook."\n' > "$T/guests.meta.yml"
printf '<!DOCTYPE html>\n<html lang="en">\n<head><title>Guests</title></head>\n<body>\n<header id="site-header"></header>\n<main id="content">\n<h1>Guests</h1>\n<div id="guestbook" data-widget="guestbook/main"></div>\n</main>\n<footer id="site-footer"></footer>\n</body>\n</html>\n' > "$T/guests.html"
cp "$T/about.th.xml" "$T/guests.th.xml"
settings "$DB_PORT"
LOG="$SCRATCH/active.log"
echo "[verify] booting host (ACTIVE) ..."
boot "$LOG"
wait_for "$LOG" "Started RunwayApplication" 90 || { echo "ACTIVE did not start"; tail -20 "$LOG"; exit 1; }
wait_for "$LOG" "database: connected to" 30
echo "== loading =="
ck "3 plugins registered, 0 blocked" "grep -qE 'plugins: 3 registered, 0 blocked' '$LOG'"
ck "no linkage or surface findings" "! grep -qE \"plugin '(runway-demo-database|database[a-z-]*)' (linkage scan|is blocked)\" '$LOG'"
echo "== the page and signing =="
curl -s -D "$SCRATCH/page.h" "$BASE/guests" -o "$SCRATCH/page.html"
ETAG="$(grep -i '^etag:' "$SCRATCH/page.h" | head -1 | sed 's/^[^:]*: *//; s/\r$//')"
ck "the page serves the form and an empty list shell" "grep -q 'action=\"/guestbook/sign\"' '$SCRATCH/page.html' && grep -q 'data-src=\"/guestbook/entries.json\"' '$SCRATCH/page.html'"
ck "the page has an ETag" "[ -n '$ETAG' ]"
ck "the list starts empty" "curl -s '$BASE/guestbook/entries.json' | grep -q '\"entries\":\\[\\]'"
sign() { curl -s -o /dev/null -w '%{http_code} %{redirect_url}' "$BASE/guestbook/sign" --data-urlencode "return=/guests" "$@"; }
ck "signing answers 303 back to the page with thanks" "[ \"\$(sign --data-urlencode 'name=Ana' --data-urlencode 'message=Hola desde la prueba')\" = '303 $BASE/guests?guestbook=thanks' ]"
curl -s -D "$SCRATCH/entries.h" "$BASE/guestbook/entries.json" -o "$SCRATCH/entries.json"
ck "the entry is listed at once" "grep -q 'Hola desde la prueba' '$SCRATCH/entries.json'"
ck "the entries endpoint is never cached" "grep -qi '^cache-control: no-store' '$SCRATCH/entries.h'"
ck "the page itself may still answer 304 (its shell did not change)" "[ \"\$(code -H 'If-None-Match: $ETAG' '$BASE/guests')\" = 304 ]"
ck "…while the entries endpoint answers 200 with the new entry even with If-None-Match" "[ \"\$(code -H 'If-None-Match: $ETAG' '$BASE/guestbook/entries.json')\" = 200 ] && curl -s -H 'If-None-Match: $ETAG' '$BASE/guestbook/entries.json' | grep -q 'Hola desde'"
ck "the honeypot pretends success and keeps nothing" "[ \"\$(sign --data-urlencode 'name=Bot' --data-urlencode 'message=spam' --data-urlencode 'website=x')\" = '303 $BASE/guests?guestbook=thanks' ] && ! curl -s '$BASE/guestbook/entries.json' | grep -q spam"
ck "an over-long name is refused" "sign --data-urlencode \"name=\$(printf 'n%.0s' \$(seq 1 81))\" --data-urlencode 'message=x' | grep -q 'guestbook=invalid'"
for i in 2 3 4 5; do sign --data-urlencode "name=Visitor $i" --data-urlencode "message=Entry $i" > /dev/null; done
ck "the sixth entry in a minute from one address is limited" "sign --data-urlencode 'name=Six' --data-urlencode 'message=six' | grep -q 'guestbook=limited'"
ck "a CSRF-less anonymous post is the only one allowed (the console's is refused)" "[ \"\$(code -X POST '$BASE/__admin/runway-demo-database/delete' -d id=1)\" != 303 ]"
echo "== the site console =="
sc() { curl -s -H 'Accept-Language: en' -c "$SCRATCH/site.jar" -b "$SCRATCH/site.jar" "$@"; }
sc -o /dev/null -X POST "$BASE/login" --data-urlencode "username=$SITE_USER" --data-urlencode "password=$SITE_PW" \
--data-urlencode "_csrf=$(sc "$BASE/login" | token)"
sc "$BASE/__admin/runway-demo-database" > "$SCRATCH/console.html"
ck "the console lists the entries" "grep -q 'Hola desde la prueba' '$SCRATCH/console.html' && grep -q 'Visitor 5' '$SCRATCH/console.html'"
ID="$(grep -o 'name="id" value="[0-9]*"' "$SCRATCH/console.html" | head -1 | grep -o '[0-9]*')"
sc -L "$BASE/__admin/runway-demo-database/delete" --data-urlencode "id=$ID" \
--data-urlencode "_csrf=$(token < "$SCRATCH/console.html")" > "$SCRATCH/deleted.html"
ck "deleting from the console works" "grep -q 'Entry deleted' '$SCRATCH/deleted.html' && ! curl -s '$BASE/guestbook/entries.json' | grep -q 'Visitor 5'"
ck "the dashboard shows the site now has database data" "sc '$BASE/__admin' | grep -q 'keeps plugin data in the database'"
ck "no ERROR line names the plugins" "! grep -E ' ERROR ' '$LOG' | grep -qiE 'demodatabase|mx\\.quest\\.database'"
ck "the password appears in no log line" "! grep -qF -- '$DB_PASSWORD' '$LOG'"
stop_host
echo "== the server unreachable =="
settings 1
LOG2="$SCRATCH/unreachable.log"
boot "$LOG2"
wait_for "$LOG2" "Started RunwayApplication" 90 || { echo "did not start"; exit 1; }
ck "Runway starts anyway" "[ \"\$(code '$BASE/guests')\" = 200 ]"
ck "the entries endpoint says unavailable (503)" "[ \"\$(code '$BASE/guestbook/entries.json')\" = 503 ]"
ck "signing says unavailable" "sign --data-urlencode 'name=Ana' --data-urlencode 'message=x' | grep -q 'guestbook=unavailable'"
stop_host
echo "== the database plugin absent =="
rm -rf "$EXT/plugins/database" "$EXT/plugins/database-$PROVIDER"
LOG3="$SCRATCH/absent.log"
boot "$LOG3"
wait_for "$LOG3" "Started RunwayApplication" 90 || { echo "did not start"; exit 1; }
ck "the example is blocked with the requires reason" "grep -E 'runway-demo-database' '$LOG3' | grep -qiE 'requires|database'"
ck "the page still serves (the widget is simply absent)" "[ \"\$(code '$BASE/guests')\" = 200 ]"
ck "the example's routes are gone" "[ \"\$(code '$BASE/guestbook/entries.json')\" = 404 ]"
echo "[verify] $PASS passed, $FAIL failed (namespace $NS left on the server)"
[ "$FAIL" = 0 ]
@@ -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);
}
}
@@ -0,0 +1,10 @@
/* Runway demo — guestbook. Plain, so it sits in any site's design. */
.rw-guestbook form { display: grid; gap: .4rem; max-width: 36rem; margin: 0 0 1.5rem; }
.rw-guestbook input, .rw-guestbook textarea { font: inherit; padding: .4rem; }
.rw-guestbook button { justify-self: start; padding: .4rem 1rem; font: inherit; cursor: pointer; }
.rw-guestbook-hp { position: absolute; left: -10000px; width: 1px; height: 1px; overflow: hidden; }
.rw-guestbook-notice { padding: .5rem .75rem; border-left: 3px solid currentColor; }
.rw-guestbook-list { list-style: none; padding: 0; margin: 0; }
.rw-guestbook-list li { padding: .6rem 0; border-top: 1px solid rgba(127, 127, 127, .25); }
.rw-guestbook-list time { opacity: .7; font-size: .875em; }
.rw-guestbook-list p { margin: .25rem 0 0; white-space: pre-wrap; overflow-wrap: anywhere; }
@@ -0,0 +1,65 @@
// Runway demo — guestbook list. Fills each .rw-guestbook-list from its data-src endpoint (never cached), a page at a
// time. Entries are inserted as text, never as HTML.
(function () {
"use strict";
function item(entry, lang) {
var li = document.createElement("li");
var who = document.createElement("strong");
who.textContent = entry.name;
var when = document.createElement("time");
when.dateTime = entry.at;
when.textContent = new Date(entry.at).toLocaleString(lang || undefined);
var text = document.createElement("p");
text.textContent = entry.message;
li.appendChild(who);
li.appendChild(document.createTextNode(" "));
li.appendChild(when);
li.appendChild(text);
return li;
}
function note(list, message) {
var li = document.createElement("li");
li.className = "rw-guestbook-empty";
li.textContent = message;
list.appendChild(li);
}
function load(list, page) {
var url = list.dataset.src + "?page=" + page;
fetch(url, { credentials: "same-origin", cache: "no-store" })
.then(function (r) { return r.json(); })
.then(function (data) {
var old = list.querySelector(".rw-guestbook-more");
if (old) { old.remove(); }
if (!data.available) { note(list, list.dataset.unavailable); return; }
if (page === 0 && data.entries.length === 0) { note(list, list.dataset.empty); return; }
data.entries.forEach(function (e) { list.appendChild(item(e, list.dataset.lang)); });
if (data.more) {
var li = document.createElement("li");
li.className = "rw-guestbook-more";
var button = document.createElement("button");
button.type = "button";
button.textContent = list.dataset.more;
button.addEventListener("click", function () { load(list, page + 1); });
li.appendChild(button);
list.appendChild(li);
}
})
.catch(function () { note(list, list.dataset.unavailable); });
}
function start() {
document.querySelectorAll(".rw-guestbook-list:not([data-loaded])").forEach(function (list) {
list.dataset.loaded = "1";
load(list, 0);
});
}
if (document.readyState === "loading") {
document.addEventListener("DOMContentLoaded", start);
} else {
start();
}
})();
@@ -0,0 +1,44 @@
<!DOCTYPE html>
<html lang="en">
<head><meta charset="utf-8"><title>Guestbook</title></head>
<body>
<!-- The guestbook console screen (@ConsoleScreen, site console). Markup only: bindings in console.th.xml. -->
<div id="content">
<div class="page-header d-print-none mb-3">
<h2 class="page-title" id="gb-heading">Guestbook</h2>
</div>
<div id="gb-flash" class="alert alert-success" role="status"><span id="gb-flash-text">done</span></div>
<div id="gb-error" class="alert alert-danger" role="alert"><span id="gb-error-text">error</span></div>
<div class="alert alert-warning" id="gb-unavailable">The database is not available.</div>
<div class="card" id="gb-card">
<div class="card-header"><h3 class="card-title"><span id="gb-count-label">Entries</span>:
<span id="gb-count">0</span></h3></div>
<p class="card-body text-secondary mb-0" id="gb-empty">No entries yet.</p>
<div class="table-responsive" id="gb-table">
<table class="table table-vcenter card-table">
<thead><tr><th id="gb-h-at">When</th><th id="gb-h-name">Name</th><th id="gb-h-message">Message</th>
<th></th></tr></thead>
<tbody>
<tr id="gb-row">
<td class="text-nowrap small gb-at">time</td>
<td class="gb-name">name</td>
<td class="gb-message">message</td>
<td>
<form method="post" action="/__admin/runway-demo-database/delete" class="m-0">
<input class="gb-csrf" type="hidden" name="_csrf" value="">
<input class="gb-id" type="hidden" name="id" value="">
<button type="submit" class="btn btn-sm btn-outline-danger gb-delete">Delete</button>
</form>
</td>
</tr>
</tbody>
</table>
</div>
<div class="card-footer" id="gb-pager">
<a class="btn btn-sm" id="gb-newer" href="?page=0">Newer</a>
<a class="btn btn-sm" id="gb-older" href="?page=1">Older</a>
</div>
</div>
</div>
</body>
</html>
@@ -0,0 +1,31 @@
<?xml version="1.0" encoding="UTF-8"?>
<!-- Decoupled logic of the guestbook console screen. `gb` is the Screen record the controller put in the model. -->
<thlogic>
<attr sel="#gb-heading" th:text="#{guestbook.console.title}"/>
<attr sel="#gb-flash" th:if="${guestbookFlash != null}"/>
<attr sel="#gb-flash-text" th:text="${guestbookFlash}"/>
<attr sel="#gb-error" th:if="${guestbookError != null}"/>
<attr sel="#gb-error-text" th:text="${guestbookError}"/>
<attr sel="#gb-unavailable" th:unless="${gb.available()}" th:text="#{guestbook.console.unavailable}"/>
<attr sel="#gb-card" th:if="${gb.available()}"/>
<attr sel="#gb-count-label" th:text="#{guestbook.console.count}"/>
<attr sel="#gb-count" th:text="${gb.count()}"/>
<attr sel="#gb-empty" th:if="${gb.page().entries().isEmpty()}" th:text="#{guestbook.console.empty}"/>
<attr sel="#gb-table" th:unless="${gb.page().entries().isEmpty()}"/>
<attr sel="#gb-h-at" th:text="#{guestbook.console.at}"/>
<attr sel="#gb-h-name" th:text="#{guestbook.name}"/>
<attr sel="#gb-h-message" th:text="#{guestbook.message}"/>
<attr sel="#gb-row" th:each="e : ${gb.page().entries()}"/>
<attr sel="#gb-row//.gb-at" th:text="${e.at()}"/>
<attr sel="#gb-row//.gb-name" th:text="${e.name()}"/>
<attr sel="#gb-row//.gb-message" th:text="${e.message()}"/>
<attr sel="#gb-row//.gb-id" th:value="${e.id()}"/>
<attr sel="#gb-row//.gb-delete" th:text="#{guestbook.console.delete}"/>
<attr sel=".gb-csrf"
th:attr="name=${_csrf != null ? _csrf.parameterName : '_csrf'},value=${_csrf != null ? _csrf.token : ''}"/>
<attr sel="#gb-pager" th:if="${gb.page().page() > 0 or gb.page().more()}"/>
<attr sel="#gb-newer" th:if="${gb.page().page() > 0}" th:href="@{''(page=${gb.page().page() - 1})}"
th:text="#{guestbook.console.newer}"/>
<attr sel="#gb-older" th:if="${gb.page().more()}" th:href="@{''(page=${gb.page().page() + 1})}"
th:text="#{guestbook.console.older}"/>
</thlogic>