3 Commits
Author SHA1 Message Date
Runway 9144c206be Runway 1.2.0 2026-10-30 11:24:46 -06:00
Runway 5fa0c1ef9f Runway 1.1.2 2026-10-29 12:42:22 -06:00
Runway 67d61f339c Runway 1.1.1 2026-10-29 11:41:13 -06:00
119 changed files with 4092 additions and 649 deletions

No files matched your search

+231
View File
@@ -2,6 +2,237 @@
All notable changes are recorded here. Versions follow [Semantic Versioning](https://semver.org/). All notable changes are recorded here. Versions follow [Semantic Versioning](https://semver.org/).
## [1.2.0] — 2026-10-30
_A minor release: a site's audit journal records its backups (saved, downloaded, deleted, restored), a restore no
longer erases the site's logs, password settings are never filled in by the browser with your console login, and
the plugin contract gains one method (SPI `1.2.0`: `PluginSettings.savedApp`) that the database plugins 2.0.0 use for
their connection tests. Every plugin that runs on 1.1.2 loads unchanged._
### Upgrading — read this first
**From `1.1.2`: a kernel upgrade, no flag.** From `1.1.1`, `1.1.0`, `1.0.1` or `1.0.0`, read the *Upgrading*
sections of the releases in between first, then install this release directly. Paths are the installer defaults
(`/opt/runway`, `/opt/runway-data`).
**The database plugins.** `database`, `database-postgresql` and `database-mariadb` 1.0.0 keep running on this
release unchanged. Their 2.0.0, released with it, needs it: the server's settings move from the `database` plugin to
the provider plugin, and the connection tests move to the `database` plugin's settings page. Upgrade the kernel
first, then those three plugins together, and move the settings **before** saving the `database` plugin's settings
form (Administration §11.1, *Upgrading from database 1.x*; the plugins' own release notes).
**1. Back up.** Take each site's backup (**Backups**) and copy `/opt/runway-data/external/` somewhere **outside**
`external/plugins/`.
**2. Upgrade the kernel:**
```bash
chmod +x runway-1.2.0.bin
sudo ./runway-1.2.0.bin -y
```
The essential plugin moves with the kernel to `1.2.0` (its two settings pages mark the reCAPTCHA secret as a new
password), so the installer refreshes it; expect these lines, once (a template you edited is backed up instead, and
the line names the copy):
```
refreshing bundled plugin 'protection' from this release (it moves with the kernel; files you edited are backed up)
plugin 'protection': plugin.yml replaced (the previous one kept as plugin.yml.bak, for a rollback)
plugin 'protection': runway-plugin-protection.jar replaced (the previous one kept as runway-plugin-protection.jar.bak, for a rollback)
plugin 'protection': templates/admin-app.html updated (unchanged since it was installed — no backup needed)
plugin 'protection': templates/site-protection.html updated (unchanged since it was installed — no backup needed)
keeping the bundled plugins in the release: /opt/runway-1.2.0/seed/ (the repair copy — Administration §12)
```
**3. Check.**
- **About Runway** shows `1.2.0`.
- On **Plugins**, every row is *Loaded* and none *Blocked*; protection shows `1.2.0`.
- On a site's console, save a backup (**Backups**, *Save a backup on the server*): the site's **Logs** journal
shows `backup.saved` with your name and the backup's.
**4. Rollback**, if needed: `sudo bash runway-1.1.2.bin -y` puts 1.1.2 back, its protection files included. Nothing
this release saves is read differently by 1.1.2. Put the database plugins back to 1.0.0 first if you moved them to
2.0.0 (with the server's settings back in `database.yml`): 2.0.0 needs SPI `1.2.0` and is refused by 1.1.2.
### Added
- **SPI 1.2.0: `PluginSettings.savedApp(key)`.** A plugin can read one of its own app-level settings as it is saved
now, before the restart that applies it (a secret in clear), so it can check a change first. The database plugins
2.0.0 use it for their connection test. Existing plugins load unchanged: the method only adds to the contract. See
`docs/SPI-STABILITY.md`.
- **The site's audit journal records backups.** On the site console, saving a backup on the server (`backup.saved`),
downloading one (`backup.downloaded`: `full`, `transfer`, or `full` and a saved backup's name),
deleting one (`backup.deleted`) and restoring the site (`site.restored`) are now journal lines, with who did it. A
refused act writes nothing. On the application console, downloads join the platform's activity log, which already
had saves, deletes and restores.
- **Journal labels for every recorded action.** User changes (`user.updated`, `user.suspended`, `user.resumed`) and
static-file changes (`static.uploaded`, `static.folder-created`, `static.deleted`) were recorded but shown only by
their key; they now have English and Spanish labels like the others.
### Fixed
- **A restore erased the site's logs.** A restore replaced the whole site folder, and a backup never carries logs
or stats, so the access log and the audit journal started again from nothing (the bandwidth history file too,
until its next periodic save rewrote it from memory). A restore now keeps both folders; if it is interrupted, or
the logs cannot be carried over at once, the next restore of the site or the next start finishes it. Logs or
stats inside an archive are ignored: no backup writes them.
- **A restore could lose the site it replaced.** If a log line was written in the instant between moving the site
folder aside and moving the restored copy in, the site folder came back holding only logs: the restore failed, the
rollback was skipped, and the next start deleted the previous copy. That folder is now set aside and the move
retried, and a folder without a `site.yml` is never taken for the site.
- **A browser could fill a plugin's password setting with your own console login.** On a plugin's settings page, a
text box followed by a password box looks like a login form, and browsers fill it in with the saved console
username and password, ignoring `autocomplete="off"`. A save would then store your console password as the
plugin's credential. Password settings (plugin and widget settings, the protection plugin's CAPTCHA secret, a
master administrator's password reset) are now marked as new passwords, which browsers do not fill in.
## [1.1.2] — 2026-10-29
_A patch release: the access log now records every public request that gets past the protection edge, including the
ones a filter answers on its own: login attempts, refused form posts, a suspended or maintenance site, a slow body's
`408`, an oversized form's `413`, plugin routes such as `robots.txt` and the sitemap._
### Upgrading — read this first
**From `1.1.1`: a kernel upgrade, no flag.** From `1.1.0`, `1.0.1` or `1.0.0`, read `1.1.1`'s and `1.1.0`'s
*Upgrading* first, then install this release directly. Paths are the installer defaults (`/opt/runway`,
`/opt/runway-data`).
**Your access log will carry more lines.** Nothing is removed and the line format is unchanged, but requests that
used to leave no line now leave one: in the `runway.access` stream and in each site's own access log (its **Logs**
screen). Expect, among others, `POST /login -> 302` for a login attempt, `POST /login -> 403` for a form post refused
for its missing token, `-> 503` while a site is suspended, in maintenance or over its quota, `-> 408` for a refused
slow body, `-> 413` for a `PUT`/`PATCH`/`DELETE` form over `runway.endpoints.max-form-bytes`, and `GET /robots.txt`,
`GET /sitemap.xml` and other plugin routes. A tool that reads `runway.access` (a
log shipper, an alert on `4xx`/`5xx` counts, a ban list fed by failed logins) sees these from now on; check any
threshold that assumed they were absent; under a flood of login attempts that gets past the protection edge, the
`runway.access` stream now grows by one line per attempt, which a journal rate limit may also count. Each site's
**Insights** does not count the refusals (it counts only `GET` page views and `404`s), but it now sees plugin routes:
a page a plugin serves counts as a page view, and a plugin route answering `404` (a missing blog post, an icon the
site has not set) appears among the top 404s. Requests the protection edge turns away (`403`/`429`) still go to
`runway.protect` only, throttled, as before.
**1. Back up.** Take each site's backup (**Backups**) and copy `/opt/runway-data/external/` somewhere **outside**
`external/plugins/`.
**2. Upgrade the kernel:**
```bash
chmod +x runway-1.1.2.bin
sudo ./runway-1.1.2.bin -y
```
The essential plugin moves with the kernel to `1.1.2` (its descriptor changes in version only, and its jar is
rebuilt), so the installer refreshes it; expect these lines, once:
```
refreshing bundled plugin 'protection' from this release (it moves with the kernel; files you edited are backed up)
plugin 'protection': plugin.yml replaced (the previous one kept as plugin.yml.bak, for a rollback)
plugin 'protection': runway-plugin-protection.jar replaced (the previous one kept as runway-plugin-protection.jar.bak, for a rollback)
keeping the bundled plugins in the release: /opt/runway-1.1.2/seed/ (the repair copy — Administration §12)
```
**3. Check.**
- **About Runway** shows `1.1.2`.
- On **Plugins**, every row is *Loaded* and none *Blocked*; protection shows `1.1.2`.
- A login form posted without its token appears in the access log:
`curl -s -o /dev/null -w '%{http_code}\n' -H 'Host: <a site host>' -d 'username=x&password=y' http://127.0.0.1:8080/login`
answers `403`, and `journalctl -u runway --since '-5min' | grep 'runway.access' | grep -c 'POST /login -> 403'` is
at least `1`.
**4. Rollback**, if needed: `sudo bash runway-1.1.1.bin -y` puts 1.1.1 back, its protection files included; those
requests then leave no access-log line again. Nothing this release saves is read differently by 1.1.1.
### Fixed
- **The access log records every public request past the protection edge.** It used to be written by the innermost
filter, so any request answered by a filter further out left no line in either the platform log or the site's
own: every attempt at a site's login page, successful or not (Spring Security answers it itself), a form post
refused for its missing token, the `503` of a suspended, maintenance or over-quota site, a request body refused for
arriving too slowly, a `PUT`/`PATCH`/`DELETE` form refused unread for its size, and every plugin route
(`robots.txt`, the sitemap, `llms.txt`, a plugin's form). A password-guessing run against a site's login was
invisible in its access log. The log is now written just inside the protection edge, from where it sees how each
request was answered. A plugin page served by a route now also counts in **Insights** like any other page.
- **Audit lines are kept ahead of access lines when a site's log queue is full.** Both share one queue
(`runway.logs.queue-capacity`); an eighth of it is now held for audit lines, so a flood that fills it drops access
lines first and keeps the `login.failure` records of the very attack that filled it.
### Documentation
- OPERATIONS §3 (what the access log records, and since when), PLUGIN-DEVELOPMENT (which plugin filters' answers are
logged), SITE-MANAGER-GUIDE §3 and §10 (login attempts and refusals on **Logs**; not counted by **Insights**).
## [1.1.1] — 2026-10-29
_A patch release: the slow-request-body limit 1.1.0 introduced now covers form posts and multipart uploads too, and
after a restore the Backups screen shows how the site is reached, for review._
### Upgrading — read this first
**From `1.1.0`: a kernel upgrade, no flag.** From `1.0.1` or `1.0.0`, read `1.1.0`'s *Upgrading* first (behind a
reverse proxy its step 1 matters), then install this release directly: `1.1.0` itself is not needed in between. Paths
are the installer defaults (`/opt/runway`, `/opt/runway-data`).
**1. Back up.** Take each site's backup (**Backups**) and copy `/opt/runway-data/external/` somewhere **outside**
`external/plugins/`.
**2. Upgrade the kernel:**
```bash
chmod +x runway-1.1.1.bin
sudo ./runway-1.1.1.bin -y
```
The essential plugin moves with the kernel to `1.1.1` (its descriptor changes in version only, and its jar is
rebuilt), so the installer refreshes it; expect these lines, once:
```
refreshing bundled plugin 'protection' from this release (it moves with the kernel; files you edited are backed up)
plugin 'protection': plugin.yml replaced (the previous one kept as plugin.yml.bak, for a rollback)
plugin 'protection': runway-plugin-protection.jar replaced (the previous one kept as runway-plugin-protection.jar.bak, for a rollback)
keeping the bundled plugins in the release: /opt/runway-1.1.1/seed/ (the repair copy — Administration §12)
```
**3. Check.**
- **About Runway** shows `1.1.1`.
- On **Plugins**, every row is *Loaded* and none *Blocked*; protection shows `1.1.1`.
- The start log says `request bodies slower than 4096 bytes/s are refused (runway.http.min-request-data-rate)`, with
your value if you changed it.
**4. Rollback**, if needed: `sudo bash runway-1.1.0.bin -y` puts 1.1.0 back, its protection files included; slow form
posts are then held until the idle timeout again. Nothing this release saves is read differently by 1.1.0.
### Fixed
- **Slow request bodies are refused on every path, as 1.1.0 said they would be.** In 1.1.0
`runway.http.min-request-data-rate` was enforced only where a body was read as a stream. Form posts — every login
form, the console's forms, a plugin's form — and multipart uploads were read past it, so a client trickling one in
still held a request thread until the 30-second idle timeout, as in 1.0.1. Runway now checks the rate on every read
of a request body and answers `408 Request Timeout`: within about two seconds for a steady drip (measured: form and
multipart posts at 20 bytes a second, on both login pages and a plugin's form route), and for a client that pauses
between packets when its next packet arrives, within one idle timeout. Only time spent waiting for the client
counts, and a body that has arrived complete is never refused, however late its last packet came. A proxy that
buffers the whole request body before forwarding it kept such clients off Runway already, in 1.1.0 too.
- **Sending part of a body fast no longer buys a long drip.** 1.1.0 averaged over the whole body, so a client that
sent most of a large one at full speed could then drip the rest for the body's size divided by the rate (16 MiB at
4 KiB/s: over an hour). Bytes sent early now earn at most 30 seconds of waiting.
- **A request refused for a slow body is answered `408`.** Depending on how the code above handled the failed read,
1.1.0 could answer it `400` (a form parser's "unable to parse") or an empty `200`.
### Changed
- **After a restore, the Backups screen shows how the site is reached.** On the application console, after a restore
or after creating a site from a backup, the screen shows the site's hosts and base URL as they now are, with the
same editor as **Sites → Edit hosts**: a restore made there brings back the hosts and base URL saved in the backup,
which may not be how this installation reaches the site. On a site's own console the hosts are shown read-only: a
restore made there keeps them. See `docs/ADMINISTRATION.md` §10.
### Documentation
- **Exempting a same-host proxy's health check from the rate limit** (`docs/ADMINISTRATION.md` §12.4): the proxy sends
its check with a fixed `X-Forwarded-For` that no visitor can produce, and that one address is listed in protection's
allowlist, so the check never shares a rate-limit bucket with a local crawl and loopback stays limited.
## [1.1.0] — 2026-10-29 ## [1.1.0] — 2026-10-29
_A minor release: plugins can keep their data in PostgreSQL or MariaDB through the new database plugins, platform _A minor release: plugins can keep their data in PostgreSQL or MariaDB through the new database plugins, platform
+153 -19
View File
@@ -710,7 +710,7 @@ from the configuration metadata shipped in the jar.
| `runway.security.secret-key` | _(installer-set)_ | Master key for AES-256-GCM encryption of every stored secret (platform SMTP password or OAuth2 client secret, per-site CAPTCHA secrets, `secret`-typed plugin settings). The installer generates one on first install and stores it in a root-only systemd drop-in as `RUNWAY_SECURITY_SECRET_KEY` (see `--secret-key`, §3); Spring's relaxed binding maps that env var to this property. **While blank the secret cipher is unavailable and no secret can be saved** — the app console shows a persistent warning on every page until it is set. Holds a real secret — never in the classpath default. | | `runway.security.secret-key` | _(installer-set)_ | Master key for AES-256-GCM encryption of every stored secret (platform SMTP password or OAuth2 client secret, per-site CAPTCHA secrets, `secret`-typed plugin settings). The installer generates one on first install and stores it in a root-only systemd drop-in as `RUNWAY_SECURITY_SECRET_KEY` (see `--secret-key`, §3); Spring's relaxed binding maps that env var to this property. **While blank the secret cipher is unavailable and no secret can be saved** — the app console shows a persistent warning on every page until it is set. Holds a real secret — never in the classpath default. |
| `runway.proxy.forwarded-headers` | `true` | Whether to honor `X-Forwarded-*` at all (still only from trusted peers; the standard `Forwarded` header is never read) — see **§7**. | | `runway.proxy.forwarded-headers` | `true` | Whether to honor `X-Forwarded-*` at all (still only from trusted peers; the standard `Forwarded` header is never read) — see **§7**. |
| `runway.proxy.trusted-cidrs` | `127.0.0.1/32`, `::1/128` | Proxy peers whose forwarded headers are trusted. The **bound default is empty** (trust nothing); the shipped file seeds loopback. **§7**. | | `runway.proxy.trusted-cidrs` | `127.0.0.1/32`, `::1/128` | Proxy peers whose forwarded headers are trusted. The **bound default is empty** (trust nothing); the shipped file seeds loopback. **§7**. |
| `runway.http.min-request-data-rate` | `4096` | The slowest a request body may arrive, in **bytes per second**, before Runway answers `408 Request Timeout` and frees the request thread. Without it a client sending a byte now and then kept a thread for as long as it liked (the idle timeout only limits one stalled read). Measured from the body's first byte on what has arrived, so a server slow to start reading is never blamed. 4096 (4 KiB/s) is below any real connection; `0` turns the check off. Set on **Settings → Server settings → Request limits**; applies after a restart. | | `runway.http.min-request-data-rate` | `4096` | The slowest a request body may arrive, in **bytes per second**, before Runway answers `408 Request Timeout` and frees the request thread. It applies to every body — login and other forms, multipart uploads, raw bodies alike. Without it a client sending a byte now and then kept a thread for as long as it liked (the idle timeout only limits one stalled read). Only the time spent waiting for the client counts, from the first second of waiting on, so a server slow to start reading is never blamed, and a body that has arrived complete is never refused, however late its last packet came. Sending part of a body fast earns at most 30 seconds of waiting, so a large body cannot buy a long drip; a client pausing between packets is cut when its next packet arrives, within one idle timeout. 4096 (4 KiB/s) is below any real connection; `0` turns the check off. Set on **Settings → Server settings → Request limits**; applies after a restart. |
| `runway.i18n.cache-seconds` | `5` | How often a message lookup **outside** a public page (an error page, a plugin's background text) and the operator console's own bundle re-check their files on disk (`0` = on every lookup). Public pages re-check on every request, so a bundle edited on disk shows on the next page view, under a new ETag. | | `runway.i18n.cache-seconds` | `5` | How often a message lookup **outside** a public page (an error page, a plugin's background text) and the operator console's own bundle re-check their files on disk (`0` = on every lookup). Public pages re-check on every request, so a bundle edited on disk shows on the next page view, under a new ETag. |
| `runway.csp.mode` | `report` | Content-Security-Policy delivery: `report` (report-only — violations are logged, nothing is blocked), `enforce`, or `off`. Upper or lower case; blank means `report`. Any other value (`enforced`, say) stops startup with a message naming it. See **§8.4**. | | `runway.csp.mode` | `report` | Content-Security-Policy delivery: `report` (report-only — violations are logged, nothing is blocked), `enforce`, or `off`. Upper or lower case; blank means `report`. Any other value (`enforced`, say) stops startup with a message naming it. See **§8.4**. |
| `runway.csp.strict-dynamic` | `true` | `'strict-dynamic'` on the nonced pages. `false` rolls the whole estate (console **and** public pages) back to the host allowlist. **§8.4**. | | `runway.csp.strict-dynamic` | `true` | `'strict-dynamic'` on the nonced pages. `false` rolls the whole estate (console **and** public pages) back to the host allowlist. **§8.4**. |
@@ -1588,7 +1588,10 @@ wherever a site gets hosts: creating a site, installing a demo, and creating a s
malformed host or one another site answers on, before anything is created. Restoring a backup brings back the malformed host or one another site answers on, before anything is created. Restoring a backup brings back the
hosts and base URL the site had when the backup was taken when it is made from the application console (a host hosts and base URL the site had when the backup was taken when it is made from the application console (a host
given to another site since then is left off, the log says which: `restored site '…' without host(s) […]`, and you given to another site since then is left off, the log says which: `restored site '…' without host(s) […]`, and you
can add it back with **Edit hosts** once it is free). A restore made from the site's own console keeps the hosts and can add it back with **Edit hosts** once it is free). After such a restore, and after creating a site from a backup,
the Backups screen shows the site's hosts and base URL **as they now are**, with the same editor as **Edit hosts**:
check them before anything else, because a backup taken on another installation, or before the site moved, brings
back how it was reached then. A restore made from the site's own console keeps the hosts and
base URL the site has: how a site is reached is yours to set, never the site manager's, and a backup file is base URL the site has: how a site is reached is yours to set, never the site manager's, and a backup file is
theirs to write. A host is a plain DNS name: no scheme, path, theirs to write. A host is a plain DNS name: no scheme, path,
port (`example.com:8080`), wildcard (`*.example.com`) or underscore, and an international name is written in its port (`example.com:8080`), wildcard (`*.example.com`) or underscore, and an international name is written in its
@@ -1947,14 +1950,80 @@ chosen in settings. Nothing uses them unless a plugin that needs a database is i
| Plugin | What it is | | Plugin | What it is |
|---|---| |---|---|
| `database` | The generic plugin: the connection pool, the settings, one schema per site, migrations, backups, the **Database** screen. Requires Runway 1.1.0 or later. | | `database` | The generic plugin: the connection pool, the provider choice and the limits, one schema per site, migrations, backups, the **Database** screen and the connection tests. Version 2.0.0 requires Runway 1.2.0 or later (1.0.0 ran on 1.1.0). |
| `database-postgresql` | The PostgreSQL provider: bundles the pgjdbc driver. PostgreSQL **14 or later**, database encoding `UTF8`. | | `database-postgresql` | The PostgreSQL provider: bundles the pgjdbc driver and holds the server's settings (host, account, password, TLS). PostgreSQL **14 or later**, database encoding `UTF8`. |
| `database-mariadb` | The MariaDB provider: bundles MariaDB Connector/J (LGPL-2.1; its unmodified sources are published next to the zip). MariaDB **10.11 or later**; MySQL is not supported. | | `database-mariadb` | The MariaDB provider: bundles MariaDB Connector/J (LGPL-2.1; its unmodified sources are published next to the zip) and holds the server's settings, collation included. MariaDB **10.11 or later**; MySQL is not supported. |
Install `database` and the provider for your server (installing both providers is harmless: the setting picks one), Install `database` and the provider for your server, then restart. With one provider installed, it is the one used;
then restart. A plugin that needs the database declares it, so without `database` it shows as **Blocked** with the with both, the database plugin's `provider` setting picks one. A plugin that needs the database declares it, so without `database` it shows as **Blocked** with the
reason, and Runway runs normally. reason, and Runway runs normally.
**Setting it up, step by step.** The whole path for one server; each step is explained further down.
1. **Prepare the server**: an account and a UTF-8 database for Runway (*Preparing the server*, below). On PostgreSQL
the account only owns that database; on MariaDB it also needs the grant on the namespace's databases.
2. **Install the plugins.** From the release (the plugin zips are published with each Runway release, §11), download `runway-plugin-database-<version>.zip`, the provider's
zip (`runway-plugin-database-postgresql-…` or `runway-plugin-database-mariadb-…`) and `SHA256SUMS`, check them
(`sha256sum -c --ignore-missing SHA256SUMS`), and upload each zip on **Plugins**. Add the plugins that will use
the database (for a first try, `runway-demo-database`, the guestbook). Do not restart yet.
3. **Enter the settings**: the server, the account, the password and TLS on the provider's page (**Plugins →
Database — PostgreSQL → Settings**, or **Database — MariaDB**), or in its settings file (*Setting it up without the
console*, below). The database plugin's own page (**Plugins → Database → Settings**) needs a change only when both
providers are installed, or for the namespace and the limits. Settings take effect on the next restart.
4. **Test them**: on **Plugins → Database → Settings**, below the form, **Connection tests** → **Test the saved
PostgreSQL settings** (or MariaDB) connects once with what is saved and changes nothing. The answer is one of those
in *When it does not connect*, below.
5. **Restart once.** Runway starts without waiting for the database, then connects on its own thread.
6. **Check**: **Settings → Database** says *Connected* and shows the server's version; the server log has one line
`database: connected to … (postgresql), namespace 'rw'` (or `mariadb`). If it says anything else, see *When it
does not connect*, below.
7. **Try it** (with the guestbook): place `<div id="guestbook" data-widget="guestbook/main"></div>` on a page of a
site, sign the guestbook as a visitor, and the site's schema appears on the server (`rw_s_<site>_<n>`); the entries
are managed under **Guestbook** in that site's console (the site superadmin has it; anyone else needs the
guestbook's *manage* permission, granted on **Permissions**).
**Setting it up without the console.** The server's settings live in the provider's file,
`external/plugin-settings/database-postgresql.yml` (or `database-mariadb.yml`), nested under
`runway.plugin.<provider plugin id>` like every plugin's (§11). `host`, `database` and `username` are required; the
other keys keep their defaults when absent:
```yaml
# external/plugin-settings/database-postgresql.yml (owner: the service account; mode 600 — it holds the password)
runway:
plugin:
database-postgresql: # database-mariadb for MariaDB
host: "127.0.0.1"
port: 5432 # blank or absent: 5432 / 3306
database: "runway"
username: "runway"
password: "…"
tls: disable # same host only; otherwise verify-full (the default) or require
```
The database plugin's own file, `external/plugin-settings/database.yml` (under `runway.plugin.database`), is needed
only to choose the provider when both are installed (`provider: postgresql` or `mariadb`; the default `auto` uses the
one installed), or to change the namespace or a limit.
The password may be written **in clear**: it is used as written and stays in clear in the file. Runway does not
encrypt a hand-written value, and nothing outside the console can produce the encrypted `ENC(...)` form; it is made
only when the password is typed on the settings form, with the platform secret key (§8). So either keep the file
readable by the service account only (`chown runway: …; chmod 600 …`), or type the password once on the form, which
replaces it with `ENC(...)`. Saving the form with the password field left blank keeps whatever is stored, clear or
encrypted, as long as the settings it is bound to do not change (below).
**Upgrading from database 1.x.** Until 2.0.0 the server's settings were in the database plugin's own file. After the
upgrade, a `database.yml` that still holds them gives the status *Not configured: the server settings moved to the
database-postgresql plugin in database 2.0.0: move host, …* and Runway does not connect with them. Move every server
key (`host`, `port`, `database`, `username`, `password`, `tls`, `caCertificate`, and on MariaDB `collation`) into the
provider's file, under `runway.plugin.database-postgresql` (or `database-mariadb`), as above; keep `provider`,
`namespace` and the limits in `database.yml`. An encrypted password (`ENC(...)`) can be moved as it is: it is
encrypted with the platform secret key, not with anything tied to the file. **Move the keys before you save the
Database plugin's settings form**: a save writes only the settings the form has, so it removes the old server keys
from `database.yml`, encrypted password included (if that happens, type the settings on the provider's page). Or retype the settings on the provider's
page and delete the old keys. Install the 2.0.0 versions of all three plugins together; a 1.x provider with
database 2.0.0 gives *No provider: the database-postgresql plugin is older than 2.0.0*. Then test (step 4 above)
and restart.
**What Runway creates.** Every name starts with the **namespace** (setting `namespace`, default `rw`): **What Runway creates.** Every name starts with the **namespace** (setting `namespace`, default `rw`):
- `<ns>_app` — Runway's own registry tables (`rw_…`) and data that belongs to no site; - `<ns>_app` — Runway's own registry tables (`rw_…`) and data that belongs to no site;
@@ -1978,6 +2047,13 @@ CREATE DATABASE runway OWNER runway ENCODING 'UTF8' TEMPLATE template0;
would refuse it; on a UTF-8 cluster it changes nothing. If PostgreSQL then answers that the encoding does not match would refuse it; on a UTF-8 cluster it changes nothing. If PostgreSQL then answers that the encoding does not match
the locale, the cluster's locale is not UTF-8 either: add `LOCALE 'C.UTF-8'` (PostgreSQL 14 and later). the locale, the cluster's locale is not UTF-8 either: add `LOCALE 'C.UTF-8'` (PostgreSQL 14 and later).
Owning the database is all the account needs: Runway creates its schemas inside it. The server must accept the
account over TCP with a password: on PostgreSQL that is a `pg_hba.conf` line for the database, the account and the
address Runway connects from, for example `host runway runway 127.0.0.1/32 scram-sha-256` for a server on the same
host (reload PostgreSQL after editing it), and, for a server on another host, `listen_addresses` covering an
interface Runway can reach. Give the host as `127.0.0.1` rather than `localhost` to avoid depending on which of
`127.0.0.1` and `::1` the name resolves to.
```sql ```sql
-- MariaDB (as root). The pattern is the namespace, then an escaped underscore: `rw\_%` for the default `rw`. -- MariaDB (as root). The pattern is the namespace, then an escaped underscore: `rw\_%` for the default `rw`.
CREATE USER 'runway'@'10.0.0.%' IDENTIFIED BY '…'; CREATE USER 'runway'@'10.0.0.%' IDENTIFIED BY '…';
@@ -1989,21 +2065,35 @@ GRANT ALL PRIVILEGES ON `rw\_%`.* TO 'runway'@'10.0.0.%';
A MariaDB account without the pattern grant connects but cannot create the namespace's databases: the **Database** A MariaDB account without the pattern grant connects but cannot create the namespace's databases: the **Database**
screen stays at *Connecting* with an "Access denied" error until the grant exists. screen stays at *Connecting* with an "Access denied" error until the grant exists.
**Settings** (**Plugins → database → Settings**, Runway-wide, applied on **restart**): **Settings** (Runway-wide, applied on **restart**). The server's, on the provider's page (**Plugins → Database —
PostgreSQL → Settings**, or **Database — MariaDB**):
| Setting | Meaning | | Setting | Meaning |
|---|---| |---|---|
| `provider` | `postgresql` or `mariadb`. |
| `host`, `port` | One server: a host name or an IP address (no lists, no options). A blank port means 5432 / 3306. | | `host`, `port` | One server: a host name or an IP address (no lists, no options). A blank port means 5432 / 3306. |
| `database` | The database to connect to (see above). | | `database` | The database to connect to (see above). |
| `username`, `password` | The account. The password is stored encrypted. It is **bound** to provider, host, port, database, username, TLS and the CA certificate: change any of them without typing the password again and the stored password is removed, so it can never be sent to a server someone else chose. | | `username`, `password` | The account. The password is stored encrypted. It is **bound** to host, port, database, username, TLS and the CA certificate: change any of them without typing the password again and the stored password is removed, so it can never be sent to a server someone else chose. |
| `tls` | `verify-full` (default: encrypted, the certificate and the host name checked against the Java trust store or `caCertificate`), `require` (encrypted, the server **not** checked), `disable`. Use `disable` only for a database on the same host or a private network you trust. | | `tls` | `verify-full` (default: encrypted, the certificate and the host name checked against the Java trust store or `caCertificate`), `require` (encrypted, the server **not** checked), `disable`. Use `disable` only for a database on the same host or a private network you trust. |
| `caCertificate` | Advanced. The PEM certificate of the CA that signed the server's certificate, when the Java trust store does not know it. | | `caCertificate` | Advanced. The PEM certificate of the CA that signed the server's certificate, when the Java trust store does not know it. |
| `collation` | Advanced, MariaDB's page only: for plugins' tables. Blank means `utf8mb4_uca1400_ai_ci`. Runway's own identifier columns are always binary. |
The rest, on the database plugin's page (**Plugins → Database → Settings**):
| Setting | Meaning |
|---|---|
| `provider` | `auto` (default: the one provider plugin installed), `postgresql` or `mariadb`. Needed only when both providers are installed. |
| `namespace` | Advanced. Default `rw`; lower-case letters and digits, up to 12. Changing it later starts from empty schemas: the old ones stay on the server. | | `namespace` | Advanced. Default `rw`; lower-case letters and digits, up to 12. Changing it later starts from empty schemas: the old ones stay on the server. |
| `poolMax` | Connections plugins may hold at once (default 10). One site may use at most half, so a busy site cannot starve the others. | | `poolMax` | Connections plugins may hold at once (default 10). One site may use at most half, so a busy site cannot starve the others. |
| `statementTimeoutSeconds` | A plugin's statement that runs longer is stopped (default 10). Migrations, backups and restores have their own 30-minute limit. | | `statementTimeoutSeconds` | A plugin's statement that runs longer is stopped (default 10). Migrations, backups and restores have their own 30-minute limit. |
| `backupBudgetMiB` | The compressed size a site's database data may reach in its backup (default 128). | | `backupBudgetMiB` | The compressed size a site's database data may reach in its backup (default 128). |
| `collation` | Advanced, MariaDB only: for plugins' tables. Blank means `utf8mb4_uca1400_ai_ci`. Runway's own identifier columns are always binary. |
**Connection tests**, below the database plugin's settings form (same permission as the form, and the same as the
Database screen: `CONFIGURE_PLATFORM`): *Running now* shows the status; **Test the running connection** borrows from
the live pool; **Test the saved PostgreSQL settings** (one button per installed provider) opens one throwaway
connection with the settings saved on that provider's page — which the next restart would apply — and changes
nothing. The tests take no typed values: a form with a username and a password box is one a browser fills in with
your own saved console login, which a test would then send to whatever server the form named. Answers are fixed
categories (below); the driver's own message goes only to the server log, never with a password.
**Runway never fails to start because of the database.** Nothing connects while Runway starts; the plugin connects **Runway never fails to start because of the database.** Nothing connects while Runway starts; the plugin connects
right after, on its own thread, retrying with back-off. Until it succeeds, plugins that need it say so (for example right after, on its own thread, retrying with back-off. Until it succeeds, plugins that need it say so (for example
@@ -2015,11 +2105,7 @@ administrators hold) shows:
- the status: *Connected*, *Connecting* (with the last error), *Not configured* (with the setting at fault), *No - the status: *Connected*, *Connecting* (with the last error), *Not configured* (with the setting at fault), *No
provider*, or *Server not supported*; the provider, server version, driver, pool use and the number of sites with provider*, or *Server not supported*; the provider, server version, driver, pool use and the number of sites with
data; data;
- **Test running connection** (the live pool) and **Test these settings** (typed values, one throwaway connection, - a link to the settings page and its **Connection tests** (above);
nothing saved). Answers are fixed categories — unreachable, TLS failure, authentication failed, database missing or
no access, unsupported server — and the driver's own message goes only to the server log, never with a password.
A blank password in the test reuses the saved one only for exactly the same provider, server, database, account and
TLS settings;
- **Plugin tables needing attention**, with recovery actions (below); - **Plugin tables needing attention**, with recovery actions (below);
- the plugins using the database, the nodes seen in the last five minutes, the largest site backup against the - the plugins using the database, the nodes seen in the last five minutes, the largest site backup against the
budget (a warning from 75%), and the last failed restore. budget (a warning from 75%), and the last failed restore.
@@ -2040,7 +2126,28 @@ sites carry on — and the screen lists the case:
Every recovery action is written to the server log with the operator's name. Every recovery action is written to the server log with the operator's name.
**Clusters.** Every node needs the same `external/plugin-settings/database.yml` and the same platform secret key **When it does not connect.** The **Database** screen's status, and the server log's `database:` lines, say why;
**Test the saved … settings** checks what is saved before you restart. While the status is *Connecting*,
Runway retries on its own, waiting twice as long each time up to a minute (every 5 minutes for *Server not
supported*); a fixed server is picked up without a restart. A changed setting needs a restart.
| Status / test answer | Usual cause | What to do |
|---|---|---|
| *Not configured: …* (log: `database: not configured: …`; test: *The settings cannot be used: …*) | A setting is missing or invalid; the message names the plugin and the setting (for example *database-postgresql settings: no host is set*), or says *no server is set* on the provider's page, or *both provider plugins are installed* (choose one in `provider`), or *the server settings moved* (*Upgrading from database 1.x*, above). | Set it and restart. |
| *No provider: …* | No provider plugin is installed, `provider` names a product whose plugin is not, two plugins offer the same product, or the provider is older than 2.0.0 (*the database-postgresql plugin is older than 2.0.0*). | Install `database-postgresql` or `database-mariadb` (2.0.0 or later), or change `provider`; restart. |
| *Connecting:* … / *The server could not be reached.* | Wrong host or port, the server is down, it listens on another interface, or a firewall is in between. The connection attempt gives up after 5 seconds. | From the Runway host, check the address and port (`pg_isready -h … -p …`, `nc -vz … 3306`); `listen_addresses` / `bind-address` on the server. |
| *The server refused the username or password.* | Wrong password; on PostgreSQL, no `pg_hba.conf` line matches the database, account and Runway's address; on MariaDB, no account matches the address Runway connects from. | Fix the password (retype it; §11 on bound secrets), the `pg_hba.conf` line (then reload), or the account's host part. |
| *The TLS handshake failed* | `verify-full` against a server whose certificate the Java trust store does not know (a private CA, or a self-signed certificate), or whose name does not match `host`; or TLS asked for from a server that has none (on PostgreSQL the status shows *The server does not support SSL*; database 1.0.0 reported this one as a refused password). | Paste the CA into `caCertificate`, use the name on the certificate as `host`, or, for a server on the same host or a trusted private network only, `tls: disable`. |
| *The database does not exist on the server, or the account has no access to it.* | The `database` setting names a database that is not there, or (MariaDB) the account has no rights on it. On PostgreSQL an account without the `CONNECT` right answers *The test failed; see the server log*. | Create it as shown above, or fix the name. |
| *Connecting:* … *Access denied* (MariaDB) | The account connects but lacks the grant on the namespace's databases. | Add the namespace pattern grant shown above. |
| *Server not supported: …* | PostgreSQL older than 14, MariaDB older than 10.11, MySQL, or a PostgreSQL database whose encoding is not UTF-8 (*the database's encoding is … UTF8 is needed*). | Upgrade the server or use another one; recreate the database as UTF-8 as shown above. |
The test answers are fixed categories. The status and *Last error* on the screen, and the log's `database:` line,
carry the driver's own message (never a password): the exception, its SQL state and the text, which is where the
detail is.
**Clusters.** Every node needs the same `external/plugin-settings/database.yml` and provider file
(`database-postgresql.yml` or `database-mariadb.yml`) and the same platform secret key
(`runway.security.secret-key`), because the password is stored encrypted with it. The database is shared, so a site (`runway.security.secret-key`), because the password is stored encrypted with it. The database is shared, so a site
deleted on one node has its schema dropped once, by that node. To change the server or the provider, stop **every** deleted on one node has its schema dropped once, by that node. To change the server or the provider, stop **every**
node first. node first.
@@ -2431,6 +2538,24 @@ runway:
- "198.51.100.7" # the audit runner - "198.51.100.7" # the audit runner
``` ```
**A health check from a proxy on the same host.** Behind a same-host reverse proxy, the proxy's own health check
(`GET /actuator/health` or a site's `/__health`) usually reaches Runway from loopback with no `X-Forwarded-For`, so it
shares one rate-limit bucket with everything else run on that host — a local crawl or audit can then earn the check
`429`s and push the proxy towards marking the server down. Exempt the check alone, not loopback: have the proxy send
it with a fixed `X-Forwarded-For` from a documentation range, and list that address here. No visitor can pose as
it: on real traffic the proxy adds the visitor's own address to the right of anything the visitor sent (or replaces
the header), and Runway reads the header from the right. With HAProxy 2.2 or later:
```
backend runway
option httpchk
http-check send meth GET uri /actuator/health ver HTTP/1.1 hdr Host www.example.com hdr X-Forwarded-For 192.0.2.53
```
and `192.0.2.53` in `allowlist`. Loopback must be in `runway.proxy.trusted-cidrs` (it is, for a same-host proxy);
leave the probe's address out of it, which is for real proxies only. Checking
`/actuator/health` from outside the proxy (a monitoring service) needs no header: list that service's own address.
> **If you are blocked, stop — do not keep probing.** Once an address is auto-blocked, requests no longer > **If you are blocked, stop — do not keep probing.** Once an address is auto-blocked, requests no longer
> reach the rate limiter at all; they hit the blocklist. So the `rate-limit` counter freezes while > reach the rate limiter at all; they hit the blocklist. So the `rate-limit` counter freezes while
> `blocklist-auto` keeps climbing, and continued probing simply confirms the block rather than measuring it. > `blocklist-auto` keeps climbing, and continued probing simply confirms the block rather than measuring it.
@@ -2487,6 +2612,14 @@ holder and explains why; the routes answer `403` regardless. A backup the holder
there for an administrator — or the platform operator, on `/__app/backups` — to download or restore. See the there for an administrator — or the platform operator, on `/__app/backups` — to download or restore. See the
*Site Manager & Designer Guide* §12 for the end-user workflow. *Site Manager & Designer Guide* §12 for the end-user workflow.
**Who did it is recorded.** Each backup act on the site console that took effect — saving, downloading (full,
transfer, or a saved backup), deleting and restoring — is a line in that site's own audit journal (`backup.saved`,
`backup.downloaded`, `backup.deleted`, `site.restored`; Site Manager & Designer Guide §3). The same acts on
`/__app/backups` are in the platform's activity log, under the same names, and not in the site's journal. **A
restore keeps the site's logs and traffic history** (on either console): it replaces the content only, so the
journal still holds what happened before it; logs or stats inside an archive are ignored, as no backup writes them.
A site created from a backup starts its own logs.
**Pending editorial work travels with the site.** On a site whose manager has turned on review **Pending editorial work travels with the site.** On a site whose manager has turned on review
(*Site Manager & Designer Guide* §10), changes waiting for approval are kept beside their pages under (*Site Manager & Designer Guide* §10), changes waiting for approval are kept beside their pages under
`sites/<id>/templates/.pending/<slug>/`. They are site content, never served, listed or indexed: a backup `sites/<id>/templates/.pending/<slug>/`. They are site content, never served, listed or indexed: a backup
@@ -2522,7 +2655,7 @@ with:
- `users.yml` and `permissions.yml` **omitted** — accounts, hashes and grants; - `users.yml` and `permissions.yml` **omitted** — accounts, hashes and grants;
- traffic history (`stats/bandwidth.csv`) and logs — absent, as from **every** backup: they are transient - traffic history (`stats/bandwidth.csv`) and logs — absent, as from **every** backup: they are transient
per-site data that no backup carries; per-site data that no backup carries (and a restore keeps the target site's own);
- every per-site plugin value that is **declared** secret, stored `ENC(...)`, or **named** like a credential - every per-site plugin value that is **declared** secret, stored `ENC(...)`, or **named** like a credential
(`secret`, `password`, `passwd`, `token`, `credential`, `apiKey`, `privateKey`) — **blanked** at any depth, (`secret`, `password`, `passwd`, `token`, `credential`, `apiKey`, `privateKey`) — **blanked** at any depth,
including inside nested maps and lists, and kept as an empty key so the recipient sees what to fill in; including inside nested maps and lists, and kept as an empty key so the recipient sees what to fill in;
@@ -2754,7 +2887,8 @@ Each site keeps its own access log (its public traffic) and audit log (its manag
- `runway.logs.queue-capacity` (default `8192`, at least `16`) — log lines wait in a queue between the request and - `runway.logs.queue-capacity` (default `8192`, at least `16`) — log lines wait in a queue between the request and
the disk, so a slow disk never slows a page. When the queue is full, new lines are **dropped**, not waited for: the disk, so a slow disk never slows a page. When the queue is full, new lines are **dropped**, not waited for:
the count is the `runway_logs_dropped` metric (and the Logs screen), and a `WARN` *"site log queue saturated"* is the count is the `runway_logs_dropped` metric (and the Logs screen), and a `WARN` *"site log queue saturated"* is
logged at most once a minute. Raise it if that count grows; each queued line takes a little memory. logged at most once a minute. An eighth of the queue is held for audit lines (sign-ins, changes), so a flood of
public requests drops access lines first. Raise it if that count grows; each queued line takes a little memory.
### Bandwidth metering (`runway.bandwidth.*`) ### Bandwidth metering (`runway.bandwidth.*`)
+11 -2
View File
@@ -223,7 +223,9 @@ is written **only in detached launcher mode** — the supervisor appends the JVM
usually empty; do not go looking for application logs there when running as a service. usually empty; do not go looking for application logs there when running as a service.
**The public access log.** One line is emitted per **public** request under the logger **The public access log.** One line is emitted per **public** request under the logger
`runway.access`, from the innermost filter (so the status is final): `runway.access`, written once every filter and handler has finished with it, so with the status it was answered
with (the one exception: an error escaping a plugin's own controller is logged with the status set before it,
while the client receives `500`):
``` ```
203.0.113.7 GET /about -> 200 (12ms) 203.0.113.7 GET /about -> 200 (12ms)
@@ -237,6 +239,13 @@ fetch will **not** appear here; that is by design (this is a traffic log, not an
client IP is the gated one (from a trusted forwarded header only — see Administration §7), never a client IP is the gated one (from a trusted forwarded header only — see Administration §7), never a
raw spoofable header. raw spoofable header.
It records **every** public request that gets past the protection edge (§3.1), whoever answers it: a page, a
plugin's route (`robots.txt`, the sitemap, a form), the sign-in form (every login attempt, successful or not, and
a form post refused for its missing token, `403`), an oversized form refused unread (`413`), a suspended, maintenance or over-quota site (`503`), and a
request body refused for arriving too slowly (`408`). Before 1.1.2 every one of these except the page was missing,
because the log was written by the innermost filter and each of them is answered by a filter outside it. Only the
edge's own `403`/`429` stay out: those go to `runway.protect` (§3.1).
**What to grep for** (systemd, hence `journalctl`): **What to grep for** (systemd, hence `journalctl`):
```bash ```bash
@@ -302,7 +311,7 @@ rejections, §3.1); everything else logs under its package, `mx.quest.runway.*`.
### 3.1 Seeing what the edge rejected ### 3.1 Seeing what the edge rejected
A request the protection edge turns away is rejected at `FilterOrder.CORE_PROTECTION` — the outermost slot — A request the protection edge turns away is rejected at `FilterOrder.CORE_PROTECTION` — the outermost slot —
and the chain is never called. The access log lives at the innermost slot. So a `403`/`429` from the edge and the chain is never called. The access log sits just inside that slot, so a `403`/`429` from the edge
**appears in no other log**, and without a log of its own a site manager would have no way to tell that a **appears in no other log**, and without a log of its own a site manager would have no way to tell that a
crawler was being throttled. crawler was being throttled.
+15 -6
View File
@@ -5,7 +5,7 @@
> the contribution seams, settings, permissions, and the rules that keep plugins compatible. > the contribution seams, settings, permissions, and the rules that keep plugins compatible.
> **Doc status.** The plugin contract is **SPI `1.0.0`, frozen** (Runway `1.0.0`): from here it changes only > **Doc status.** The plugin contract is **SPI `1.0.0`, frozen** (Runway `1.0.0`): from here it changes only
> additively within `1.x` (SPI `1.1.0` added `PluginSettings.appSecret`) — the commitment and the full type list are in [SPI-STABILITY.md](SPI-STABILITY.md); the > additively within `1.x` (SPI `1.1.0` added `PluginSettings.appSecret`, `1.2.0` `PluginSettings.savedApp`) — the commitment and the full type list are in [SPI-STABILITY.md](SPI-STABILITY.md); the
> `plugin.yml` keys and their tolerance rules are covered by > `plugin.yml` keys and their tolerance rules are covered by
> [CONFIGURATION-AND-DATA-STABILITY.md](CONFIGURATION-AND-DATA-STABILITY.md) §4. A plugin is built against > [CONFIGURATION-AND-DATA-STABILITY.md](CONFIGURATION-AND-DATA-STABILITY.md) §4. A plugin is built against
> `runway-spi` **only**; the kernel refuses one that links its internal classes (§3, *The 1.0 contract at a > `runway-spi` **only**; the kernel refuses one that links its internal classes (§3, *The 1.0 contract at a
@@ -104,7 +104,7 @@ boots.
> **Which floor to declare.** The lowest SPI version whose additions you use — the evolution log on > **Which floor to declare.** The lowest SPI version whose additions you use — the evolution log on
> `RunwaySpi.VERSION` lists them per version. `>=0.4.0`, `>=0.5.0` and `>=0.6.0` are all **1.x floors** (the service > `RunwaySpi.VERSION` lists them per version. `>=0.4.0`, `>=0.5.0` and `>=0.6.0` are all **1.x floors** (the service
> tier those versions introduced is the 1.0 contract), so a plugin built against them loads on every `1.x` kernel; > tier those versions introduced is the 1.0 contract), so a plugin built against them loads on every `1.x` kernel;
> declare `>=1.0.0` only if you use `HeadContext.origin()`, and `>=1.1.0` if you call `PluginSettings.appSecret`. The floor is an **SPI level** — the value of > declare `>=1.0.0` only if you use `HeadContext.origin()`, `>=1.1.0` if you call `PluginSettings.appSecret`, and `>=1.2.0` if you call `PluginSettings.savedApp`. The floor is an **SPI level** — the value of
> `RunwaySpi.VERSION` — not the version of the `runway-spi` artifact you compile against, which is the kernel's > `RunwaySpi.VERSION` — not the version of the `runway-spi` artifact you compile against, which is the kernel's
> release version (kernel `1.0.0` carries SPI `1.0.0`; §3). > release version (kernel `1.0.0` carries SPI `1.0.0`; §3).
@@ -216,7 +216,7 @@ Then depend on `mx.quest:runway-spi:<ver>` (`provided`) and `mx.quest:runway-spi
| You need | Use | Never | | You need | Use | Never |
|---|---|---| |---|---|---|
| your per-site settings and secrets (app-level ones: `@ConfigurationProperties("runway.plugin.<id>")`; an app-level secret in clear: `PluginSettings.appSecret`, SPI 1.1.0) | `PluginSettings` (+ `SettingsView`) | `SitePluginConfigService`, `SecretCipher`, `@Value("${runway.plugin…}")` on a per-site key | | your per-site settings and secrets (app-level ones: `@ConfigurationProperties("runway.plugin.<id>")`; an app-level secret in clear: `PluginSettings.appSecret`, SPI 1.1.0; an app-level setting as saved, before the restart applies it: `PluginSettings.savedApp`, SPI 1.2.0) | `PluginSettings` (+ `SettingsView`) | `SitePluginConfigService`, `SecretCipher`, `@Value("${runway.plugin…}")` on a per-site key |
| your per-site files | `PluginSiteFiles`; declare personal data in `siteData.personal` | `SiteFileStore`, `StorageLayout`, a path you build | | your per-site files | `PluginSiteFiles`; declare personal data in `siteData.personal` | `SiteFileStore`, `StorageLayout`, a path you build |
| the site, the request's site, a permission check, a message | `Sites`, `RequestContext`, `AccessCheck` (`@authz`), `Messages` | `SiteResolver`, `AuthzExpressions`, `SiteAwareMessageSource` | | the site, the request's site, a permission check, a message | `Sites`, `RequestContext`, `AccessCheck` (`@authz`), `Messages` | `SiteResolver`, `AuthzExpressions`, `SiteAwareMessageSource` |
| a starter page | `SitePages.install` → `InstallResult` | `PageWriteService`, writing templates | | a starter page | `SitePages.install` → `InstallResult` | `PageWriteService`, writing templates |
@@ -226,6 +226,7 @@ Then depend on `mx.quest:runway-spi:<ver>` (`provided`) and `mx.quest:runway-spi
| a start/stop hook | `PluginLifecycle` | `RunwayPlugin`/`PluginContext` (removed at `1.0.0`) | | a start/stop hook | `PluginLifecycle` | `RunwayPlugin`/`PluginContext` (removed at `1.0.0`) |
| a console screen | `@ConsoleScreen` on a `@Controller` under `/__admin/<id>` or `/__app/<id>` | your own `@ControllerAdvice` calling `OperatorShellModel` | | a console screen | `@ConsoleScreen` on a `@Controller` under `/__admin/<id>` or `/__app/<id>` | your own `@ControllerAdvice` calling `OperatorShellModel` |
| an HTTP route on the site | `EndpointContributor` (`Route`, `Route.anonymousPost` for a public form) | a `@Controller` outside the console prefixes, a servlet `Filter` | | an HTTP route on the site | `EndpointContributor` (`Route`, `Route.anonymousPost` for a public form) | a `@Controller` outside the console prefixes, a servlet `Filter` |
| tables in PostgreSQL or MariaDB | the `database` plugin's own SPI (`Databases`, `DatabaseConsumer`, migrations shipped in your jar; `requires: [ "database >= 1.0.0" ]`): `plugins/docs/PLUGIN-AUTHORING-GUIDE.md` §7.14, example `plugins/runway-demo-database/` | a JDBC driver or pool of your own, a connection string in your settings |
| an absolute URL in head markup | `HeadContext.origin()` (1.0.0) | the `Host` header | | an absolute URL in head markup | `HeadContext.origin()` (1.0.0) | the `Host` header |
**How the kernel enforces it** — each is a **Blocked** plugin with the reason in its row on the **Plugins** screen, **How the kernel enforces it** — each is a **Blocked** plugin with the reason in its row on the **Plugins** screen,
@@ -332,7 +333,7 @@ if you use any `0.6.0` type, `">=0.5.0"` for a `0.5.0` service.
| Service | What it gives you | | Service | What it gives you |
|---|---| |---|---|
| `PluginSettings` | `site(siteId)` → a `SettingsView` of **your** per-site settings: the `siteSettings:` defaults overlaid by what the operator saved (`sites/<id>/plugins/<yourId>.yml`), unknown stored keys preserved, secret keys absent. `secret(siteId, key)` → a `type: secret` value in clear (an `ENC(...)` value decrypted; a hand-written plaintext returned as is; empty when unset, undeclared as secret, or undecryptable). `appSecret(key)` (SPI 1.1.0) → the same for a secret declared in your app-level `settings:`, as the running application holds it. | | `PluginSettings` | `site(siteId)` → a `SettingsView` of **your** per-site settings: the `siteSettings:` defaults overlaid by what the operator saved (`sites/<id>/plugins/<yourId>.yml`), unknown stored keys preserved, secret keys absent. `secret(siteId, key)` → a `type: secret` value in clear (an `ENC(...)` value decrypted; a hand-written plaintext returned as is; empty when unset, undeclared as secret, or undecryptable). `appSecret(key)` (SPI 1.1.0) → the same for a secret declared in your app-level `settings:`, as the running application holds it. `savedApp(key)` (SPI 1.2.0) → one of your app-level settings as **saved** now (a secret in clear; a blank non-secret as its declared default), read from your settings file, for checking a change before the restart applies it. |
| `SettingsView` | lenient typed reads: `string(key, fallback)` (blank → fallback), `bool`, `integer` (and a clamped form), `decimal`, `list` (a YAML list or a comma/newline string). A value that does not parse yields the fallback, never an exception. Nested values are frozen; parse structures from `values()` yourself. | | `SettingsView` | lenient typed reads: `string(key, fallback)` (blank → fallback), `bool`, `integer` (and a clamped form), `decimal`, `list` (a YAML list or a comma/newline string). A value that does not parse yields the fallback, never an exception. Nested values are frozen; parse structures from `values()` yourself. |
| `PluginInfo` | your `id`, `version` and install folder. Injectable; also handed to `PluginLifecycle.started`. | | `PluginInfo` | your `id`, `version` and install folder. Injectable; also handed to `PluginLifecycle.started`. |
| `PluginLifecycle` | optional `started(PluginInfo)` after the platform is up (in plugin load order) and `stopping()` at shutdown (reverse order, only if started). Collected by type — no `id()` to keep in sync. | | `PluginLifecycle` | optional `started(PluginInfo)` after the platform is up (in plugin load order) and `stopping()` at shutdown (reverse order, only if started). Collected by type — no `id()` to keep in sync. |
@@ -738,7 +739,9 @@ You declare a **`FilterBand` + a small offset** — never a raw order. The kerne
escape its band to preempt the protection floor or run before security. The bands (outermost → escape its band to preempt the protection floor or run before security. The bands (outermost →
innermost) are `EDGE_INGRESS` (raw request, pre-security), `EDGE_EGRESS` (response rewriting), innermost) are `EDGE_INGRESS` (raw request, pre-security), `EDGE_EGRESS` (response rewriting),
`TENANT` (after the site is resolved, before security), `APPLICATION` (feature filters, inner of `TENANT` (after the site is resolved, before security), `APPLICATION` (feature filters, inner of
security; the default). **`SECURITY` is not contributable** — it belongs to the kernel's realm security; the default). The kernel's access log sits between `EDGE_INGRESS` and the rest: whatever an
`EDGE_EGRESS`, `TENANT` or `APPLICATION` filter answers is logged with its status, while a request an
`EDGE_INGRESS` filter turns away is not (log it yourself, throttled, if you need to). **`SECURITY` is not contributable** — it belongs to the kernel's realm
security chains, and (as above) a non-essential plugin may not declare a `SecurityFilterChain` bean either. security chains, and (as above) a non-essential plugin may not declare a `SecurityFilterChain` bean either.
**Verify:** the boot log prints one line per plugin filter — **Verify:** the boot log prints one line per plugin filter —
@@ -926,7 +929,8 @@ holds one. Read a per-site secret with `PluginSettings.secret(siteId, key)` —
appears in `site(siteId)`. Read an **app-level** secret (declared `type: secret` under `settings:`) with appears in `site(siteId)`. Read an **app-level** secret (declared `type: secret` under `settings:`) with
`PluginSettings.appSecret(key)` (SPI 1.1.0, so declare `requiresSpi: ">=1.1.0"`): your `@ConfigurationProperties` `PluginSettings.appSecret(key)` (SPI 1.1.0, so declare `requiresSpi: ">=1.1.0"`): your `@ConfigurationProperties`
bind it only in its `ENC(...)` form, which you cannot decrypt. It answers the value the running application started bind it only in its `ENC(...)` form, which you cannot decrypt. It answers the value the running application started
with, so a saved change applies after the restart, like every app-level setting. Encryption requires `runway.security.secret-key` to be set — until it is, a secret can't be with, so a saved change applies after the restart, like every app-level setting. To check a saved change before
that restart (a connection test, say), read it with `PluginSettings.savedApp(key)` (SPI 1.2.0). Encryption requires `runway.security.secret-key` to be set — until it is, a secret can't be
saved and the form says so. A **blank secret on resubmit keeps** the stored value (you never retype saved and the form says so. A **blank secret on resubmit keeps** the stored value (you never retype
it), and secrets are never echoed back into the form. it), and secrets are never echoed back into the form.
@@ -999,6 +1003,11 @@ Because the plugin classloader is **shared** and **parent-first** (§10), the ow
to the same `Class` for owner and implementers, so a `List<TheSpi>` injection collects to the same `Class` for owner and implementers, so a `List<TheSpi>` injection collects
implementations across plugins by type. implementations across plugins by type.
The shipped example is the **`database`** plugin: it publishes `mx.quest.database.spi`, which the provider plugins
implement (`DatabaseProvider`) and which plugins that keep data in PostgreSQL or MariaDB use (`Databases`,
`DatabaseConsumer`). How to use it — scopes, transactions, migrations, backups — is in
`plugins/docs/PLUGIN-AUTHORING-GUIDE.md` §7.14; how operators set it up is ADMINISTRATION §11.1.
--- ---
## 8. Static assets, templates & i18n ## 8. Static assets, templates & i18n
+1 -1
View File
@@ -47,7 +47,7 @@ How large a request may be. Applies after a restart.
| Setting | Key | What it does | Values | | Setting | Key | What it does | Values |
|---|---|---|---| |---|---|---|---|
| Largest request before sign-in (bytes) | `runway.endpoints.max-form-bytes` | The most a visitor who is not signed in may send in one request, on any path. Default 262144 (256 KiB). | whole number from 1024 to 104857600; default `262144` | | Largest request before sign-in (bytes) | `runway.endpoints.max-form-bytes` | The most a visitor who is not signed in may send in one request, on any path. Default 262144 (256 KiB). | whole number from 1024 to 104857600; default `262144` |
| Slowest request body (bytes per second) *(Advanced)* | `runway.http.min-request-data-rate` | A request body arriving more slowly is answered 408 Request Timeout, so a client sending a byte now and then cannot hold a request thread. Measured on what has arrived since the body's first byte. Default 4096; 0 turns the check off. | whole number from 0 to 1048576; default `4096` | | Slowest request body (bytes per second) *(Advanced)* | `runway.http.min-request-data-rate` | A request body arriving more slowly is answered 408 Request Timeout: login and other forms, uploads and raw bodies alike, so a client sending a byte now and then cannot keep a request thread. Only time spent waiting for the client counts, and a body that has arrived complete is never refused. Sending part of a body fast earns at most 30 seconds of waiting. Default 4096; 0 turns the check off. | whole number from 0 to 1048576; default `4096` |
| Largest request to a plugin (bytes) | `runway.endpoints.max-body-bytes` | The most a signed-in user may send to a plugin's route. Default 10485760 (10 MiB). | whole number from 1024 to 1073741824; default `10485760` | | Largest request to a plugin (bytes) | `runway.endpoints.max-body-bytes` | The most a signed-in user may send to a plugin's route. Default 10485760 (10 MiB). | whole number from 1024 to 1073741824; default `10485760` |
| Largest uploaded file | `spring.servlet.multipart.max-file-size` | For uploads such as a backup to restore. A size like 256MB or 1GB. Default 256MB. | text; default `256MB` | | Largest uploaded file | `spring.servlet.multipart.max-file-size` | For uploads such as a backup to restore. A size like 256MB or 1GB. Default 256MB. | text; default `256MB` |
| Largest upload request | `spring.servlet.multipart.max-request-size` | All the files of one upload together. A size like 256MB. Default 256MB. | text; default `256MB` | | Largest upload request | `spring.servlet.multipart.max-request-size` | All the files of one upload together. A size like 256MB. Default 256MB. | text; default `256MB` |
+39 -9
View File
@@ -230,11 +230,17 @@ name or the default language. While no field is set and no manifest icon (192, 5
`/manifest.webmanifest` answers 404 and pages do not link to it. `/manifest.webmanifest` answers 404 and pages do not link to it.
The **Logs** screen (`/__admin/logs`) shows your site's own **access log** (public traffic — the most recent The **Logs** screen (`/__admin/logs`) shows your site's own **access log** (public traffic — the most recent
lines) and its **audit journal**: who did what on your site, and when. The journal records sign-ins lines; every sign-in attempt on your site's login page is there too, as a `POST /login`, and so is a request your
site refused, such as a `503` while it is in maintenance) and its **audit journal**: who did what on your site, and when. The journal records sign-ins
(`login.success`, `login.failure`) and sign-outs (`logout`), each with the address it came from (`ip=…`, in full: (`login.success`, `login.failure`) and sign-outs (`logout`), each with the address it came from (`ip=…`, in full:
the anonymizing setting below applies to the access log only); password recovery through an emailed link the anonymizing setting below applies to the access log only); password recovery through an emailed link
(`recovery.requested`, `recovery.completed`); page changes (`page.saved`, `page.deleted`, `page.published`, (`recovery.requested`, `recovery.completed`); page changes (`page.saved`, `page.deleted`, `page.published`,
`page.unpublished`); user changes (`user.created`, `user.password-reset`, `user.deleted`); role and permission `page.unpublished`); user changes (`user.created`, `user.updated`, `user.suspended`, `user.resumed`,
`user.password-reset`, `user.deleted`); static files (`static.uploaded`, `static.folder-created`, `static.deleted`);
backups made on your console (§12): a backup saved on the server (`backup.saved`) or deleted (`backup.deleted`), a
backup downloaded (`backup.downloaded`: `full` for a fresh full backup, `transfer` for a transfer copy, `full` and the
name for a saved one) and a restore (`site.restored`, naming the backup, or `(upload)` for an uploaded file) — the
platform operator's own backup work is in the platform's log, not here; role and permission
changes on **Permissions** (`permissions.role-assigned`, `permissions.permission-granted`, changes on **Permissions** (`permissions.role-assigned`, `permissions.permission-granted`,
`permissions.role-created` and their counterparts); and settings changes — a plugin's settings `permissions.role-created` and their counterparts); and settings changes — a plugin's settings
(`plugin.settings-changed`, naming the plugin), the site settings (`site-config.changed`, naming which parts — (`plugin.settings-changed`, naming the plugin), the site settings (`site-config.changed`, naming which parts —
@@ -256,7 +262,8 @@ happens when a line is written, so switching it changes only the lines written a
how many **days** of logs to keep, 30 by default, up to the how many **days** of logs to keep, 30 by default, up to the
platform's maximum (90 unless your operator changed it; the field's hint says it). A value above it is refused. If platform's maximum (90 unless your operator changed it; the field's hint says it). A value above it is refused. If
the operator lowers the maximum below what you chose, your choice is kept, the logs are kept only up to the new the operator lowers the maximum below what you chose, your choice is kept, the logs are kept only up to the new
maximum, and the panel says so until you save a value within it. Logs are *transient*: they never travel in a backup, so restoring a site never carries old logs. maximum, and the panel says so until you save a value within it. Logs are *transient*: they never travel in a backup, and a restore keeps the logs your site has now, so the
journal still shows everything before the restore (and, for a restore made on your console, the restore itself).
The **Bandwidth** screen (`/__admin/bandwidth`, site-admin only) charts your site's data transfer — a The **Bandwidth** screen (`/__admin/bandwidth`, site-admin only) charts your site's data transfer — a
30-day daily graph plus 24-hour / 7-day / 30-day totals. Like logs, the underlying stats are transient and 30-day daily graph plus 24-hour / 7-day / 30-day totals. Like logs, the underlying stats are transient and
@@ -835,6 +842,20 @@ index-backed plugin rebuilds its index).
page or master template (described in **§7**); you decide where it appears and — on the **Content page or master template (described in **§7**); you decide where it appears and — on the **Content
widgets** screen below — how each placement behaves. widgets** screen below — how each placement behaves.
**Plugins that keep data in a database.** Most plugins keep your site's data in your site's folder. Some keep it in
a database server the platform operator runs (PostgreSQL or MariaDB) instead: things that pile up, such as visitors'
entries. For you it works the same way: each site has its own part of the database, kept apart from every other site's,
and your **full backups** carry it (**§12**). Your dashboard has a **Database** card saying whether your site keeps
any data there, and how the last restore of that data went. If the database cannot be reached, those plugins say
so on the page (for example *This example needs the database*) and the rest of your site works as usual; the
operator sees why on their own console.
One such plugin is an example, the **guestbook** (`runway-demo-database`), if your operator installed it:
place `<div id="guestbook" data-widget="guestbook/main"></div>` on a page; visitors sign it there, and you read and
delete the entries under **Guestbook** in your console (it needs the *manage* permission of that plugin, which a role
gets on **Permissions**). Its settings, under **Settings → Runway demo — database**, turn it off for your site and cap how many
entries are kept (500 by default; the oldest go first).
### Content widgets — configuring each placement ### Content widgets — configuring each placement
Open **Resources → Content widgets** (`/__admin/widgets`). The screen lists **every widget a Open **Resources → Content widgets** (`/__admin/widgets`). The screen lists **every widget a
@@ -1184,10 +1205,10 @@ two lists, for the **last 7 or 30 days** (never longer than your log retention
with a corrected link, the missing page or file, or a redirect from the old address. with a corrected link, the missing page or file, or a redirect from the old address.
- **Most-visited pages** — your pages by how often they were successfully viewed, with when last. - **Most-visited pages** — your pages by how often they were successfully viewed, with when last.
**What it counts.** Only `GET` requests (a form post or a crawler's `HEAD` is not a visit). A **page view** is a **What it counts.** Only `GET` requests (a form post, a sign-in attempt or a crawler's `HEAD` is not a visit). A **page view** is a
successful (2xx) answer for an address that looks like a page — no file extension in the last part, or `.html` successful (2xx) answer for an address that looks like a page — no file extension in the last part, or `.html`
— so stylesheets, images, downloads, `robots.txt` and the sitemap are left out; a browser re-checking a page it — so stylesheets, images, downloads, `robots.txt` and the sitemap are left out; a browser re-checking a page it
already has (a `304`) is not a new view. A **404** counts for any address, images included, because a missing already has (a `304`) is not a new view, and neither is a refusal (a `403`, or a `503` during maintenance). A **404** counts for any address, images included, because a missing
image is a broken link too. Addresses are shown **without their query string** (`/search?q=…` counts as image is a broken link too. Addresses are shown **without their query string** (`/search?q=…` counts as
`/search`), and very long ones are shortened on screen (hover to see the whole stored address). `/search`), and very long ones are shortened on screen (hover to see the whole stored address).
@@ -1315,18 +1336,27 @@ backup they save stays on the server, where an administrator — or the platform
download or restore it. Why: handing out the permission to keep the site safe should not also hand out download or restore it. Why: handing out the permission to keep the site safe should not also hand out
a copy of everyone's credentials. a copy of everyone's credentials.
**Data in a database.** When plugins keep data for your site in a database (**§8**), a full backup carries it, and
a backup taken while the database cannot be reached **fails** rather than leaving that data out: a backup is
complete or it is not a backup. On restore, that data is loaded beside the live data and switched in only when all
of it loaded; if loading fails, your site's files are still restored, the database data **stays as it was**, and the
dashboard's **Database** card shows the failed restore (tell the operator; the detail is on their console).
**Restoring.** Restore **replaces your entire site** with the contents of a backup — every **Restoring.** Restore **replaces your entire site** with the contents of a backup — every
page, template, user and setting reverts to the moment the backup was taken. Because it is page, template, user and setting reverts to the moment the backup was taken. Because it is
destructive, **only the site's administrators (the site superadmin, or the Administrator tier) may destructive, **only the site's administrators (the site superadmin, or the Administrator tier) may
restore**; the restore controls are hidden for everyone else. You can restore either from a **saved backup** (pick it from the list) or by restore**; the restore controls are hidden for everyone else. You can restore either from a **saved backup** (pick it from the list) or by
**uploading a `.zip`** you downloaded earlier. One thing does not revert: the site's **host names and base URL** **uploading a `.zip`** you downloaded earlier. Two things do not revert: the site's **host names and base URL**
(how visitors reach it) stay as the platform operator has set them now, whatever the backup says. (how visitors reach it) stay as the platform operator has set them now, whatever the backup says; and its **logs and
bandwidth history** stay as they are, so the audit journal keeps its record (the backup acts made here are in it,
§3).
Restore is safe by design: the platform first checks the file is a genuine, complete site Restore is safe by design: the platform first checks the file is a genuine, complete site
backup and only then swaps it in, in one step. **A corrupt, empty, or wrong file is rejected backup and only then swaps it in, in one step. **A corrupt, empty, or wrong file is rejected
and your live site is left exactly as it was** — a failed or interrupted restore never leaves and your live site is left exactly as it was** — a failed or interrupted restore never leaves
you with a half-restored or missing site. After a successful restore the site reflects the you with a half-restored or missing site. After a successful restore the site reflects the
backup immediately (no restart). backup immediately (no restart), and the Backups screen shows the site's host names and base URL for you to check: a restore made here keeps them as
they were (how the site is reached is set by the platform operator), so if they look wrong, ask the operator.
A backup made on a **newer** version of the platform than the one your site runs on is refused A backup made on a **newer** version of the platform than the one your site runs on is refused
the same way, with the message *"This backup was made by a newer version of Runway … Ask the the same way, with the message *"This backup was made by a newer version of Runway … Ask the
@@ -1359,7 +1389,7 @@ kind of `.zip`, restorable in the same way, with the parts that are yours alone
| Plugin settings that are **not** secrets | Plugin secrets (blanked, so you can see what to fill in) | | Plugin settings that are **not** secrets | Plugin secrets (blanked, so you can see what to fill in) |
| | Hostnames and base URL (replaced with a placeholder) | | | Hostnames and base URL (replaced with a placeholder) |
| | Traffic figures | | | Traffic figures |
| | Plugin-held data such as form submissions | | | Plugin-held data such as form submissions, and everything plugins keep for your site in a database (§8) |
| | Changes waiting for review — unpublished drafts, who submitted them, reviewers' notes | | | Changes waiting for review — unpublished drafts, who submitted them, reviewers' notes |
The recipient restores it exactly like a backup. Their copy comes up with your content and appearance, no The recipient restores it exactly like a backup. Their copy comes up with your content and appearance, no
+11 -1
View File
@@ -50,7 +50,7 @@ contribution, a host-coupled seam that is not part of the 1.0 contract (see "Wha
| Type | Since | Scope | What it gives a plugin | | Type | Since | Scope | What it gives a plugin |
|---|---|---|---| |---|---|---|---|
| `service.PluginSettings` (+ `model.SettingsView`) | 0.4.0 | plugin-scoped | its per-site settings, defaults applied, and its declared secrets decrypted (app-level settings bind through `@ConfigurationProperties("runway.plugin.<id>")`; an app-level `secret` setting in clear through `appSecret(key)`, since 1.1.0) | | `service.PluginSettings` (+ `model.SettingsView`) | 0.4.0 | plugin-scoped | its per-site settings, defaults applied, and its declared secrets decrypted (app-level settings bind through `@ConfigurationProperties("runway.plugin.<id>")`; an app-level `secret` setting in clear through `appSecret(key)`, since 1.1.0; an app-level setting as saved but not yet applied through `savedApp(key)`, since 1.2.0) |
| `model.PluginInfo` | 0.4.0 | plugin-scoped | its own id, version and install facts | | `model.PluginInfo` | 0.4.0 | plugin-scoped | its own id, version and install facts |
| `service.PluginLifecycle` | 0.4.0 | callback | `started(PluginInfo)` / `stopping()`, in load order and reverse | | `service.PluginLifecycle` | 0.4.0 | callback | `started(PluginInfo)` / `stopping()`, in load order and reverse |
| `service.PluginSiteFiles` (+ `model.FileEntry`) | 0.5.0 | plugin-scoped | its own per-site subtree `sites/<id>/plugins/<pluginId>/`: atomic text writes, capped reads, listing, deletes; confined against crafted paths **and** symbolic links | | `service.PluginSiteFiles` (+ `model.FileEntry`) | 0.5.0 | plugin-scoped | its own per-site subtree `sites/<id>/plugins/<pluginId>/`: atomic text writes, capped reads, listing, deletes; confined against crafted paths **and** symbolic links |
@@ -101,6 +101,16 @@ additive rules below apply to them unchanged.
It is a `default` method answering empty, so an implementation written against `1.0.0` still compiles. A plugin It is a `default` method answering empty, so an implementation written against `1.0.0` still compiles. A plugin
that calls it declares `requiresSpi: ">=1.1.0"`. that calls it declares `requiresSpi: ">=1.1.0"`.
### What `1.2.0` added
- **`PluginSettings.savedApp(key)`**: the calling plugin's own **app-level** setting as it is **saved now**, which
may differ from the running value until the restart that applies it. It answers the saved value when not blank (a
`secret` in clear, as `appSecret` decrypts it), otherwise the declared default of a non-secret setting, otherwise
empty; only keys the plugin declared in its own `settings:` are read, from its own settings file, on each call. It
lets a plugin check settings before that restart: the database plugin's connection test uses it. It is a `default`
method answering empty, so an implementation written against `1.1.0` still compiles. A plugin that calls it
declares `requiresSpi: ">=1.2.0"`.
## The compatibility rules (in force from `1.0.0`) ## The compatibility rules (in force from `1.0.0`)
The SPI is **binary API**. A plugin compiled against a released `runway-spi` keeps loading on any later version of The SPI is **binary API**. A plugin compiled against a released `runway-spi` keeps loading on any later version of
+16
View File
@@ -2,6 +2,22 @@
All notable changes are recorded here. Versions follow [Semantic Versioning](https://semver.org/). All notable changes are recorded here. Versions follow [Semantic Versioning](https://semver.org/).
## [2.0.0] — 2026-10-30
### Upgrade note
- Install it together with `database` 2.0.0, on Runway 1.2.0 or later, and move the MariaDB server's
settings into this plugin as the `database` 2.0.0 *Upgrade note* says. On Runway 1.1.x, keep 1.0.0 of both.
### Changed
- **This plugin holds the MariaDB server's settings**: host, port, database, username, password, TLS and CA
certificate and the collation, on its own settings page (**Plugins → Database — MariaDB → Settings**; file
`external/plugin-settings/database-mariadb.yml`, under `runway.plugin.database-mariadb`). Until 2.0.0 they were the `database` plugin's;
move them as its 2.0.0 *Upgrade note* says.
- Requires `database >= 2.0.0` and Runway SPI 1.2.0 (Runway 1.2.0), whose `PluginSettings.savedApp` hands the saved
settings to the database plugin's connection test.
## [1.0.0] — 2026-10-29 ## [1.0.0] — 2026-10-29
First public release of `database-mariadb`: the MariaDB 10.11+ provider for the `database` plugin, with MariaDB First public release of `database-mariadb`: the MariaDB 10.11+ provider for the `database` plugin, with MariaDB
+8 -4
View File
@@ -2,13 +2,17 @@
Lets the [`database`](../database) plugin use **MariaDB 10.11 or later** (MySQL is not supported). It bundles MariaDB Lets the [`database`](../database) plugin use **MariaDB 10.11 or later** (MySQL is not supported). It bundles MariaDB
Connector/J and builds a configured, unpooled `DataSource`; every statement Runway runs is written in the database Connector/J and builds a configured, unpooled `DataSource`; every statement Runway runs is written in the database
plugin. Choose it with the database plugin's `provider: mariadb` setting. plugin. Since 2.0.0 it also holds the server's settings, collation included: host, port, database, account, password and TLS,
on its own settings page (**Plugins → Database — MariaDB → Settings**, file `external/plugin-settings/database-mariadb.yml`).
With both providers installed, choose this one with the database plugin's `provider: mariadb` setting; with one
installed, it is used.
- **Plugin id:** `database-mariadb` (v`1.0.0`) — install folder `external/plugins/database-mariadb/` - **Plugin id:** `database-mariadb` (v`2.0.0`) — install folder `external/plugins/database-mariadb/`
- **Requires:** `database >= 1.0.0`, Runway SPI `1.1.0` or later - **Requires:** `database >= 2.0.0`, Runway SPI `1.2.0` or later (Runway 1.2.0)
- **Bundles:** MariaDB Connector/J `3.5.8` (LGPL-2.1), unmodified, in `lib/`. Its sources are published next to this - **Bundles:** MariaDB Connector/J `3.5.8` (LGPL-2.1), unmodified, in `lib/`. Its sources are published next to this
plugin's zip in each release (`mariadb-java-client-3.5.8-sources.jar`); the license and how to replace the jar are plugin's zip in each release (`mariadb-java-client-3.5.8-sources.jar`); the license and how to replace the jar are
in `THIRD-PARTY-NOTICES`. in `THIRD-PARTY-NOTICES`.
Setup, grants and settings: the kernel's ADMINISTRATION §11.1. Details: [`docs/DATABASE-MARIADB-PLUGIN.md`](docs/DATABASE-MARIADB-PLUGIN.md), Setup, grants and settings: the kernel's ADMINISTRATION §11.1 — step by step, the settings file for a setup
without the console, upgrading from 1.x, and a table for when it does not connect. Details: [`docs/DATABASE-MARIADB-PLUGIN.md`](docs/DATABASE-MARIADB-PLUGIN.md),
[`CHANGELOG.md`](CHANGELOG.md). [`CHANGELOG.md`](CHANGELOG.md).
@@ -32,3 +32,15 @@ The provider is one bean, `databaseMariadbProvider`, collected by type. Tests: `
each TLS policy and that it never carries the account, a real connection when `-Ddb.it.mariadb=host:port` and each TLS policy and that it never carries the account, a real connection when `-Ddb.it.mariadb=host:port` and
`-Ddb.it.password-file=…` are set, the bean name, and the linkage scan). End to end: `-Ddb.it.password-file=…` are set, the bean name, and the linkage scan). End to end:
`../database/scripts/verify-against-host.sh` with `PROVIDER=mariadb`. `../database/scripts/verify-against-host.sh` with `PROVIDER=mariadb`.
## Its settings (since 2.0.0)
The server's settings are this plugin's own app-level settings (`runway.plugin.database-mariadb.*`, the console's **Plugins →
Database — MariaDB → Settings**): `host`, `port`, `database`, `username`, `password` (a `secret`, bound to the
others), `tls`, `caCertificate`, and `collation`. The provider hands them to the database plugin raw; the database
plugin checks every one before use, as before:
- **running** (`runningSettings()`): bound at startup into a `ProviderSettingsProps` bean
(`databaseMariadbSettings`), the password read in clear with `PluginSettings.appSecret("password")`;
- **saved** (`savedSettings()`): read with `PluginSettings.savedApp(key)` (SPI 1.2.0) from the settings file as it is
now, for the database plugin's connection test before a restart applies them.
@@ -0,0 +1,17 @@
# Runway Database — MariaDB provider — English
database-mariadb.group.connection=Server
database-mariadb.group.connection.help=The MariaDB server Runway keeps plugins' data on. Changes apply after a restart; test them first with the connection tests on the Database plugin's settings page. In a cluster every node needs the same values.
database-mariadb.set.host=Host
database-mariadb.set.host.help=A host name or an IP address. One server only.
database-mariadb.set.port=Port
database-mariadb.set.port.help=Leave blank for MariaDB's default, 3306.
database-mariadb.set.database=Database
database-mariadb.set.database.help=An existing database on the server. Runway creates its own databases next to it: one per site and one for the whole installation.
database-mariadb.set.username=Username
database-mariadb.set.password=Password
database-mariadb.set.tls=TLS
database-mariadb.set.tls.help=verify-full checks the server's certificate and name. require encrypts without checking who the server is. Use disable only for a database on the same host or a private network you trust.
database-mariadb.set.caCertificate=CA certificate (PEM)
database-mariadb.set.caCertificate.help=The certificate authority that signed the server's certificate, when the Java trust store does not know it.
database-mariadb.set.collation=Collation
database-mariadb.set.collation.help=For plugins' tables. Blank uses utf8mb4_uca1400_ai_ci (utf8mb4_unicode_ci before MariaDB 10.10).
@@ -0,0 +1,17 @@
# Runway Database — MariaDB provider — español
database-mariadb.group.connection=Servidor
database-mariadb.group.connection.help=El servidor MariaDB donde Runway guarda los datos de los plugins. Los cambios se aplican al reiniciar; pruébelos antes con las pruebas de conexión de la página de ajustes del plugin Base de datos. En un clúster, todos los nodos necesitan los mismos valores.
database-mariadb.set.host=Servidor
database-mariadb.set.host.help=Un nombre de host o una dirección IP. Un solo servidor.
database-mariadb.set.port=Puerto
database-mariadb.set.port.help=Déjelo en blanco para usar el predeterminado de MariaDB, 3306.
database-mariadb.set.database=Base de datos
database-mariadb.set.database.help=Una base de datos existente en el servidor. Runway crea sus propias bases de datos junto a ella: una por sitio y una para toda la instalación.
database-mariadb.set.username=Usuario
database-mariadb.set.password=Contraseña
database-mariadb.set.tls=TLS
database-mariadb.set.tls.help=verify-full comprueba el certificado y el nombre del servidor. require cifra sin comprobar quién es el servidor. Use disable solo para una base de datos en el mismo equipo o en una red privada de confianza.
database-mariadb.set.caCertificate=Certificado de la CA (PEM)
database-mariadb.set.caCertificate.help=La autoridad que firmó el certificado del servidor, cuando el almacén de confianza de Java no la conoce.
database-mariadb.set.collation=Intercalación
database-mariadb.set.collation.help=Para las tablas de los plugins. En blanco se usa utf8mb4_uca1400_ai_ci (utf8mb4_unicode_ci antes de MariaDB 10.10).
+34 -4
View File
@@ -5,16 +5,46 @@
# published next to this plugin's release) and builds a configured # published next to this plugin's release) and builds a configured
# DataSource; every statement Runway runs is written in the database plugin. # DataSource; every statement Runway runs is written in the database plugin.
# #
# Choose it with the database plugin's `provider: mariadb` setting. # The server, the account and TLS are set on THIS plugin's settings page
# (since 2.0.0); the database plugin keeps the provider choice and the
# limits. With both providers installed, choose this one with the database
# plugin's `provider: mariadb` setting.
#
# The install folder name MUST equal this `id`: external/plugins/database-mariadb/. # The install folder name MUST equal this `id`: external/plugins/database-mariadb/.
# ============================================================================= # =============================================================================
id: database-mariadb id: database-mariadb
name: Database — MariaDB name: Database — MariaDB
version: 1.0.0 version: 2.0.0
mainClass: mx.quest.database.mariadb.MariaDbProviderConfig mainClass: mx.quest.database.mariadb.MariaDbProviderConfig
# The database plugin publishes the DatabaseProvider interface this plugin implements. # The database plugin publishes the DatabaseProvider interface this plugin implements.
requires: [ "database >= 1.0.0" ] requires: [ "database >= 2.0.0" ]
requiresSpi: ">=1.1.0" # SPI 1.2.0: PluginSettings.savedApp, which hands the saved settings to the connection test.
requiresSpi: ">=1.2.0"
settingGroups:
- { id: connection, label: database-mariadb.group.connection, help: database-mariadb.group.connection.help }
# Runway-wide settings, applied on RESTART. In a cluster every node needs the same values and the same platform
# secret key. Test them before restarting: Plugins -> Database -> Settings, "Connection tests".
settings:
- { key: host, type: string, group: connection, label: database-mariadb.set.host, help: database-mariadb.set.host.help }
- { key: port, type: int, range: "1..65535", group: connection, label: database-mariadb.set.port,
help: database-mariadb.set.port.help }
- { key: database, type: string, group: connection, label: database-mariadb.set.database,
help: database-mariadb.set.database.help }
- { key: username, type: string, group: connection, label: database-mariadb.set.username }
# Bound to where it goes: changing any of these without typing the password again removes the stored one.
- key: password
type: secret
group: connection
label: database-mariadb.set.password
secretBoundTo: [host, port, database, username, tls, caCertificate]
- { key: tls, type: enum, range: "verify-full,require,disable", default: verify-full, group: connection,
label: database-mariadb.set.tls, help: database-mariadb.set.tls.help }
- { key: caCertificate, type: text, group: connection, advanced: true, label: database-mariadb.set.caCertificate,
help: database-mariadb.set.caCertificate.help }
- { key: collation, type: string, group: connection, advanced: true, label: database-mariadb.set.collation,
help: database-mariadb.set.collation.help }
+7 -4
View File
@@ -17,7 +17,7 @@
<groupId>mx.quest</groupId> <groupId>mx.quest</groupId>
<artifactId>runway-plugin-database-mariadb</artifactId> <artifactId>runway-plugin-database-mariadb</artifactId>
<version>1.0.0</version> <version>2.0.0</version>
<packaging>jar</packaging> <packaging>jar</packaging>
<name>Runway Database — MariaDB</name> <name>Runway Database — MariaDB</name>
<licenses> <licenses>
@@ -38,11 +38,11 @@
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<!-- Reproducible builds: pins every archive entry's timestamp. Bump at each release. --> <!-- Reproducible builds: pins every archive entry's timestamp. Bump at each release. -->
<project.build.outputTimestamp>2026-10-29T00:00:00Z</project.build.outputTimestamp> <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. --> <!-- The runway-spi this plugin compiles against: SPI 1.2.0 adds PluginSettings.savedApp. -->
<runway.version>1.1.0</runway.version> <runway.version>1.2.0</runway.version>
<!-- The database plugin whose SPI this provider implements (provided: the shared plugin class loader <!-- The database plugin whose SPI this provider implements (provided: the shared plugin class loader
supplies it; install ../database first). --> supplies it; install ../database first). -->
<database.version>1.0.0</database.version> <database.version>2.0.0</database.version>
<!-- The driver bundled in lib/. Pinned so the bundle never drifts from what the notices name. --> <!-- The driver bundled in lib/. Pinned so the bundle never drifts from what the notices name. -->
<mariadb.version>3.5.8</mariadb.version> <mariadb.version>3.5.8</mariadb.version>
</properties> </properties>
@@ -160,6 +160,9 @@
<copy todir="${stage}/lib"> <copy todir="${stage}/lib">
<fileset dir="${project.build.directory}/staged-lib"/> <fileset dir="${project.build.directory}/staged-lib"/>
</copy> </copy>
<copy todir="${stage}/i18n">
<fileset dir="${project.basedir}/i18n"/>
</copy>
<!-- Never a plugin zip without its libraries (it would load and fail at its first use). --> <!-- Never a plugin zip without its libraries (it would load and fail at its first use). -->
<fail message="no library in ${stage}/lib"> <fail message="no library in ${stage}/lib">
<condition><resourcecount when="equal" count="0"> <condition><resourcecount when="equal" count="0">
@@ -4,9 +4,12 @@ import java.sql.SQLException;
import java.util.LinkedHashMap; import java.util.LinkedHashMap;
import java.util.Map; import java.util.Map;
import java.util.Objects; import java.util.Objects;
import java.util.Optional;
import java.util.function.Supplier;
import javax.sql.DataSource; import javax.sql.DataSource;
import mx.quest.database.spi.ConnectionSettings; import mx.quest.database.spi.ConnectionSettings;
import mx.quest.database.spi.DatabaseProvider; import mx.quest.database.spi.DatabaseProvider;
import mx.quest.database.spi.ProviderSettings;
import org.mariadb.jdbc.MariaDbDataSource; import org.mariadb.jdbc.MariaDbDataSource;
/** /**
@@ -27,6 +30,25 @@ public final class MariaDbProvider implements DatabaseProvider {
static final int DEFAULT_PORT = 3306; static final int DEFAULT_PORT = 3306;
private final Supplier<ProviderSettings> running;
private final Supplier<ProviderSettings> saved;
/**
* Without settings, as before database 2.0.0: for building data sources only (tests).
*/
public MariaDbProvider() {
this(() -> null, () -> null);
}
/**
* @param running the server settings the application started with, from this plugin's own settings page
* @param saved the server settings saved on that page now, which the next restart applies
*/
public MariaDbProvider(Supplier<ProviderSettings> running, Supplier<ProviderSettings> saved) {
this.running = Objects.requireNonNull(running, "running");
this.saved = Objects.requireNonNull(saved, "saved");
}
@Override @Override
public String id() { public String id() {
return "mariadb"; return "mariadb";
@@ -95,4 +117,14 @@ public final class MariaDbProvider implements DatabaseProvider {
} }
return value; return value;
} }
@Override
public Optional<ProviderSettings> runningSettings() {
return Optional.ofNullable(running.get());
}
@Override
public Optional<ProviderSettings> savedSettings() {
return Optional.ofNullable(saved.get());
}
} }
@@ -1,14 +1,33 @@
package mx.quest.database.mariadb; package mx.quest.database.mariadb;
import mx.quest.database.spi.ProviderSettings;
import mx.quest.database.spi.ProviderSettingsProps;
import mx.quest.runway.spi.service.PluginSettings;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
/** Registers the MariaDB provider; the database plugin collects it by type. */ /**
* Registers the MariaDB provider; the database plugin collects it by type. The server's settings are this plugin's
* own app-level settings ({@code runway.plugin.database-mariadb.*}, since database 2.0.0): the running ones as
* bound at startup, the password through {@link PluginSettings#appSecret}, and the saved ones through
* {@link PluginSettings#savedApp} for the connection test. With both providers installed the context holds two
* {@link ProviderSettingsProps} beans, hence the qualifier.
*/
@Configuration(proxyBeanMethods = false) @Configuration(proxyBeanMethods = false)
public class MariaDbProviderConfig { public class MariaDbProviderConfig {
@Bean @Bean
public MariaDbProvider databaseMariadbProvider() { @ConfigurationProperties("runway.plugin.database-mariadb")
return new MariaDbProvider(); public ProviderSettingsProps databaseMariadbSettings() {
return new ProviderSettingsProps();
}
@Bean
public MariaDbProvider databaseMariadbProvider(
@Qualifier("databaseMariadbSettings") ProviderSettingsProps server, PluginSettings settings) {
return new MariaDbProvider(() -> server.toSettings(settings.appSecret(ProviderSettings.PASSWORD)),
() -> ProviderSettings.read(settings::savedApp));
} }
} }
@@ -20,14 +20,21 @@ import java.time.temporal.ChronoUnit;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Calendar; import java.util.Calendar;
import java.util.List; import java.util.List;
import java.util.Map;
import java.util.TimeZone; import java.util.TimeZone;
import java.util.regex.Matcher; import java.util.regex.Matcher;
import java.util.regex.Pattern; import java.util.regex.Pattern;
import java.util.stream.Stream; import java.util.stream.Stream;
import mx.quest.database.spi.ConnectionSettings;
import mx.quest.database.spi.ConnectionSettings.Tls; import mx.quest.database.spi.ConnectionSettings.Tls;
import mx.quest.database.spi.ConnectionSettings;
import mx.quest.database.spi.ProviderSettings;
import mx.quest.runway.spi.service.PluginSettings;
import mx.quest.runway.spi.testkit.FakePluginSettings;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.MapPropertySource;
class MariaDbProviderTest { class MariaDbProviderTest {
@@ -114,15 +121,66 @@ class MariaDbProviderTest {
assertThat(new MariaDbProvider().driverVersion()).startsWith("MariaDB Connector/J"); assertThat(new MariaDbProvider().driverVersion()).startsWith("MariaDB Connector/J");
} }
/** Turns on @ConfigurationProperties binding, as the kernel's context does. */
@Configuration(proxyBeanMethods = false)
@EnableConfigurationProperties
static class Binding {
}
@Test @Test
void theConfigurationRegistersOneProviderNamedForThePlugin() { void theConfigurationRegistersOneProviderNamedForThePlugin() {
try (AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext( try (AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext()) {
MariaDbProviderConfig.class)) { ctx.registerBean(PluginSettings.class, FakePluginSettings::new);
ctx.register(Binding.class, MariaDbProviderConfig.class);
ctx.refresh();
assertThat(ctx.getBeanNamesForType(mx.quest.database.spi.DatabaseProvider.class)) assertThat(ctx.getBeanNamesForType(mx.quest.database.spi.DatabaseProvider.class))
.containsExactly("databaseMariadbProvider"); .containsExactly("databaseMariadbProvider");
for (String name : ctx.getBeanDefinitionNames()) {
if ("mariaDbProviderConfig".equals(ctx.getBeanDefinition(name).getFactoryBeanName())) {
assertThat(name).as("bean names carry the plugin id").startsWith("databaseMariadb");
}
}
} }
} }
@Test
void theServerSettingsAreThisPluginsOwnRunningAndSaved() {
try (AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext()) {
String prefix = "runway.plugin.database-mariadb.";
ctx.getEnvironment().getPropertySources().addFirst(new MapPropertySource("test", Map.of(
prefix + "host", "db.running", prefix + "port", "6000", prefix + "database", "runway",
prefix + "username", "rw", prefix + "password", "ENC(only-the-stored-form)",
prefix + "tls", "require", prefix + "collation", "utf8mb4_uca1400_ai_ci",
"runway.plugin.database.host", "not-this-plugins")));
ctx.registerBean(PluginSettings.class, () -> new FakePluginSettings().appSecret("password", "running-pw")
.savedApp("host", "db.saved").savedApp("database", "runway").savedApp("username", "rw2")
.savedApp("password", "saved-pw"));
ctx.register(Binding.class, MariaDbProviderConfig.class);
ctx.refresh();
MariaDbProvider provider = ctx.getBean(MariaDbProvider.class);
ProviderSettings running = provider.runningSettings().orElseThrow();
assertThat(running.host()).isEqualTo("db.running");
assertThat(running.port()).isEqualTo("6000");
assertThat(running.username()).isEqualTo("rw");
assertThat(running.tls()).isEqualTo("require");
assertThat(running.password()).as("in clear, from appSecret").isEqualTo("running-pw");
assertThat(running.collation()).isEqualTo("utf8mb4_uca1400_ai_ci");
ProviderSettings saved = provider.savedSettings().orElseThrow();
assertThat(saved.host()).isEqualTo("db.saved");
assertThat(saved.username()).isEqualTo("rw2");
assertThat(saved.password()).isEqualTo("saved-pw");
assertThat(saved.port()).as("unsaved: blank, the product's default").isNull();
}
}
@Test
void withoutSettingsTheProviderSaysNothingAsBeforeTwo() {
assertThat(new MariaDbProvider().runningSettings()).isEmpty();
assertThat(new MariaDbProvider().savedSettings()).isEmpty();
}
@Test @Test
void theCompiledClassesLinkNoHostInternals() throws Exception { void theCompiledClassesLinkNoHostInternals() throws Exception {
Path classes = Path.of("target", "classes"); Path classes = Path.of("target", "classes");
+16
View File
@@ -2,6 +2,22 @@
All notable changes are recorded here. Versions follow [Semantic Versioning](https://semver.org/). All notable changes are recorded here. Versions follow [Semantic Versioning](https://semver.org/).
## [2.0.0] — 2026-10-30
### Upgrade note
- Install it together with `database` 2.0.0, on Runway 1.2.0 or later, and move the PostgreSQL server's
settings into this plugin as the `database` 2.0.0 *Upgrade note* says. On Runway 1.1.x, keep 1.0.0 of both.
### Changed
- **This plugin holds the PostgreSQL server's settings**: host, port, database, username, password, TLS and CA
certificate, on its own settings page (**Plugins → Database — PostgreSQL → Settings**; file
`external/plugin-settings/database-postgresql.yml`, under `runway.plugin.database-postgresql`). Until 2.0.0 they were the `database` plugin's;
move them as its 2.0.0 *Upgrade note* says.
- Requires `database >= 2.0.0` and Runway SPI 1.2.0 (Runway 1.2.0), whose `PluginSettings.savedApp` hands the saved
settings to the database plugin's connection test.
## [1.0.0] — 2026-10-29 ## [1.0.0] — 2026-10-29
First public release of `database-postgresql`: the PostgreSQL 14+ provider for the `database` plugin, with the First public release of `database-postgresql`: the PostgreSQL 14+ provider for the `database` plugin, with the
+8 -4
View File
@@ -2,11 +2,15 @@
Lets the [`database`](../database) plugin use **PostgreSQL 14 or later** (database encoding `UTF8`). It bundles the Lets the [`database`](../database) plugin use **PostgreSQL 14 or later** (database encoding `UTF8`). It bundles the
pgjdbc driver and builds a configured, unpooled `DataSource`; every statement Runway runs is written in the database pgjdbc driver and builds a configured, unpooled `DataSource`; every statement Runway runs is written in the database
plugin. Choose it with the database plugin's `provider: postgresql` setting. plugin. Since 2.0.0 it also holds the server's settings: host, port, database, account, password and TLS,
on its own settings page (**Plugins → Database — PostgreSQL → Settings**, file `external/plugin-settings/database-postgresql.yml`).
With both providers installed, choose this one with the database plugin's `provider: postgresql` setting; with one
installed, it is used.
- **Plugin id:** `database-postgresql` (v`1.0.0`) — install folder `external/plugins/database-postgresql/` - **Plugin id:** `database-postgresql` (v`2.0.0`) — install folder `external/plugins/database-postgresql/`
- **Requires:** `database >= 1.0.0`, Runway SPI `1.1.0` or later - **Requires:** `database >= 2.0.0`, Runway SPI `1.2.0` or later (Runway 1.2.0)
- **Bundles:** pgjdbc `42.7.10` (BSD-2-Clause) in `lib/`; its license is in `THIRD-PARTY-NOTICES` - **Bundles:** pgjdbc `42.7.10` (BSD-2-Clause) in `lib/`; its license is in `THIRD-PARTY-NOTICES`
Setup, grants and settings: the kernel's ADMINISTRATION §11.1. Details: [`docs/DATABASE-POSTGRESQL-PLUGIN.md`](docs/DATABASE-POSTGRESQL-PLUGIN.md), Setup, grants and settings: the kernel's ADMINISTRATION §11.1 — step by step, the settings file for a setup
without the console, upgrading from 1.x, and a table for when it does not connect. Details: [`docs/DATABASE-POSTGRESQL-PLUGIN.md`](docs/DATABASE-POSTGRESQL-PLUGIN.md),
[`CHANGELOG.md`](CHANGELOG.md). [`CHANGELOG.md`](CHANGELOG.md).
@@ -21,3 +21,17 @@ The provider is one bean, `databasePostgresqlProvider`, collected by type. Tests
properties for each TLS policy, a real connection when `-Ddb.it.postgresql=host:port` and properties for each TLS policy, a real connection when `-Ddb.it.postgresql=host:port` and
`-Ddb.it.password-file=…` are set, the bean name, and the linkage scan). End to end: `-Ddb.it.password-file=…` are set, the bean name, and the linkage scan). End to end:
`../database/scripts/verify-against-host.sh` with `PROVIDER=postgresql`. `../database/scripts/verify-against-host.sh` with `PROVIDER=postgresql`.
## Its settings (since 2.0.0)
The server's settings are this plugin's own app-level settings (`runway.plugin.database-postgresql.*`, the console's **Plugins →
Database — PostgreSQL → Settings**): `host`, `port`, `database`, `username`, `password` (a `secret`, bound to the
others), `tls`, `caCertificate`. The provider hands them to the database plugin raw; the database
plugin checks every one before use, as before:
- **running** (`runningSettings()`): bound at startup into a `ProviderSettingsProps` bean
(`databasePostgresqlSettings`), the password read in clear with `PluginSettings.appSecret("password")`;
- **saved** (`savedSettings()`): read with `PluginSettings.savedApp(key)` (SPI 1.2.0) from the settings file as it is
now, for the database plugin's connection test before a restart applies them.
A `collation` written into this plugin's file by hand is never handed over: it is a MariaDB setting.
@@ -0,0 +1,15 @@
# Runway Database — PostgreSQL provider — English
database-postgresql.group.connection=Server
database-postgresql.group.connection.help=The PostgreSQL server Runway keeps plugins' data on. Changes apply after a restart; test them first with the connection tests on the Database plugin's settings page. In a cluster every node needs the same values.
database-postgresql.set.host=Host
database-postgresql.set.host.help=A host name or an IP address. One server only.
database-postgresql.set.port=Port
database-postgresql.set.port.help=Leave blank for PostgreSQL's default, 5432.
database-postgresql.set.database=Database
database-postgresql.set.database.help=An existing database on the server. Runway creates its schemas inside it.
database-postgresql.set.username=Username
database-postgresql.set.password=Password
database-postgresql.set.tls=TLS
database-postgresql.set.tls.help=verify-full checks the server's certificate and name. require encrypts without checking who the server is. Use disable only for a database on the same host or a private network you trust.
database-postgresql.set.caCertificate=CA certificate (PEM)
database-postgresql.set.caCertificate.help=The certificate authority that signed the server's certificate, when the Java trust store does not know it.
@@ -0,0 +1,15 @@
# Runway Database — PostgreSQL provider — español
database-postgresql.group.connection=Servidor
database-postgresql.group.connection.help=El servidor PostgreSQL donde Runway guarda los datos de los plugins. Los cambios se aplican al reiniciar; pruébelos antes con las pruebas de conexión de la página de ajustes del plugin Base de datos. En un clúster, todos los nodos necesitan los mismos valores.
database-postgresql.set.host=Servidor
database-postgresql.set.host.help=Un nombre de host o una dirección IP. Un solo servidor.
database-postgresql.set.port=Puerto
database-postgresql.set.port.help=Déjelo en blanco para usar el predeterminado de PostgreSQL, 5432.
database-postgresql.set.database=Base de datos
database-postgresql.set.database.help=Una base de datos existente en el servidor. Runway crea sus esquemas dentro de ella.
database-postgresql.set.username=Usuario
database-postgresql.set.password=Contraseña
database-postgresql.set.tls=TLS
database-postgresql.set.tls.help=verify-full comprueba el certificado y el nombre del servidor. require cifra sin comprobar quién es el servidor. Use disable solo para una base de datos en el mismo equipo o en una red privada de confianza.
database-postgresql.set.caCertificate=Certificado de la CA (PEM)
database-postgresql.set.caCertificate.help=La autoridad que firmó el certificado del servidor, cuando el almacén de confianza de Java no la conoce.
+32 -4
View File
@@ -4,16 +4,44 @@
# driver (BSD-2-Clause, in lib/) and builds a configured DataSource; every # driver (BSD-2-Clause, in lib/) and builds a configured DataSource; every
# statement Runway runs is written in the database plugin. # statement Runway runs is written in the database plugin.
# #
# Choose it with the database plugin's `provider: postgresql` setting. # The server, the account and TLS are set on THIS plugin's settings page
# (since 2.0.0); the database plugin keeps the provider choice and the
# limits. With both providers installed, choose this one with the database
# plugin's `provider: postgresql` setting.
#
# The install folder name MUST equal this `id`: external/plugins/database-postgresql/. # The install folder name MUST equal this `id`: external/plugins/database-postgresql/.
# ============================================================================= # =============================================================================
id: database-postgresql id: database-postgresql
name: Database — PostgreSQL name: Database — PostgreSQL
version: 1.0.0 version: 2.0.0
mainClass: mx.quest.database.postgresql.PostgresProviderConfig mainClass: mx.quest.database.postgresql.PostgresProviderConfig
# The database plugin publishes the DatabaseProvider interface this plugin implements. # The database plugin publishes the DatabaseProvider interface this plugin implements.
requires: [ "database >= 1.0.0" ] requires: [ "database >= 2.0.0" ]
requiresSpi: ">=1.1.0" # SPI 1.2.0: PluginSettings.savedApp, which hands the saved settings to the connection test.
requiresSpi: ">=1.2.0"
settingGroups:
- { id: connection, label: database-postgresql.group.connection, help: database-postgresql.group.connection.help }
# Runway-wide settings, applied on RESTART. In a cluster every node needs the same values and the same platform
# secret key. Test them before restarting: Plugins -> Database -> Settings, "Connection tests".
settings:
- { key: host, type: string, group: connection, label: database-postgresql.set.host, help: database-postgresql.set.host.help }
- { key: port, type: int, range: "1..65535", group: connection, label: database-postgresql.set.port,
help: database-postgresql.set.port.help }
- { key: database, type: string, group: connection, label: database-postgresql.set.database,
help: database-postgresql.set.database.help }
- { key: username, type: string, group: connection, label: database-postgresql.set.username }
# Bound to where it goes: changing any of these without typing the password again removes the stored one.
- key: password
type: secret
group: connection
label: database-postgresql.set.password
secretBoundTo: [host, port, database, username, tls, caCertificate]
- { key: tls, type: enum, range: "verify-full,require,disable", default: verify-full, group: connection,
label: database-postgresql.set.tls, help: database-postgresql.set.tls.help }
- { key: caCertificate, type: text, group: connection, advanced: true, label: database-postgresql.set.caCertificate,
help: database-postgresql.set.caCertificate.help }
+7 -4
View File
@@ -17,7 +17,7 @@
<groupId>mx.quest</groupId> <groupId>mx.quest</groupId>
<artifactId>runway-plugin-database-postgresql</artifactId> <artifactId>runway-plugin-database-postgresql</artifactId>
<version>1.0.0</version> <version>2.0.0</version>
<packaging>jar</packaging> <packaging>jar</packaging>
<name>Runway Database — PostgreSQL</name> <name>Runway Database — PostgreSQL</name>
<licenses> <licenses>
@@ -38,11 +38,11 @@
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<!-- Reproducible builds: pins every archive entry's timestamp. Bump at each release. --> <!-- Reproducible builds: pins every archive entry's timestamp. Bump at each release. -->
<project.build.outputTimestamp>2026-10-29T00:00:00Z</project.build.outputTimestamp> <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. --> <!-- The runway-spi this plugin compiles against: SPI 1.2.0 adds PluginSettings.savedApp. -->
<runway.version>1.1.0</runway.version> <runway.version>1.2.0</runway.version>
<!-- The database plugin whose SPI this provider implements (provided: the shared plugin class loader <!-- The database plugin whose SPI this provider implements (provided: the shared plugin class loader
supplies it; install ../database first). --> supplies it; install ../database first). -->
<database.version>1.0.0</database.version> <database.version>2.0.0</database.version>
<!-- The driver bundled in lib/. Pinned so the bundle never drifts from what the notices name. --> <!-- The driver bundled in lib/. Pinned so the bundle never drifts from what the notices name. -->
<postgresql.version>42.7.10</postgresql.version> <postgresql.version>42.7.10</postgresql.version>
</properties> </properties>
@@ -138,6 +138,9 @@
<copy todir="${stage}/lib"> <copy todir="${stage}/lib">
<fileset dir="${project.build.directory}/staged-lib"/> <fileset dir="${project.build.directory}/staged-lib"/>
</copy> </copy>
<copy todir="${stage}/i18n">
<fileset dir="${project.basedir}/i18n"/>
</copy>
<!-- Never a plugin zip without its libraries (it would load and fail at its first use). --> <!-- Never a plugin zip without its libraries (it would load and fail at its first use). -->
<fail message="no library in ${stage}/lib"> <fail message="no library in ${stage}/lib">
<condition><resourcecount when="equal" count="0"> <condition><resourcecount when="equal" count="0">
@@ -1,9 +1,12 @@
package mx.quest.database.postgresql; package mx.quest.database.postgresql;
import java.util.Objects; import java.util.Objects;
import java.util.Optional;
import java.util.function.Supplier;
import javax.sql.DataSource; import javax.sql.DataSource;
import mx.quest.database.spi.ConnectionSettings; import mx.quest.database.spi.ConnectionSettings;
import mx.quest.database.spi.DatabaseProvider; import mx.quest.database.spi.DatabaseProvider;
import mx.quest.database.spi.ProviderSettings;
import org.postgresql.ds.PGSimpleDataSource; import org.postgresql.ds.PGSimpleDataSource;
import org.postgresql.util.DriverInfo; import org.postgresql.util.DriverInfo;
@@ -28,6 +31,25 @@ public final class PostgresProvider implements DatabaseProvider {
static final String JVM_TRUST = "org.postgresql.ssl.DefaultJavaSSLFactory"; static final String JVM_TRUST = "org.postgresql.ssl.DefaultJavaSSLFactory";
static final String CA_FILE = "org.postgresql.ssl.LibPQFactory"; static final String CA_FILE = "org.postgresql.ssl.LibPQFactory";
private final Supplier<ProviderSettings> running;
private final Supplier<ProviderSettings> saved;
/**
* Without settings, as before database 2.0.0: for building data sources only (tests).
*/
public PostgresProvider() {
this(() -> null, () -> null);
}
/**
* @param running the server settings the application started with, from this plugin's own settings page
* @param saved the server settings saved on that page now, which the next restart applies
*/
public PostgresProvider(Supplier<ProviderSettings> running, Supplier<ProviderSettings> saved) {
this.running = Objects.requireNonNull(running, "running");
this.saved = Objects.requireNonNull(saved, "saved");
}
@Override @Override
public String id() { public String id() {
return "postgresql"; return "postgresql";
@@ -76,4 +98,20 @@ public final class PostgresProvider implements DatabaseProvider {
private static int seconds(long value) { private static int seconds(long value) {
return (int) Math.max(1, Math.min(Integer.MAX_VALUE, value)); return (int) Math.max(1, Math.min(Integer.MAX_VALUE, value));
} }
@Override
public Optional<ProviderSettings> runningSettings() {
return Optional.ofNullable(withoutCollation(running.get()));
}
@Override
public Optional<ProviderSettings> savedSettings() {
return Optional.ofNullable(withoutCollation(saved.get()));
}
/** A collation is a MariaDB setting: never handed over from here, even when written into the file by hand. */
private static ProviderSettings withoutCollation(ProviderSettings s) {
return s == null ? null : new ProviderSettings(s.host(), s.port(), s.database(), s.username(), s.password(),
s.tls(), s.caCertificate(), null);
}
} }
@@ -1,14 +1,33 @@
package mx.quest.database.postgresql; package mx.quest.database.postgresql;
import mx.quest.database.spi.ProviderSettings;
import mx.quest.database.spi.ProviderSettingsProps;
import mx.quest.runway.spi.service.PluginSettings;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
/** Registers the PostgreSQL provider; the database plugin collects it by type. */ /**
* Registers the PostgreSQL provider; the database plugin collects it by type. The server's settings are this plugin's
* own app-level settings ({@code runway.plugin.database-postgresql.*}, since database 2.0.0): the running ones as
* bound at startup, the password through {@link PluginSettings#appSecret}, and the saved ones through
* {@link PluginSettings#savedApp} for the connection test. With both providers installed the context holds two
* {@link ProviderSettingsProps} beans, hence the qualifier.
*/
@Configuration(proxyBeanMethods = false) @Configuration(proxyBeanMethods = false)
public class PostgresProviderConfig { public class PostgresProviderConfig {
@Bean @Bean
public PostgresProvider databasePostgresqlProvider() { @ConfigurationProperties("runway.plugin.database-postgresql")
return new PostgresProvider(); public ProviderSettingsProps databasePostgresqlSettings() {
return new ProviderSettingsProps();
}
@Bean
public PostgresProvider databasePostgresqlProvider(
@Qualifier("databasePostgresqlSettings") ProviderSettingsProps server, PluginSettings settings) {
return new PostgresProvider(() -> server.toSettings(settings.appSecret(ProviderSettings.PASSWORD)),
() -> ProviderSettings.read(settings::savedApp));
} }
} }
@@ -12,14 +12,21 @@ import java.sql.Statement;
import java.time.Duration; import java.time.Duration;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.Map;
import java.util.regex.Matcher; import java.util.regex.Matcher;
import java.util.regex.Pattern; import java.util.regex.Pattern;
import java.util.stream.Stream; import java.util.stream.Stream;
import mx.quest.database.spi.ConnectionSettings;
import mx.quest.database.spi.ConnectionSettings.Tls; import mx.quest.database.spi.ConnectionSettings.Tls;
import mx.quest.database.spi.ConnectionSettings;
import mx.quest.database.spi.ProviderSettings;
import mx.quest.runway.spi.service.PluginSettings;
import mx.quest.runway.spi.testkit.FakePluginSettings;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import org.postgresql.ds.PGSimpleDataSource; import org.postgresql.ds.PGSimpleDataSource;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.MapPropertySource;
class PostgresProviderTest { class PostgresProviderTest {
@@ -67,15 +74,66 @@ class PostgresProviderTest {
assertThat(new PostgresProvider().driverVersion()).isEqualTo("pgjdbc 42.7.10"); assertThat(new PostgresProvider().driverVersion()).isEqualTo("pgjdbc 42.7.10");
} }
/** Turns on @ConfigurationProperties binding, as the kernel's context does. */
@Configuration(proxyBeanMethods = false)
@EnableConfigurationProperties
static class Binding {
}
@Test @Test
void theConfigurationRegistersOneProviderNamedForThePlugin() { void theConfigurationRegistersOneProviderNamedForThePlugin() {
try (AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext( try (AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext()) {
PostgresProviderConfig.class)) { ctx.registerBean(PluginSettings.class, FakePluginSettings::new);
ctx.register(Binding.class, PostgresProviderConfig.class);
ctx.refresh();
assertThat(ctx.getBeanNamesForType(mx.quest.database.spi.DatabaseProvider.class)) assertThat(ctx.getBeanNamesForType(mx.quest.database.spi.DatabaseProvider.class))
.containsExactly("databasePostgresqlProvider"); .containsExactly("databasePostgresqlProvider");
for (String name : ctx.getBeanDefinitionNames()) {
if ("postgresProviderConfig".equals(ctx.getBeanDefinition(name).getFactoryBeanName())) {
assertThat(name).as("bean names carry the plugin id").startsWith("databasePostgresql");
}
}
} }
} }
@Test
void theServerSettingsAreThisPluginsOwnRunningAndSaved() {
try (AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext()) {
String prefix = "runway.plugin.database-postgresql.";
ctx.getEnvironment().getPropertySources().addFirst(new MapPropertySource("test", Map.of(
prefix + "host", "db.running", prefix + "port", "6000", prefix + "database", "runway",
prefix + "username", "rw", prefix + "password", "ENC(only-the-stored-form)",
prefix + "tls", "require", prefix + "collation", "utf8mb4_uca1400_ai_ci",
"runway.plugin.database.host", "not-this-plugins")));
ctx.registerBean(PluginSettings.class, () -> new FakePluginSettings().appSecret("password", "running-pw")
.savedApp("host", "db.saved").savedApp("database", "runway").savedApp("username", "rw2")
.savedApp("password", "saved-pw"));
ctx.register(Binding.class, PostgresProviderConfig.class);
ctx.refresh();
PostgresProvider provider = ctx.getBean(PostgresProvider.class);
ProviderSettings running = provider.runningSettings().orElseThrow();
assertThat(running.host()).isEqualTo("db.running");
assertThat(running.port()).isEqualTo("6000");
assertThat(running.username()).isEqualTo("rw");
assertThat(running.tls()).isEqualTo("require");
assertThat(running.password()).as("in clear, from appSecret").isEqualTo("running-pw");
assertThat(running.collation()).as("a MariaDB setting, never handed over").isNull();
ProviderSettings saved = provider.savedSettings().orElseThrow();
assertThat(saved.host()).isEqualTo("db.saved");
assertThat(saved.username()).isEqualTo("rw2");
assertThat(saved.password()).isEqualTo("saved-pw");
assertThat(saved.port()).as("unsaved: blank, the product's default").isNull();
}
}
@Test
void withoutSettingsTheProviderSaysNothingAsBeforeTwo() {
assertThat(new PostgresProvider().runningSettings()).isEmpty();
assertThat(new PostgresProvider().savedSettings()).isEmpty();
}
@Test @Test
void theCompiledClassesLinkNoHostInternals() throws Exception { void theCompiledClassesLinkNoHostInternals() throws Exception {
Path classes = Path.of("target", "classes"); Path classes = Path.of("target", "classes");
+47
View File
@@ -2,6 +2,53 @@
All notable changes are recorded here. Versions follow [Semantic Versioning](https://semver.org/). All notable changes are recorded here. Versions follow [Semantic Versioning](https://semver.org/).
## [2.0.0] — 2026-10-30
The server's settings move to the provider plugins, and the connection tests move to this plugin's settings page.
**A breaking change for the settings**: read the *Upgrade note* first.
### Upgrade note
- Install `database`, and the provider you use, **2.0.0 together**, on Runway **1.2.0** or later (SPI 1.2.0). A 1.x
provider with database 2.0.0 gives *No provider: the database-postgresql plugin is older than 2.0.0*.
- Move the server's keys — `host`, `port`, `database`, `username`, `password`, `tls`, `caCertificate`, and on
MariaDB `collation` — from `external/plugin-settings/database.yml` (under `runway.plugin.database`) to the
provider's file, `external/plugin-settings/database-postgresql.yml` under `runway.plugin.database-postgresql` (or
`database-mariadb`). An encrypted password (`ENC(...)`) moves as it is. Keep `provider`, `namespace` and the limits
in `database.yml`. Or retype the settings on the provider's settings page and delete the old keys. Move them
**before** saving this plugin's settings form: a save keeps only the settings the form has, so it removes the old
keys, encrypted password included.
- Until they are moved, the status is *Not configured: the server settings moved to the database-postgresql plugin
…*, naming the keys to move; Runway never connects with the old keys.
- Then test them (below) and restart.
- On Runway 1.1.x, keep `database` 1.0.0 and its provider 1.0.0.
### Changed
- **The server's settings are the provider's.** Host, port, database, account, password, TLS and CA certificate are
set on the provider plugin's own settings page; MariaDB's collation is on MariaDB's page only. This plugin keeps
the provider choice, the namespace and the limits (pool size, statement time limit, backup budget).
- **The `provider` setting defaults to `auto`**: with one provider plugin installed, it is used; a choice is needed
only when both are installed.
- **The connection tests are below this plugin's settings form** (**Plugins → Database → Settings**), no longer on
the **Database** screen, which now links to them. They test the running connection and **each installed
provider's saved settings**, the ones the next restart would apply, and take no typed values. 1.0.0's test of
typed values is removed: a form with a username and a password box is one a browser fills in with the operator's
own saved console login, which a test would then send to whatever server the form named.
- The password is bound to host, port, database, username, TLS and CA certificate (no longer to the provider, which
now has a password of its own).
### Added
- Provider SPI: `ProviderSettings` (a provider's server settings, raw), `ProviderSettingsProps` (to bind them), and
`DatabaseProvider.runningSettings()` / `savedSettings()` (`default` methods; empty means a provider older than
2.0.0).
### Fixed
- On PostgreSQL, asking for TLS from a server that has TLS off was reported as a refused username or password; it is
now reported as a TLS failure.
## [1.0.0] — 2026-10-29 ## [1.0.0] — 2026-10-29
First public release of `database`: plugins can keep their own data in PostgreSQL 14+ or MariaDB 10.11+, through a First public release of `database`: plugins can keep their own data in PostgreSQL 14+ or MariaDB 10.11+, through a
+15 -7
View File
@@ -11,23 +11,31 @@ settings — stays on files; this plugin is for plugins.
resuming after a failure. resuming after a failure.
- **Backups**: a site's full backup carries its database data in a portable format (PostgreSQL ↔ MariaDB); a restore - **Backups**: a site's full backup carries its database data in a portable format (PostgreSQL ↔ MariaDB); a restore
builds a new generation and switches only when everything loaded. builds a new generation and switches only when everything loaded.
- **A health screen** in the application console (**Settings → Database**) with connection tests and recovery - **A health screen** in the application console (**Settings → Database**) with recovery actions; **connection
actions; one line on each site's dashboard. tests** below this plugin's settings form, which try the running connection and each provider's saved settings
before a restart applies them; one line on each site's dashboard.
- **Runway never fails to start because of the database**: the plugin connects after startup, on its own thread. - **Runway never fails to start because of the database**: the plugin connects after startup, on its own thread.
The product comes from a provider plugin — [`database-postgresql`](../database-postgresql) or The product comes from a provider plugin — [`database-postgresql`](../database-postgresql) or
[`database-mariadb`](../database-mariadb) — which brings the driver; every statement Runway runs is written here. [`database-mariadb`](../database-mariadb) — which brings the driver and, since 2.0.0, holds the server's settings
(host, account, password, TLS) on its own settings page; every statement Runway runs is written here. This plugin's
settings are the provider choice (`auto`: the one installed), the namespace and the limits.
- **Plugin id:** `database` (v`1.0.0`) — install folder `external/plugins/database/` - **Plugin id:** `database` (v`2.0.0`) — install folder `external/plugins/database/`
- **Requires:** Runway with SPI `1.1.0` or later (`requiresSpi: ">=1.1.0"`) and one provider plugin - **Requires:** Runway with SPI `1.2.0` or later (Runway 1.2.0; `requiresSpi: ">=1.2.0"`) and one provider plugin
2.0.0 or later
- **Bundles:** HikariCP `7.0.2` (Apache-2.0) in `lib/`; its license is in `THIRD-PARTY-NOTICES` - **Bundles:** HikariCP `7.0.2` (Apache-2.0) in `lib/`; its license is in `THIRD-PARTY-NOTICES`
- **Publishes:** `mx.quest.database.spi` — the consumer interface (`DatabaseConsumer`, `Databases`, `PluginDatabase`, - **Publishes:** `mx.quest.database.spi` — the consumer interface (`DatabaseConsumer`, `Databases`, `PluginDatabase`,
`Scope`, `Dialect`) and the provider interface (`DatabaseProvider`, `ConnectionSettings`) `Scope`, `Dialect`) and the provider interface (`DatabaseProvider`, `ConnectionSettings`, `ProviderSettings`,
`ProviderSettingsProps`)
## For operators ## For operators
Installation, the server's grants, every setting, TLS, clusters, backups and recovery are in the kernel's Installation, the server's grants, every setting, TLS, clusters, backups and recovery are in the kernel's
**ADMINISTRATION §11.1**. **ADMINISTRATION §11.1**: *Setting it up, step by step*, *Setting it up without the console* (the provider's
`external/plugin-settings/database-postgresql.yml` or `database-mariadb.yml` file and its password), *Upgrading from
database 1.x* and *When it does not connect*. What site managers
see (the dashboard card, backups, the guestbook) is in the **SITE-MANAGER-GUIDE**, §8 and §12.
## For plugin authors ## For plugin authors
+6 -4
View File
@@ -24,7 +24,7 @@ reaches every schema.
| Part | Where | Job | | Part | Where | Job |
|---|---|---| |---|---|---|
| Settings | `DatabaseProps` → `DatabaseConfig` | Bound from `runway.plugin.database.*`; checked before any use. The password comes from `PluginSettings.appSecret("password")` (SPI 1.1.0). | | Settings | `DatabaseProps`, `ProviderChoice` → `DatabaseConfig` | This plugin's own settings (provider choice, namespace, limits) bound from `runway.plugin.database.*`; `ProviderChoice` picks the provider (`auto`: the one installed) and takes the server's settings from it (`DatabaseProvider.runningSettings()`, since 2.0.0); `DatabaseConfig` checks every value before any use. 1.x server keys still in `database.yml` are bound only to report that they moved. |
| Runtime | `DatabaseRuntime` | Connects after startup on the plugin's executor, with back-off; checks the server; owns the pools. | | Runtime | `DatabaseRuntime` | Connects after startup on the plugin's executor, with back-off; checks the server; owns the pools. |
| Engines | `PostgresEngine`, `MariaDbEngine` | **All** the SQL Runway runs, per product. | | Engines | `PostgresEngine`, `MariaDbEngine` | **All** the SQL Runway runs, per product. |
| Registry | `Registry` | Runway's own `rw_` tables in `<ns>_app`. | | Registry | `Registry` | Runway's own `rw_` tables in `<ns>_app`. |
@@ -33,7 +33,7 @@ reaches every schema.
| Migrations | `Migrator` | Brings a plugin's tables in a schema to the shipped version. | | Migrations | `Migrator` | Brings a plugin's tables in a schema to the shipped version. |
| Scopes | `ScopeImpl`, `PluginDatabaseImpl`, `DatabasesImpl` | What consumers call. | | Scopes | `ScopeImpl`, `PluginDatabaseImpl`, `DatabasesImpl` | What consumers call. |
| Backups | `DatabaseBackup`, `Archive`, `Portable` | Export, staged restore, parked data. | | Backups | `DatabaseBackup`, `Archive`, `Portable` | Export, staged restore, parked data. |
| Console | `DatabaseConsoleController`, `DatabaseScreens`, `ConnectionTester` | The health screen and the dashboard line. | | Console | `DatabaseConsoleController`, `DatabaseScreens`, `ConnectionTester` | The health screen, the dashboard line, and the connection tests (panel `templates/admin-app.html`, below this plugin's settings form): the running connection, and each installed provider's **saved** settings (`DatabaseProvider.savedSettings()`, read by the provider through the kernel's `PluginSettings.savedApp`). |
**Providers bring the driver, not the SQL.** A provider builds an unpooled `DataSource` from its own driver **Providers bring the driver, not the SQL.** A provider builds an unpooled `DataSource` from its own driver
classes with the checked settings and pinned properties; nothing goes through `DriverManager`. Every statement — classes with the checked settings and pinned properties; nothing goes through `DriverManager`. Every statement —
@@ -217,8 +217,10 @@ restore counts as done; a staging generation is dropped only while no site maps
URL is built from them and nothing else; the account goes in as properties. MariaDB pins `allowLocalInfile=false`, URL is built from them and nothing else; the account goes in as properties. MariaDB pins `allowLocalInfile=false`,
`allowMultiQueries=false`, `permitRedirect=false`, `allowPublicKeyRetrieval=false`. `allowMultiQueries=false`, `permitRedirect=false`, `allowPublicKeyRetrieval=false`.
- TLS defaults to `verify-full`. The CA certificate is written to an owner-only file in the plugin's folder. - TLS defaults to `verify-full`. The CA certificate is written to an owner-only file in the plugin's folder.
- The password is bound (`secretBoundTo`) to everything that decides where it goes, and the connection test reuses it - The password is bound (`secretBoundTo`, on the provider's page) to everything that decides where it goes. The
only for exactly the running target. connection test takes no typed values, only what is saved: a form with a username and a password box is one a
browser fills with the operator's own console login, which a typed test (1.0.0's) would then send to whatever host
was typed.
- No log line carries the password or a credentialed URL (checked by the tests and the verify script). - No log line carries the password or a credentialed URL (checked by the tests and the verify script).
- The health screen needs `CONFIGURE_PLATFORM`; its recovery actions are logged with the operator's name. - The health screen needs `CONFIGURE_PLATFORM`; its recovery actions are logged with the operator's name.
+17 -24
View File
@@ -1,25 +1,14 @@
# Runway Database — English # Runway Database — English
database.menu=Database database.menu=Database
database.group.connection=Connection database.group.provider=Database product
database.group.connection.help=The database server Runway connects to. Changes apply after a restart; in a cluster every node needs the same values. database.group.provider.help=Which provider plugin Runway uses, and the names it gives its schemas. Changes apply after a restart; in a cluster every node needs the same values. The connection tests are below the form.
database.group.limits=Limits database.group.limits=Limits
database.group.limits.help=How much of the server Runway may use, and how large a site's database backup may be. database.group.limits.help=How much of the server Runway may use, and how large a site's database backup may be.
database.set.provider=Provider database.set.provider=Provider
database.set.provider.help=The database product. Install its provider plugin too: database-postgresql or database-mariadb. database.set.provider.help=auto uses the one provider plugin installed. Choose a product only when both database-postgresql and database-mariadb are installed. The server, the account and TLS are set on the provider plugin's own settings page.
database.set.host=Host
database.set.host.help=A host name or an IP address. One server only.
database.set.port=Port
database.set.port.help=Leave blank for the product's default (5432 for PostgreSQL, 3306 for MariaDB).
database.set.database=Database
database.set.database.help=An existing database on the server. Runway creates its schemas inside it (on MariaDB, databases next to it).
database.set.username=Username
database.set.password=Password
database.set.tls=TLS
database.set.tls.help=verify-full checks the server's certificate and name. require encrypts without checking who the server is. Use disable only for a database on the same host or a private network you trust.
database.set.caCertificate=CA certificate (PEM)
database.set.caCertificate.help=The certificate authority that signed the server's certificate, when the Java trust store does not know it.
database.set.namespace=Namespace database.set.namespace=Namespace
database.set.namespace.help=The start of every schema name Runway creates. Give each installation that shares a server its own. Lower-case letters and digits, starting with a letter, up to 12. database.set.namespace.help=The start of every schema name Runway creates. Give each installation that shares a server its own. Lower-case letters and digits, starting with a letter, up to 12.
database.set.poolMax=Connections database.set.poolMax=Connections
@@ -28,8 +17,6 @@ database.set.statementTimeoutSeconds=Statement time limit (seconds)
database.set.statementTimeoutSeconds.help=A plugin's statement that runs longer is stopped. Migrations, backups and restores have their own, longer limit. database.set.statementTimeoutSeconds.help=A plugin's statement that runs longer is stopped. Migrations, backups and restores have their own, longer limit.
database.set.backupBudgetMiB=Backup budget (MiB) database.set.backupBudgetMiB=Backup budget (MiB)
database.set.backupBudgetMiB.help=The compressed size a site's database data may reach in its backup. Larger data needs the database's own backup tools. database.set.backupBudgetMiB.help=The compressed size a site's database data may reach in its backup. Larger data needs the database's own backup tools.
database.set.collation=Collation (MariaDB)
database.set.collation.help=For plugins' tables on MariaDB. Blank uses utf8mb4_uca1400_ai_ci (utf8mb4_unicode_ci before MariaDB 10.10).
database.console.title=Database database.console.title=Database
database.console.pretitle=Application database.console.pretitle=Application
@@ -46,11 +33,9 @@ database.console.namespace=Namespace
database.console.pool=Connections in use database.console.pool=Connections in use
database.console.schemas=Sites with data database.console.schemas=Sites with data
database.console.lastError=Last error database.console.lastError=Last error
database.console.tests=Connection tests database.console.settings=Settings and tests
database.console.testRunning=Test running connection database.console.settings.text=The provider choice and the limits are on the Database plugin's settings page, together with the connection tests. The server, the account and TLS are on the provider plugin's settings page.
database.console.testNew=Test these settings database.console.settings.link=Settings and connection tests
database.console.testNew.help=Try other settings without saving them. Nothing is changed.
database.console.testNew.password=A blank password reuses the saved one only for the same provider, server, database, account and TLS settings.
database.console.issues=Plugin tables needing attention database.console.issues=Plugin tables needing attention
database.console.none=None. database.console.none=None.
database.console.schema=Schema database.console.schema=Schema
@@ -90,8 +75,6 @@ database.recover.done=Done. The plugin checks its tables again on its next datab
database.test.ok=Connected: {0}. database.test.ok=Connected: {0}.
database.test.invalid_settings=The settings cannot be used: {0} database.test.invalid_settings=The settings cannot be used: {0}
database.test.invalid=The settings cannot be used: {0}
database.test.port=the port is not a number
database.test.no_provider=The provider plugin {0} is not installed. database.test.no_provider=The provider plugin {0} is not installed.
database.test.unreachable=The server could not be reached. database.test.unreachable=The server could not be reached.
database.test.tls=The TLS handshake failed (certificate or TLS settings). database.test.tls=The TLS handshake failed (certificate or TLS settings).
@@ -101,6 +84,16 @@ database.test.unsupported_server=The server is not supported: {0}
database.test.not_available=The database is not in use: {0} database.test.not_available=The database is not in use: {0}
database.test.other=The test failed; see the server log. database.test.other=The test failed; see the server log.
database.panel.title=Connection tests
database.panel.intro=Settings saved here and on a provider's page apply at the next restart. Test them first: the test connects once with the saved values and changes nothing.
database.panel.now=Running now:
database.panel.testRunning=Test the running connection
database.panel.testSaved=Test the saved {0} settings
database.panel.edit=Edit the {0} settings
database.panel.none=No provider plugin is installed: install database-postgresql or database-mariadb.
database.product.postgresql=PostgreSQL
database.product.mariadb=MariaDB
database.dashboard.title=Database database.dashboard.title=Database
database.dashboard.has=This site keeps plugin data in the database. database.dashboard.has=This site keeps plugin data in the database.
database.dashboard.none=This site keeps no data in the database. database.dashboard.none=This site keeps no data in the database.
+17 -24
View File
@@ -1,25 +1,14 @@
# Runway Database — español # Runway Database — español
database.menu=Base de datos database.menu=Base de datos
database.group.connection=Conexión database.group.provider=Producto de base de datos
database.group.connection.help=El servidor de base de datos al que se conecta Runway. Los cambios se aplican al reiniciar; en un clúster, todos los nodos necesitan los mismos valores. database.group.provider.help=Qué plugin proveedor usa Runway y los nombres que da a sus esquemas. Los cambios se aplican al reiniciar; en un clúster, todos los nodos necesitan los mismos valores. Las pruebas de conexión están debajo del formulario.
database.group.limits=Límites database.group.limits=Límites
database.group.limits.help=Cuánto del servidor puede usar Runway y qué tamaño puede alcanzar el respaldo de la base de datos de un sitio. database.group.limits.help=Cuánto del servidor puede usar Runway y qué tamaño puede alcanzar el respaldo de la base de datos de un sitio.
database.set.provider=Proveedor database.set.provider=Proveedor
database.set.provider.help=El producto de base de datos. Instale también su plugin proveedor: database-postgresql o database-mariadb. database.set.provider.help=auto usa el único plugin proveedor instalado. Elija un producto solo cuando estén instalados database-postgresql y database-mariadb. El servidor, el usuario y TLS se configuran en la página de ajustes del propio plugin proveedor.
database.set.host=Servidor
database.set.host.help=Un nombre de host o una dirección IP. Un solo servidor.
database.set.port=Puerto
database.set.port.help=Déjelo en blanco para usar el predeterminado (5432 para PostgreSQL, 3306 para MariaDB).
database.set.database=Base de datos
database.set.database.help=Una base de datos existente en el servidor. Runway crea sus esquemas dentro de ella (en MariaDB, bases de datos junto a ella).
database.set.username=Usuario
database.set.password=Contraseña
database.set.tls=TLS
database.set.tls.help=verify-full comprueba el certificado y el nombre del servidor. require cifra sin comprobar quién es el servidor. Use disable solo para una base de datos en el mismo equipo o en una red privada de confianza.
database.set.caCertificate=Certificado de la CA (PEM)
database.set.caCertificate.help=La autoridad que firmó el certificado del servidor, cuando el almacén de confianza de Java no la conoce.
database.set.namespace=Espacio de nombres database.set.namespace=Espacio de nombres
database.set.namespace.help=El inicio de cada nombre de esquema que crea Runway. Dé uno distinto a cada instalación que comparta un servidor. Minúsculas y dígitos, empezando por una letra, hasta 12. database.set.namespace.help=El inicio de cada nombre de esquema que crea Runway. Dé uno distinto a cada instalación que comparta un servidor. Minúsculas y dígitos, empezando por una letra, hasta 12.
database.set.poolMax=Conexiones database.set.poolMax=Conexiones
@@ -28,8 +17,6 @@ database.set.statementTimeoutSeconds=Límite por sentencia (segundos)
database.set.statementTimeoutSeconds.help=Se detiene la sentencia de un plugin que tarde más. Las migraciones, los respaldos y las restauraciones tienen su propio límite, más largo. database.set.statementTimeoutSeconds.help=Se detiene la sentencia de un plugin que tarde más. Las migraciones, los respaldos y las restauraciones tienen su propio límite, más largo.
database.set.backupBudgetMiB=Presupuesto de respaldo (MiB) database.set.backupBudgetMiB=Presupuesto de respaldo (MiB)
database.set.backupBudgetMiB.help=El tamaño comprimido que pueden alcanzar los datos de base de datos de un sitio en su respaldo. Para datos mayores, use las herramientas de respaldo de la propia base de datos. database.set.backupBudgetMiB.help=El tamaño comprimido que pueden alcanzar los datos de base de datos de un sitio en su respaldo. Para datos mayores, use las herramientas de respaldo de la propia base de datos.
database.set.collation=Intercalación (MariaDB)
database.set.collation.help=Para las tablas de los plugins en MariaDB. En blanco se usa utf8mb4_uca1400_ai_ci (utf8mb4_unicode_ci antes de MariaDB 10.10).
database.console.title=Base de datos database.console.title=Base de datos
database.console.pretitle=Aplicación database.console.pretitle=Aplicación
@@ -46,11 +33,9 @@ database.console.namespace=Espacio de nombres
database.console.pool=Conexiones en uso database.console.pool=Conexiones en uso
database.console.schemas=Sitios con datos database.console.schemas=Sitios con datos
database.console.lastError=Último error database.console.lastError=Último error
database.console.tests=Pruebas de conexión database.console.settings=Ajustes y pruebas
database.console.testRunning=Probar la conexión en uso database.console.settings.text=La elección del proveedor y los límites están en la página de ajustes del plugin Base de datos, junto con las pruebas de conexión. El servidor, el usuario y TLS están en la página de ajustes del plugin proveedor.
database.console.testNew=Probar estos ajustes database.console.settings.link=Ajustes y pruebas de conexión
database.console.testNew.help=Pruebe otros ajustes sin guardarlos. No se cambia nada.
database.console.testNew.password=Una contraseña en blanco reutiliza la guardada solo con el mismo proveedor, servidor, base de datos, usuario y ajustes de TLS.
database.console.issues=Tablas de plugins que requieren atención database.console.issues=Tablas de plugins que requieren atención
database.console.none=Ninguno. database.console.none=Ninguno.
database.console.schema=Esquema database.console.schema=Esquema
@@ -90,8 +75,6 @@ database.recover.done=Hecho. El plugin vuelve a comprobar sus tablas en su próx
database.test.ok=Conectado: {0}. database.test.ok=Conectado: {0}.
database.test.invalid_settings=Los ajustes no se pueden usar: {0} database.test.invalid_settings=Los ajustes no se pueden usar: {0}
database.test.invalid=Los ajustes no se pueden usar: {0}
database.test.port=el puerto no es un número
database.test.no_provider=El plugin proveedor {0} no está instalado. database.test.no_provider=El plugin proveedor {0} no está instalado.
database.test.unreachable=No se pudo alcanzar el servidor. database.test.unreachable=No se pudo alcanzar el servidor.
database.test.tls=Falló el intercambio TLS (certificado o ajustes de TLS). database.test.tls=Falló el intercambio TLS (certificado o ajustes de TLS).
@@ -101,6 +84,16 @@ database.test.unsupported_server=El servidor no es compatible: {0}
database.test.not_available=La base de datos no está en uso: {0} database.test.not_available=La base de datos no está en uso: {0}
database.test.other=La prueba falló; consulte el registro del servidor. database.test.other=La prueba falló; consulte el registro del servidor.
database.panel.title=Pruebas de conexión
database.panel.intro=Los ajustes guardados aquí y en la página de un proveedor se aplican en el próximo reinicio. Pruébelos antes: la prueba se conecta una vez con los valores guardados y no cambia nada.
database.panel.now=En uso ahora:
database.panel.testRunning=Probar la conexión en uso
database.panel.testSaved=Probar los ajustes guardados de {0}
database.panel.edit=Editar los ajustes de {0}
database.panel.none=No hay ningún plugin proveedor instalado: instale database-postgresql o database-mariadb.
database.product.postgresql=PostgreSQL
database.product.mariadb=MariaDB
database.dashboard.title=Base de datos database.dashboard.title=Base de datos
database.dashboard.has=Este sitio guarda datos de plugins en la base de datos. database.dashboard.has=Este sitio guarda datos de plugins en la base de datos.
database.dashboard.none=Este sitio no guarda datos en la base de datos. database.dashboard.none=Este sitio no guarda datos en la base de datos.
+12 -26
View File
@@ -9,18 +9,21 @@
# read only from its own jar and checked for ownership. # read only from its own jar and checked for ownership.
# - A site's database data travels in its full backups (not in transfer copies). # - A site's database data travels in its full backups (not in transfer copies).
# - The product comes from a provider plugin: database-postgresql or # - The product comes from a provider plugin: database-postgresql or
# database-mariadb. This plugin holds no driver. # database-mariadb. This plugin holds no driver, and since 2.0.0 no server
# settings either: host, account, password and TLS are set on the
# provider plugin's own settings page.
# #
# The install folder name MUST equal this `id`: external/plugins/database/. # The install folder name MUST equal this `id`: external/plugins/database/.
# ============================================================================= # =============================================================================
id: database id: database
name: Database name: Database
version: 1.0.0 version: 2.0.0
mainClass: mx.quest.database.DatabasePluginConfig mainClass: mx.quest.database.DatabasePluginConfig
# SPI 1.1.0: PluginSettings.appSecret, which reads the Runway-wide password in clear. # SPI 1.2.0: PluginSettings.savedApp, which the providers use to hand over their saved settings for the
requiresSpi: ">=1.1.0" # connection test (the database plugin itself reads no secret).
requiresSpi: ">=1.2.0"
# In each site's folder (sites/<id>/plugins/database/): the token that ties the site to its schema, and data kept # In each site's folder (sites/<id>/plugins/database/): the token that ties the site to its schema, and data kept
# for plugins that were not installed when a backup was restored. Both stay out of transfer copies: a copy of a site # for plugins that were not installed when a backup was restored. Both stay out of transfer copies: a copy of a site
@@ -31,31 +34,16 @@ siteData:
- deferred/ - deferred/
settingGroups: settingGroups:
- { id: connection, label: database.group.connection, help: database.group.connection.help } - { id: provider, label: database.group.provider, help: database.group.provider.help }
- { id: limits, label: database.group.limits, help: database.group.limits.help } - { id: limits, label: database.group.limits, help: database.group.limits.help }
# Runway-wide settings, applied on RESTART. In a cluster every node needs the same values and the same platform # Runway-wide settings, applied on RESTART. In a cluster every node needs the same values and the same platform
# secret key. Changing the server or the provider does not move data: move sites with backup and restore. # secret key. The server's settings are on the provider plugin's page. Changing the server or the provider does not
# move data: move sites with backup and restore. The connection tests sit below this form (templates/admin-app.html).
settings: settings:
- { key: provider, type: enum, range: "postgresql,mariadb", default: postgresql, group: connection, - { key: provider, type: enum, range: "auto,postgresql,mariadb", default: auto, group: provider,
label: database.set.provider, help: database.set.provider.help } label: database.set.provider, help: database.set.provider.help }
- { key: host, type: string, group: connection, label: database.set.host, help: database.set.host.help } - { key: namespace, type: string, default: rw, group: provider, advanced: true, label: database.set.namespace,
- { key: port, type: int, range: "1..65535", group: connection, label: database.set.port,
help: database.set.port.help }
- { key: database, type: string, group: connection, label: database.set.database,
help: database.set.database.help }
- { key: username, type: string, group: connection, label: database.set.username }
# Bound to where it goes: changing any of these without typing the password again removes the stored one.
- key: password
type: secret
group: connection
label: database.set.password
secretBoundTo: [provider, host, port, database, username, tls, caCertificate]
- { key: tls, type: enum, range: "verify-full,require,disable", default: verify-full, group: connection,
label: database.set.tls, help: database.set.tls.help }
- { key: caCertificate, type: text, group: connection, advanced: true, label: database.set.caCertificate,
help: database.set.caCertificate.help }
- { key: namespace, type: string, default: rw, group: connection, advanced: true, label: database.set.namespace,
help: database.set.namespace.help } help: database.set.namespace.help }
- { key: poolMax, type: int, default: 10, range: "2..200", group: limits, label: database.set.poolMax, - { key: poolMax, type: int, default: 10, range: "2..200", group: limits, label: database.set.poolMax,
help: database.set.poolMax.help } help: database.set.poolMax.help }
@@ -63,8 +51,6 @@ settings:
label: database.set.statementTimeoutSeconds, help: database.set.statementTimeoutSeconds.help } label: database.set.statementTimeoutSeconds, help: database.set.statementTimeoutSeconds.help }
- { key: backupBudgetMiB, type: int, default: 128, range: "1..4096", group: limits, - { key: backupBudgetMiB, type: int, default: 128, range: "1..4096", group: limits,
label: database.set.backupBudgetMiB, help: database.set.backupBudgetMiB.help } label: database.set.backupBudgetMiB, help: database.set.backupBudgetMiB.help }
- { key: collation, type: string, group: limits, advanced: true, label: database.set.collation,
help: database.set.collation.help }
# The health screen, under the application console's Settings menu. The controller enforces the same permission. # The health screen, under the application console's Settings menu. The controller enforces the same permission.
menu: menu:
+3 -3
View File
@@ -19,7 +19,7 @@
<groupId>mx.quest</groupId> <groupId>mx.quest</groupId>
<artifactId>runway-plugin-database</artifactId> <artifactId>runway-plugin-database</artifactId>
<version>1.0.0</version> <version>2.0.0</version>
<packaging>jar</packaging> <packaging>jar</packaging>
<name>Runway Database</name> <name>Runway Database</name>
<licenses> <licenses>
@@ -42,8 +42,8 @@
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<!-- Reproducible builds: pins every archive entry's timestamp. Bump at each release. --> <!-- Reproducible builds: pins every archive entry's timestamp. Bump at each release. -->
<project.build.outputTimestamp>2026-10-29T00:00:00Z</project.build.outputTimestamp> <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. --> <!-- The runway-spi this plugin compiles against: SPI 1.2.0 adds PluginSettings.savedApp. -->
<runway.version>1.1.0</runway.version> <runway.version>1.2.0</runway.version>
<!-- Bundled in lib/ (Apache-2.0). Managed by Boot 4.0.6; pinned here so the bundle never drifts. --> <!-- Bundled in lib/ (Apache-2.0). Managed by Boot 4.0.6; pinned here so the bundle never drifts. -->
<hikaricp.version>7.0.2</hikaricp.version> <hikaricp.version>7.0.2</hikaricp.version>
<!-- Test only: the drivers the provider plugins bundle, for the tests against real servers. --> <!-- Test only: the drivers the provider plugins bundle, for the tests against real servers. -->
@@ -3,10 +3,14 @@
# Verify the database plugin and both providers inside a real Runway. # Verify the database plugin and both providers inside a real Runway.
# #
# Boots a throwaway Runway (wizard, then ACTIVE) with database, database-postgresql and database-mariadb installed # Boots a throwaway Runway (wizard, then ACTIVE) with database, database-postgresql and database-mariadb installed
# and the database plugin pointed at a server you name, then checks: # and the chosen provider pointed at a server you name, then checks:
# - a 1.x database.yml (server keys in the database plugin's file) is reported as moved, and never used;
# - all three plugins load: none blocked or quarantined, no linkage or surface findings; # - all three plugins load: none blocked or quarantined, no linkage or surface findings;
# - the runtime connects (on its own thread, after startup) and the password appears in no log line; # - the runtime connects (on its own thread, after startup) and the password appears in no log line;
# - the application console's database screen answers only after login, and its running-connection test passes; # - the application console's database screen answers only after login and points to the settings page;
# - the settings pages: the provider's holds the server, the database plugin's holds the connection tests, which
# take no typed values; the running test passes, and the saved test reads the provider's file as saved now
# (a wrong password saved after startup is refused while the running connection stays up);
# - a site's dashboard shows the database card. # - a site's dashboard shows the database card.
# #
# Usage: # Usage:
@@ -96,7 +100,7 @@ curl -s -o /dev/null -X POST "$BASE/setup" --data-urlencode "username=$APP_USER"
for _ in $(seq 1 30); do kill -0 "$PID" 2>/dev/null || break; sleep 1; done for _ in $(seq 1 30); do kill -0 "$PID" 2>/dev/null || break; sleep 1; done
stop_host stop_host
# A hand-written plaintext password works like an encrypted one; this file is deleted with the scratch folder. # 1.x layout first: the server keys in the database plugin's own file. 2.0.0 must say they moved, and not connect.
umask 077 umask 077
cat > "$EXT/plugin-settings/database.yml" <<EOF cat > "$EXT/plugin-settings/database.yml" <<EOF
runway: runway:
@@ -112,6 +116,38 @@ runway:
tls: disable tls: disable
EOF EOF
umask 022 umask 022
echo "[verify] booting host (ACTIVE, 1.x settings) ..."
boot "$SCRATCH/legacy.log"
wait_for "$SCRATCH/legacy.log" "Started RunwayApplication" 90 || { echo "ACTIVE did not start"; tail -20 "$SCRATCH/legacy.log"; exit 1; }
wait_for "$SCRATCH/legacy.log" "database: not configured" 30
stop_host
echo "== 1.x settings =="
ck "reported as moved to the provider plugin" "grep -q 'not configured: the server settings moved to the database-$PROVIDER plugin' '$SCRATCH/legacy.log'"
ck "never used to connect" "! grep -q 'database: connected to' '$SCRATCH/legacy.log'"
# 2.0.0 layout. Both providers are installed, so the database plugin names one (auto would ask which). A hand-written
# plaintext password works like an encrypted one; these files are deleted with the scratch folder.
if [ "$PROVIDER" = postgresql ]; then PRODUCT=PostgreSQL; else PRODUCT=MariaDB; fi
umask 077
cat > "$EXT/plugin-settings/database.yml" <<EOF
runway:
plugin:
database:
provider: $PROVIDER
namespace: $NS
EOF
cat > "$EXT/plugin-settings/database-$PROVIDER.yml" <<EOF
runway:
plugin:
database-$PROVIDER:
host: "$DB_HOST"
port: $DB_PORT
database: "$DB_NAME"
username: "$DB_USER"
password: "$DB_PASSWORD"
tls: disable
EOF
umask 022
echo "[verify] booting host (ACTIVE) ..." echo "[verify] booting host (ACTIVE) ..."
boot "$LOG" boot "$LOG"
@@ -128,7 +164,7 @@ ck "HikariCP and the drivers are in lib/" "ls '$EXT/plugins/database/lib/'Hikari
echo "== connection ==" echo "== connection =="
ck "connected after startup, on its own thread" "grep -E 'database: connected to' '$LOG' | grep -qv '\\[main\\]'" ck "connected after startup, on its own thread" "grep -E 'database: connected to' '$LOG' | grep -qv '\\[main\\]'"
ck "the password appears in no log line" "! grep -qF -- '$DB_PASSWORD' '$LOG' '$SCRATCH/wizard.log'" ck "the password appears in no log line" "! grep -qF -- '$DB_PASSWORD' '$LOG' '$SCRATCH/wizard.log' '$SCRATCH/legacy.log'"
echo "== application console ==" echo "== application console =="
ck "the screen needs a login" "[ \"\$(code '$BASE/__app/database')\" = 302 ]" ck "the screen needs a login" "[ \"\$(code '$BASE/__app/database')\" = 302 ]"
@@ -138,10 +174,37 @@ ac -o /dev/null -X POST "$BASE/app/login" --data-urlencode "username=$APP_USER"
ac "$BASE/__app/database" > "$SCRATCH/screen.html" ac "$BASE/__app/database" > "$SCRATCH/screen.html"
ck "the screen renders for the master" "grep -q 'Connected.' '$SCRATCH/screen.html' && grep -q '$NS' '$SCRATCH/screen.html'" ck "the screen renders for the master" "grep -q 'Connected.' '$SCRATCH/screen.html' && grep -q '$NS' '$SCRATCH/screen.html'"
ck "the screen holds no password" "! grep -qF -- '$DB_PASSWORD' '$SCRATCH/screen.html'" ck "the screen holds no password" "! grep -qF -- '$DB_PASSWORD' '$SCRATCH/screen.html'"
ac -L "$BASE/__app/database/test-running" --data-urlencode "_csrf=$(token < "$SCRATCH/screen.html")" \ ck "the screen points to the settings page" "grep -q '/__app/plugins/database/settings#db-tests' '$SCRATCH/screen.html'"
> "$SCRATCH/tested.html" ck "the screen has no test form any more" "! grep -qE 'test-new|type=\"password\"' '$SCRATCH/screen.html'"
ck "Test running connection: connected" "grep -qE 'Connected: (PostgreSQL|MariaDB)' '$SCRATCH/tested.html'" ck "the 1.x typed test is gone" "[ \"\$(ac -o /dev/null -w '%{http_code}' -X POST '$BASE/__app/database/test-new' --data-urlencode '_csrf=$(token < "$SCRATCH/screen.html")')\" != 302 ]"
ck "a POST without the CSRF token is refused" "[ \"\$(code -b '$SCRATCH/app.jar' -X POST '$BASE/__app/database/test-running')\" = 403 ]"
echo "== settings pages =="
ac "$BASE/__app/plugins/database/settings" > "$SCRATCH/settings.html"
ck "the database page has the provider choice" "grep -q 'name=\"provider\"' '$SCRATCH/settings.html'"
ck "the database page has no server fields" "! grep -qE 'name=\"(host|username|password)\"' '$SCRATCH/settings.html'"
ck "the connection tests are below its form" "grep -q 'id=\"db-tests\"' '$SCRATCH/settings.html' && grep -q 'Test the saved $PRODUCT settings' '$SCRATCH/settings.html'"
ck "the panel shows the running status" "grep -q 'Running now:' '$SCRATCH/settings.html' && grep -q 'Connected\\.' '$SCRATCH/settings.html'"
ac "$BASE/__app/plugins/database-$PROVIDER/settings" > "$SCRATCH/provider.html"
ck "the provider page holds the server" "grep -q 'value=\"$DB_HOST\"' '$SCRATCH/provider.html' && grep -q 'name=\"username\"' '$SCRATCH/provider.html'"
ck "its password box is never autofilled" "grep -q 'autocomplete=\"new-password\"' '$SCRATCH/provider.html' && ! grep -q 'type=\"password\"[^>]*autocomplete=\"off\"' '$SCRATCH/provider.html'"
ck "the pages hold no password" "! grep -qF -- '$DB_PASSWORD' '$SCRATCH/provider.html' '$SCRATCH/settings.html'"
if [ "$PROVIDER" = mariadb ]; then
ck "collation is on the MariaDB page only" "grep -q 'name=\"collation\"' '$SCRATCH/provider.html' && ! grep -q 'name=\"collation\"' '$SCRATCH/settings.html'"
fi
CSRF="$(token < "$SCRATCH/settings.html")"
ac -L "$BASE/__app/database/test-running" --data-urlencode "_csrf=$CSRF" > "$SCRATCH/tested.html"
ck "Test the running connection: connected" "grep -qE 'Connected: (PostgreSQL|MariaDB)' '$SCRATCH/tested.html' && grep -q 'id=\"db-tests\"' '$SCRATCH/tested.html'"
ac -L "$BASE/__app/database/test-saved" --data-urlencode "_csrf=$CSRF" --data-urlencode "provider=$PROVIDER" > "$SCRATCH/saved.html"
ck "Test the saved settings: connected" "grep -qE 'Connected: $PRODUCT' '$SCRATCH/saved.html'"
# Save a wrong password after startup, as the provider's form would (only a restart would apply it): the saved test
# reads the file as it is now, and the running connection is untouched.
sed -i 's/^ password: .*/ password: "not-the-password"/' "$EXT/plugin-settings/database-$PROVIDER.yml"
ac -L "$BASE/__app/database/test-saved" --data-urlencode "_csrf=$CSRF" --data-urlencode "provider=$PROVIDER" > "$SCRATCH/saved2.html"
ck "a wrong saved password is refused" "grep -q 'The server refused the username or password.' '$SCRATCH/saved2.html'"
ck "the running connection is untouched" "grep -q 'Connected\\.' '$SCRATCH/saved2.html'"
ac -L "$BASE/__app/database/test-saved" --data-urlencode "_csrf=$CSRF" --data-urlencode "provider=oracle" > "$SCRATCH/saved3.html"
ck "an unknown provider is answered, not tested" "grep -q 'is not installed' '$SCRATCH/saved3.html'"
ck "a POST without the CSRF token is refused" "[ \"\$(code -b '$SCRATCH/app.jar' -X POST '$BASE/__app/database/test-saved')\" = 403 ]"
echo "== site console ==" echo "== site console =="
sc() { curl -s -H 'Accept-Language: en' -c "$SCRATCH/site.jar" -b "$SCRATCH/site.jar" "$@"; } sc() { curl -s -H 'Accept-Language: en' -c "$SCRATCH/site.jar" -b "$SCRATCH/site.jar" "$@"; }
@@ -149,6 +212,9 @@ sc -o /dev/null -X POST "$BASE/login" --data-urlencode "username=$SITE_USER" --d
--data-urlencode "_csrf=$(sc "$BASE/login" | token)" --data-urlencode "_csrf=$(sc "$BASE/login" | token)"
ck "the site dashboard shows the database card" "sc '$BASE/__admin' | grep -q 'keeps no data in the database'" ck "the site dashboard shows the database card" "sc '$BASE/__admin' | grep -q 'keeps no data in the database'"
ck "a site admin cannot open the application screen" "[ \"\$(code -b '$SCRATCH/site.jar' '$BASE/__app/database')\" != 200 ]" ck "a site admin cannot open the application screen" "[ \"\$(code -b '$SCRATCH/site.jar' '$BASE/__app/database')\" != 200 ]"
# With the site session's own CSRF token, so a refusal comes from the permission gate, not from a missing token.
SITE_CSRF="$(sc "$BASE/__admin" | token)"
ck "nor test the saved settings" "[ \"\$(code -b '$SCRATCH/site.jar' -X POST --data-urlencode '_csrf=$SITE_CSRF' --data-urlencode 'provider=$PROVIDER' '$BASE/__app/database/test-saved')\" != 302 ]"
ck "no ERROR line names the database plugin" "! grep -E ' ERROR ' '$LOG' | grep -qiE 'mx\\.quest\\.database|database:'" ck "no ERROR line names the database plugin" "! grep -E ' ERROR ' '$LOG' | grep -qiE 'mx\\.quest\\.database|database:'"
@@ -11,7 +11,6 @@ import mx.quest.database.console.DatabaseConsoleController;
import mx.quest.database.console.DatabaseScreens; import mx.quest.database.console.DatabaseScreens;
import mx.quest.database.internal.ConnectionTester; import mx.quest.database.internal.ConnectionTester;
import mx.quest.database.internal.DatabaseBackup; import mx.quest.database.internal.DatabaseBackup;
import mx.quest.database.internal.DatabaseConfig;
import mx.quest.database.internal.DatabaseCore; import mx.quest.database.internal.DatabaseCore;
import mx.quest.database.internal.DatabaseLifecycle; import mx.quest.database.internal.DatabaseLifecycle;
import mx.quest.database.internal.DatabaseProps; import mx.quest.database.internal.DatabaseProps;
@@ -19,12 +18,12 @@ import mx.quest.database.internal.DatabaseRuntime;
import mx.quest.database.internal.DatabaseSiteEvents; import mx.quest.database.internal.DatabaseSiteEvents;
import mx.quest.database.internal.DatabasesImpl; import mx.quest.database.internal.DatabasesImpl;
import mx.quest.database.internal.Migrator; import mx.quest.database.internal.Migrator;
import mx.quest.database.internal.ProviderChoice;
import mx.quest.database.internal.SiteSchemas; import mx.quest.database.internal.SiteSchemas;
import mx.quest.database.spi.DatabaseConsumer; import mx.quest.database.spi.DatabaseConsumer;
import mx.quest.database.spi.DatabaseProvider; import mx.quest.database.spi.DatabaseProvider;
import mx.quest.runway.spi.model.PluginInfo; import mx.quest.runway.spi.model.PluginInfo;
import mx.quest.runway.spi.service.Messages; import mx.quest.runway.spi.service.Messages;
import mx.quest.runway.spi.service.PluginSettings;
import mx.quest.runway.spi.service.PluginSiteFiles; import mx.quest.runway.spi.service.PluginSiteFiles;
import mx.quest.runway.spi.service.RequestContext; import mx.quest.runway.spi.service.RequestContext;
import mx.quest.runway.spi.service.Sites; import mx.quest.runway.spi.service.Sites;
@@ -64,12 +63,11 @@ public class DatabasePluginConfig {
} }
@Bean @Bean
public DatabaseRuntime databaseRuntime(DatabaseProps databaseProps, PluginSettings settings, public DatabaseRuntime databaseRuntime(DatabaseProps databaseProps, ObjectProvider<DatabaseProvider> providers,
ObjectProvider<DatabaseProvider> providers, PluginInfo self, PluginInfo self, ScheduledExecutorService databaseExecutor) {
ScheduledExecutorService databaseExecutor) {
Supplier<List<DatabaseProvider>> found = () -> providers.orderedStream().toList(); Supplier<List<DatabaseProvider>> found = () -> providers.orderedStream().toList();
return new DatabaseRuntime(() -> DatabaseConfig.from(databaseProps, settings.appSecret("password")), found, return new DatabaseRuntime(() -> ProviderChoice.running(databaseProps, found.get()), workDir(self),
workDir(self), databaseExecutor); databaseExecutor);
} }
@Bean @Bean
@@ -115,9 +113,10 @@ public class DatabasePluginConfig {
} }
@Bean @Bean
public ConnectionTester databaseConnectionTester(DatabaseRuntime databaseRuntime, public ConnectionTester databaseConnectionTester(DatabaseRuntime databaseRuntime, DatabaseProps databaseProps,
ObjectProvider<DatabaseProvider> providers, PluginInfo self) { ObjectProvider<DatabaseProvider> providers, PluginInfo self) {
return new ConnectionTester(databaseRuntime, () -> providers.orderedStream().toList(), workDir(self)); return new ConnectionTester(databaseRuntime, databaseProps, () -> providers.orderedStream().toList(),
workDir(self));
} }
@Bean @Bean
@@ -6,10 +6,10 @@ import java.util.Optional;
import mx.quest.database.internal.ConnectionTester; import mx.quest.database.internal.ConnectionTester;
import mx.quest.database.internal.Consumer; import mx.quest.database.internal.Consumer;
import mx.quest.database.internal.DatabaseCore; import mx.quest.database.internal.DatabaseCore;
import mx.quest.database.internal.DatabaseProps;
import mx.quest.database.internal.DatabaseRuntime; import mx.quest.database.internal.DatabaseRuntime;
import mx.quest.database.internal.DatabasesImpl; import mx.quest.database.internal.DatabasesImpl;
import mx.quest.database.internal.Migrator; import mx.quest.database.internal.Migrator;
import mx.quest.database.internal.ProviderChoice;
import mx.quest.database.internal.Registry; import mx.quest.database.internal.Registry;
import mx.quest.database.spi.Scope; import mx.quest.database.spi.Scope;
import mx.quest.runway.spi.service.ConsoleScreen; import mx.quest.runway.spi.service.ConsoleScreen;
@@ -28,8 +28,9 @@ import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes; import org.springframework.web.servlet.mvc.support.RedirectAttributes;
/** /**
* The database screen in the application console ({@code /__app/database}): health, the two connection tests and * The database screen in the application console ({@code /__app/database}): health and the migration recovery
* the migration recovery actions. Every handler needs {@code CONFIGURE_PLATFORM}, which the master and wildcard * actions; and the connection tests, whose panel is on the plugin's settings page and whose result goes back there.
* Every handler needs {@code CONFIGURE_PLATFORM}, which the master and wildcard
* administrators hold; a delegable plugin permission does not open it. Every state change is a CSRF-checked POST, * administrators hold; a delegable plugin permission does not open it. Every state change is a CSRF-checked POST,
* and every recovery action is logged with the operator's name. * and every recovery action is logged with the operator's name.
*/ */
@@ -44,6 +45,11 @@ public class DatabaseConsoleController {
static final String TITLE_KEY = "database.console.title"; static final String TITLE_KEY = "database.console.title";
static final String FLASH = "databaseFlash"; static final String FLASH = "databaseFlash";
static final String FLASH_ERROR = "databaseError"; static final String FLASH_ERROR = "databaseError";
/** The connection tests' result, shown on their panel on the plugin's settings page. */
static final String TEST_FLASH = "databaseTest";
static final String TEST_FLASH_ERROR = "databaseTestError";
/** Where the connection tests are: the panel below the plugin's settings form (templates/admin-app.html). */
static final String SETTINGS_PAGE = "/__app/plugins/database/settings#db-tests";
private static final Logger log = LoggerFactory.getLogger(DatabaseConsoleController.class); private static final Logger log = LoggerFactory.getLogger(DatabaseConsoleController.class);
@@ -77,35 +83,16 @@ public class DatabaseConsoleController {
return result(flash, tester.running()); return result(flash, tester.running());
} }
@PostMapping("/test-new") /** Tests the settings saved on one provider plugin's page; the result shows on the settings page's panel. */
@PostMapping("/test-saved")
@PreAuthorize(GATE) @PreAuthorize(GATE)
public String testNew(@RequestParam(name = "provider", defaultValue = "") String provider, public String testSaved(@RequestParam(name = "provider", defaultValue = "") String provider,
@RequestParam(name = "namespace", defaultValue = "") String namespace, RedirectAttributes flash) {
@RequestParam(name = "host", defaultValue = "") String host, if (!tester.testable().contains(provider)) {
@RequestParam(name = "port", defaultValue = "") String port, return result(flash, new ConnectionTester.Result(ConnectionTester.Category.NO_PROVIDER,
@RequestParam(name = "database", defaultValue = "") String database, ProviderChoice.plugin(provider.isBlank() ? "?" : provider)));
@RequestParam(name = "username", defaultValue = "") String username,
@RequestParam(name = "password", defaultValue = "") String password,
@RequestParam(name = "tls", defaultValue = "") String tls,
@RequestParam(name = "caCertificate", defaultValue = "") String caCertificate,
RedirectAttributes flash) {
DatabaseProps props = new DatabaseProps();
props.setProvider(provider);
props.setNamespace(namespace.isBlank() ? null : namespace);
props.setHost(host);
props.setDatabase(database);
props.setUsername(username);
props.setTls(tls);
props.setCaCertificate(caCertificate);
if (!port.isBlank()) {
try {
props.setPort(Integer.parseInt(port.strip()));
} catch (NumberFormatException e) {
return back(flash, FLASH_ERROR, console("database.test.invalid", "The settings cannot be used: {0}",
console("database.test.port", "the port is not a number")));
}
} }
return result(flash, tester.newSettings(props, password)); return result(flash, tester.saved(provider));
} }
@PostMapping("/recover") @PostMapping("/recover")
@@ -164,7 +151,9 @@ public class DatabaseConsoleController {
case NOT_AVAILABLE -> console(key, "The database is not in use: {0}", result.detail()); case NOT_AVAILABLE -> console(key, "The database is not in use: {0}", result.detail());
default -> console("database.test.other", "The test failed; see the server log."); default -> console("database.test.other", "The test failed; see the server log.");
}; };
return back(flash, result.category() == ConnectionTester.Category.OK ? FLASH : FLASH_ERROR, text); flash.addFlashAttribute(result.category() == ConnectionTester.Category.OK ? TEST_FLASH : TEST_FLASH_ERROR,
text);
return "redirect:" + SETTINGS_PAGE;
} }
private static String operator() { private static String operator() {
@@ -5,8 +5,6 @@ import java.sql.Connection;
import java.sql.SQLException; import java.sql.SQLException;
import java.time.Duration; import java.time.Duration;
import java.util.List; import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.function.Supplier; import java.util.function.Supplier;
import javax.sql.DataSource; import javax.sql.DataSource;
import mx.quest.database.spi.ConnectionSettings; import mx.quest.database.spi.ConnectionSettings;
@@ -15,15 +13,15 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
/** /**
* The console's two connection tests. Each answers with a fixed category (and, for success, the server version); * The connection tests on the database plugin's settings page. Each answers with a fixed category (and, for success,
* the driver's own message goes only to the server log, never with a credential. * the server version); the driver's own message goes only to the server log, never with a credential.
* *
* <ul> * <ul>
* <li><b>Running</b>: borrows from the live pool and asks the server what it is.</li> * <li><b>Running</b>: borrows from the live pool and asks the server what it is.</li>
* <li><b>New settings</b>: opens one throwaway connection with short timeouts from typed values and saves nothing. * <li><b>Saved</b>: opens one throwaway connection with short timeouts from the settings saved on one provider
* A blank password reuses the running one only when every setting the password is bound to (provider, host, * plugin's page, which the next restart would apply, and changes nothing. The test takes no typed values: a
* port, database, username, TLS, CA certificate) matches the running value, so the test cannot send the saved * form with a username and a password box is one a browser fills in with the operator's own saved login,
* password to a server of the tester's choosing.</li> * which a test would then send to whatever server the form named (the 1.x test did exactly that).</li>
* </ul> * </ul>
*/ */
public final class ConnectionTester { public final class ConnectionTester {
@@ -44,15 +42,23 @@ public final class ConnectionTester {
} }
private final DatabaseRuntime runtime; private final DatabaseRuntime runtime;
private final DatabaseProps props;
private final Supplier<List<DatabaseProvider>> providers; private final Supplier<List<DatabaseProvider>> providers;
private final Path workDir; private final Path workDir;
public ConnectionTester(DatabaseRuntime runtime, Supplier<List<DatabaseProvider>> providers, Path workDir) { public ConnectionTester(DatabaseRuntime runtime, DatabaseProps props, Supplier<List<DatabaseProvider>> providers,
Path workDir) {
this.runtime = runtime; this.runtime = runtime;
this.props = props;
this.providers = providers; this.providers = providers;
this.workDir = workDir; this.workDir = workDir;
} }
/** The products whose provider plugin is installed, each once, in the order found: what "Saved" can test. */
public List<String> testable() {
return ProviderChoice.supported(providers.get()).stream().map(DatabaseProvider::id).distinct().toList();
}
/** Tests the live pool. */ /** Tests the live pool. */
public Result running() { public Result running() {
if (!runtime.available()) { if (!runtime.available()) {
@@ -68,35 +74,26 @@ public final class ConnectionTester {
} }
/** /**
* Tests typed settings. * Tests the settings saved on one provider plugin's page.
* *
* @param props the typed values * @param product {@code postgresql} or {@code mariadb}
* @param password the typed password; blank to reuse the running one where the rule allows
*/ */
public Result newSettings(DatabaseProps props, String password) { public Result saved(String product) {
DatabaseConfig typed; List<DatabaseProvider> matching = ProviderChoice.supported(providers.get()).stream()
try { .filter(p -> p.id().equals(product)).toList();
typed = DatabaseConfig.from(props, Optional.empty()); if (matching.size() != 1) {
} catch (IllegalArgumentException e) { return new Result(Category.NO_PROVIDER, ProviderChoice.plugin(String.valueOf(product)));
return new Result(Category.INVALID_SETTINGS, e.getMessage());
}
String secret = password == null ? "" : password;
if (secret.isEmpty()) {
DatabaseConfig running = runtime.config();
if (running != null && sameTarget(running, typed)) {
secret = running.password();
}
} }
DatabaseConfig config; DatabaseConfig config;
try { try {
config = DatabaseConfig.from(props, Optional.of(secret)); config = ProviderChoice.saved(props, matching.get(0)).config();
} catch (IllegalArgumentException e) { } catch (IllegalArgumentException e) {
return new Result(Category.INVALID_SETTINGS, e.getMessage()); return new Result(Category.INVALID_SETTINGS, e.getMessage());
} } catch (RuntimeException e) {
List<DatabaseProvider> matching = providers.get().stream().filter(p -> config.provider().equals(p.id())) // A provider whose saved settings cannot be read; its message is not trusted to be free of a secret.
.toList(); log.warn("database: the saved settings of {} could not be read ({})", ProviderChoice.plugin(product),
if (matching.size() != 1) { e.getClass().getSimpleName());
return new Result(Category.NO_PROVIDER, "database-" + config.provider()); return new Result(Category.OTHER, "");
} }
Engine engine = DatabaseRuntime.engineFor(config.provider()); Engine engine = DatabaseRuntime.engineFor(config.provider());
try { try {
@@ -108,22 +105,15 @@ public final class ConnectionTester {
return new Result(Category.OK, engine.inspectServer(c)); return new Result(Category.OK, engine.inspectServer(c));
} }
} catch (SQLException e) { } catch (SQLException e) {
log.warn("database: new-settings test against {} failed: {}", config, DatabaseRuntime.describe(e)); log.warn("database: saved-settings test against {} failed: {}", config, DatabaseRuntime.describe(e));
return new Result(category(engine.classify(e)), e instanceof UnsupportedServerException ? e.getMessage() return new Result(category(engine.classify(e)), e instanceof UnsupportedServerException ? e.getMessage()
: ""); : "");
} catch (Exception e) { } catch (Exception e) {
log.warn("database: new-settings test against {} failed: {}", config, DatabaseRuntime.describe(e)); log.warn("database: saved-settings test against {} failed: {}", config, DatabaseRuntime.describe(e));
return new Result(Category.OTHER, ""); return new Result(Category.OTHER, "");
} }
} }
/** Whether two settings point the password at the same place as the same account. */
static boolean sameTarget(DatabaseConfig a, DatabaseConfig b) {
return a.provider().equals(b.provider()) && a.host().equals(b.host()) && a.port() == b.port()
&& a.database().equals(b.database()) && a.username().equals(b.username()) && a.tls() == b.tls()
&& Objects.equals(a.caCertificate(), b.caCertificate());
}
private static Category category(Engine.ConnectFailure failure) { private static Category category(Engine.ConnectFailure failure) {
return switch (failure) { return switch (failure) {
case UNREACHABLE -> Category.UNREACHABLE; case UNREACHABLE -> Category.UNREACHABLE;
@@ -10,10 +10,12 @@ import java.util.Optional;
import java.util.Set; import java.util.Set;
import java.util.regex.Pattern; import java.util.regex.Pattern;
import mx.quest.database.spi.ConnectionSettings.Tls; import mx.quest.database.spi.ConnectionSettings.Tls;
import mx.quest.database.spi.ProviderSettings;
/** /**
* The database plugin's settings after checking: what the pool, the names and the console screen use. Built once at * The database plugin's settings after checking: what the pool, the names and the console screen use. Built once at
* startup from {@link DatabaseProps} and the password, and again by "Test new settings" from the form's values. A * startup from {@link DatabaseProps} and the chosen provider's running settings, and by the connection test from a
* provider's saved settings. A
* value the plugin cannot use safely is refused with a reason rather than repaired, except the tuning numbers, which * value the plugin cannot use safely is refused with a reason rather than repaired, except the tuning numbers, which
* are clamped to a working range. * are clamped to a working range.
* *
@@ -66,46 +68,45 @@ public record DatabaseConfig(String provider, String namespace, String host, int
/** /**
* Checks raw settings. * Checks raw settings.
* *
* @param props the bound settings * @param props the database plugin's own settings: namespace and limits (its provider choice is resolved by
* @param password the password in clear, or empty * the caller, {@link ProviderChoice})
* @param provider the chosen provider's id
* @param server the chosen provider's server settings, the password in clear
* @return the checked settings * @return the checked settings
* @throws IllegalArgumentException naming the first setting that is missing or unusable; the message never * @throws IllegalArgumentException naming the first setting that is missing or unusable; the message never
* holds the password * holds the password
*/ */
public static DatabaseConfig from(DatabaseProps props, Optional<String> password) { public static DatabaseConfig from(DatabaseProps props, String provider, ProviderSettings server) {
String provider = trimToNull(props.getProvider()); String product = trimToNull(provider);
if (provider == null) { if (product == null) {
throw new IllegalArgumentException("no provider is chosen"); throw new IllegalArgumentException("no provider is chosen");
} }
provider = provider.toLowerCase(Locale.ROOT); product = product.toLowerCase(Locale.ROOT);
if (!PROVIDERS.contains(provider)) { if (!PROVIDERS.contains(product)) {
throw new IllegalArgumentException("unknown provider: " + provider); throw new IllegalArgumentException("unknown provider: " + product);
} }
String namespace = Names.namespace(Optional.ofNullable(trimToNull(props.getNamespace())).orElse("rw")); String namespace = Names.namespace(Optional.ofNullable(trimToNull(props.getNamespace())).orElse("rw"));
String host = checkHost(props.getHost()); String host = checkHost(server.host());
int port = props.getPort() == null ? 0 : props.getPort(); int port = port(server.port());
if (port < 0 || port > 65535) { String database = trimToNull(server.database());
throw new IllegalArgumentException("the port must be between 1 and 65535, or blank for the default");
}
String database = trimToNull(props.getDatabase());
if (database == null || !DATABASE.matcher(database).matches()) { if (database == null || !DATABASE.matcher(database).matches()) {
throw new IllegalArgumentException("the database name must be 1 to 63 letters, digits, '_', '$' or '-'"); throw new IllegalArgumentException("the database name must be 1 to 63 letters, digits, '_', '$' or '-'");
} }
String username = trimToNull(props.getUsername()); String username = trimToNull(server.username());
if (username == null || username.length() > USERNAME_MAX || hasControl(username)) { if (username == null || username.length() > USERNAME_MAX || hasControl(username)) {
throw new IllegalArgumentException("the username must be 1 to " + USERNAME_MAX throw new IllegalArgumentException("the username must be 1 to " + USERNAME_MAX
+ " characters, without control characters"); + " characters, without control characters");
} }
String secret = password.orElse(""); String secret = server.password() == null ? "" : server.password();
if (secret.length() > PASSWORD_MAX || hasControl(secret)) { if (secret.length() > PASSWORD_MAX || hasControl(secret)) {
throw new IllegalArgumentException("the password is too long or holds control characters"); throw new IllegalArgumentException("the password is too long or holds control characters");
} }
Tls tls = tls(props.getTls()); Tls tls = tls(server.tls());
String ca = trimToNull(props.getCaCertificate()); String ca = trimToNull(server.caCertificate());
if (ca != null) { if (ca != null) {
ca = checkPem(ca); ca = checkPem(ca);
} }
String collation = trimToNull(props.getCollation()); String collation = trimToNull(server.collation());
if (collation != null && !COLLATION.matcher(collation).matches()) { if (collation != null && !COLLATION.matcher(collation).matches()) {
throw new IllegalArgumentException("the collation must be a MariaDB collation name such as " throw new IllegalArgumentException("the collation must be a MariaDB collation name such as "
+ "utf8mb4_uca1400_ai_ci"); + "utf8mb4_uca1400_ai_ci");
@@ -113,10 +114,27 @@ public record DatabaseConfig(String provider, String namespace, String host, int
int poolMax = clamp(props.getPoolMax(), 10, POOL_MIN, POOL_MAX); int poolMax = clamp(props.getPoolMax(), 10, POOL_MIN, POOL_MAX);
int timeout = clamp(props.getStatementTimeoutSeconds(), 10, TIMEOUT_MIN_S, TIMEOUT_MAX_S); int timeout = clamp(props.getStatementTimeoutSeconds(), 10, TIMEOUT_MIN_S, TIMEOUT_MAX_S);
int budget = clamp(props.getBackupBudgetMiB(), 128, BUDGET_MIN_MIB, BUDGET_MAX_MIB); int budget = clamp(props.getBackupBudgetMiB(), 128, BUDGET_MIN_MIB, BUDGET_MAX_MIB);
return new DatabaseConfig(provider, namespace, host, port, database, username, secret, tls, ca, poolMax, return new DatabaseConfig(product, namespace, host, port, database, username, secret, tls, ca, poolMax,
Duration.ofSeconds(timeout), budget * 1024L * 1024L, collation); Duration.ofSeconds(timeout), budget * 1024L * 1024L, collation);
} }
/** The port: blank for the product's default (0), else 1–65535. */
static int port(String value) {
String v = trimToNull(value);
if (v == null) {
return 0;
}
try {
int port = Integer.parseInt(v);
if (port >= 1 && port <= 65535) {
return port;
}
} catch (NumberFormatException e) {
// reported below
}
throw new IllegalArgumentException("the port must be between 1 and 65535, or blank for the default");
}
/** The TLS setting: {@code disable}, {@code require} or {@code verify-full} (the default). */ /** The TLS setting: {@code disable}, {@code require} or {@code verify-full} (the default). */
static Tls tls(String value) { static Tls tls(String value) {
String v = trimToNull(value); String v = trimToNull(value);
@@ -1,25 +1,54 @@
package mx.quest.database.internal; package mx.quest.database.internal;
import java.util.ArrayList;
import java.util.List;
/** /**
* The database plugin's app-level settings as bound from {@code runway.plugin.database.*} at startup * The database plugin's app-level settings as bound from {@code runway.plugin.database.*} at startup
* ({@code external/plugin-settings/database.yml}). Raw values: {@link DatabaseConfig#from} checks them. The password * ({@code external/plugin-settings/database.yml}): the provider choice, the namespace and the limits. Raw values:
* is not here: it is read in clear through {@code PluginSettings.appSecret("password")}. * {@link DatabaseConfig#from} checks them. The server's own settings (host, account, password, TLS) belong to the
* provider plugin since 2.0.0 ({@link mx.quest.database.spi.ProviderSettings}).
*
* <p>The 1.x connection keys are still bound, only so that a {@code database.yml} that still holds them can be
* reported as moved ({@link #legacyKeys()}) rather than read as "nothing is set". They are never used to connect.
*/ */
public class DatabaseProps { public class DatabaseProps {
private String provider = "auto";
private String provider;
private String namespace = "rw"; private String namespace = "rw";
private String host;
private Integer port;
private String database;
private String username;
private String tls = "verify-full";
private String caCertificate;
private Integer poolMax = 10; private Integer poolMax = 10;
private Integer statementTimeoutSeconds = 10; private Integer statementTimeoutSeconds = 10;
private Integer backupBudgetMiB = 128; private Integer backupBudgetMiB = 128;
// 1.x keys, bound only to report that they moved (never used to connect).
private String host;
private String port;
private String database;
private String username;
private String password;
private String tls;
private String caCertificate;
private String collation; private String collation;
/** The 1.x connection keys still set in {@code database.yml}, in declaration order; empty when none is. */
public List<String> legacyKeys() {
List<String> keys = new ArrayList<>();
add(keys, "host", host);
add(keys, "port", port);
add(keys, "database", database);
add(keys, "username", username);
add(keys, "password", password);
add(keys, "tls", tls);
add(keys, "caCertificate", caCertificate);
add(keys, "collation", collation);
return keys;
}
private static void add(List<String> keys, String key, String value) {
if (value != null && !value.isBlank()) {
keys.add(key);
}
}
public String getProvider() { public String getProvider() {
return provider; return provider;
} }
@@ -36,54 +65,6 @@ public class DatabaseProps {
this.namespace = namespace; this.namespace = namespace;
} }
public String getHost() {
return host;
}
public void setHost(String host) {
this.host = host;
}
public Integer getPort() {
return port;
}
public void setPort(Integer port) {
this.port = port;
}
public String getDatabase() {
return database;
}
public void setDatabase(String database) {
this.database = database;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getTls() {
return tls;
}
public void setTls(String tls) {
this.tls = tls;
}
public String getCaCertificate() {
return caCertificate;
}
public void setCaCertificate(String caCertificate) {
this.caCertificate = caCertificate;
}
public Integer getPoolMax() { public Integer getPoolMax() {
return poolMax; return poolMax;
} }
@@ -108,6 +89,62 @@ public class DatabaseProps {
this.backupBudgetMiB = backupBudgetMiB; this.backupBudgetMiB = backupBudgetMiB;
} }
public String getHost() {
return host;
}
public void setHost(String host) {
this.host = host;
}
public String getPort() {
return port;
}
public void setPort(String port) {
this.port = port;
}
public String getDatabase() {
return database;
}
public void setDatabase(String database) {
this.database = database;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getTls() {
return tls;
}
public void setTls(String tls) {
this.tls = tls;
}
public String getCaCertificate() {
return caCertificate;
}
public void setCaCertificate(String caCertificate) {
this.caCertificate = caCertificate;
}
public String getCollation() { public String getCollation() {
return collation; return collation;
} }
@@ -54,7 +54,7 @@ public final class DatabaseRuntime {
public enum Status { public enum Status {
/** The settings are missing or unusable; fixed by saving the settings and restarting. */ /** The settings are missing or unusable; fixed by saving the settings and restarting. */
NOT_CONFIGURED, NOT_CONFIGURED,
/** The chosen provider plugin is not installed (or two are). */ /** The chosen provider plugin is not installed, two offer the same product, or it predates 2.0.0. */
NO_PROVIDER, NO_PROVIDER,
/** Trying to reach the server. */ /** Trying to reach the server. */
CONNECTING, CONNECTING,
@@ -79,8 +79,7 @@ public final class DatabaseRuntime {
static final Duration UNSUPPORTED_RETRY = Duration.ofMinutes(5); static final Duration UNSUPPORTED_RETRY = Duration.ofMinutes(5);
private static final int LOCK_CONNECTIONS = 4; private static final int LOCK_CONNECTIONS = 4;
private final Supplier<DatabaseConfig> configSource; private final Supplier<ProviderChoice.Chosen> source;
private final Supplier<List<DatabaseProvider>> providers;
private final Path workDir; private final Path workDir;
private final ScheduledExecutorService executor; private final ScheduledExecutorService executor;
private final Semaphore lockConnections = new Semaphore(LOCK_CONNECTIONS, true); private final Semaphore lockConnections = new Semaphore(LOCK_CONNECTIONS, true);
@@ -104,15 +103,13 @@ public final class DatabaseRuntime {
private long backoffMillis = 1000; private long backoffMillis = 1000;
/** /**
* @param configSource builds the checked settings; throws {@link IllegalArgumentException} with a reason * @param source chooses the provider and checks the settings ({@link ProviderChoice#running}); throws
* @param providers the provider beans installed * {@link ProviderChoice.NoProviderException} or {@link IllegalArgumentException} with a reason
* @param workDir the plugin's own folder for the CA file * @param workDir the plugin's own folder for the CA file
* @param executor the plugin's executor * @param executor the plugin's executor
*/ */
public DatabaseRuntime(Supplier<DatabaseConfig> configSource, Supplier<List<DatabaseProvider>> providers, public DatabaseRuntime(Supplier<ProviderChoice.Chosen> source, Path workDir, ScheduledExecutorService executor) {
Path workDir, ScheduledExecutorService executor) { this.source = Objects.requireNonNull(source, "source");
this.configSource = Objects.requireNonNull(configSource, "configSource");
this.providers = Objects.requireNonNull(providers, "providers");
this.workDir = Objects.requireNonNull(workDir, "workDir"); this.workDir = Objects.requireNonNull(workDir, "workDir");
this.executor = Objects.requireNonNull(executor, "executor"); this.executor = Objects.requireNonNull(executor, "executor");
} }
@@ -221,27 +218,25 @@ public final class DatabaseRuntime {
fireAvailable(); fireAvailable();
} }
/** Reads the settings and finds the provider; false (with the status set) when that cannot work. */ /** Chooses the provider and reads its settings; false (with the status set) when that cannot work. */
private boolean prepare() { private boolean prepare() {
DatabaseConfig c; DatabaseConfig c;
DatabaseProvider provider;
try { try {
c = configSource.get(); ProviderChoice.Chosen chosen = source.get();
c = chosen.config();
provider = chosen.provider();
} catch (ProviderChoice.NoProviderException e) {
status = Status.NO_PROVIDER;
detail = e.getMessage();
log.warn("database: {}", detail);
return false;
} catch (IllegalArgumentException e) { } catch (IllegalArgumentException e) {
status = Status.NOT_CONFIGURED; status = Status.NOT_CONFIGURED;
detail = e.getMessage(); detail = e.getMessage();
log.info("database: not configured: {}", e.getMessage()); log.info("database: not configured: {}", e.getMessage());
return false; return false;
} }
List<DatabaseProvider> matching = providers.get().stream().filter(p -> c.provider().equals(p.id())).toList();
if (matching.size() != 1) {
status = Status.NO_PROVIDER;
detail = matching.isEmpty()
? "the provider plugin for '" + c.provider() + "' (database-" + c.provider() + ") is not installed"
: "two provider plugins offer '" + c.provider() + "'; remove one";
log.warn("database: {}", detail);
return false;
}
DatabaseProvider provider = matching.get(0);
Engine e = engineFor(c.provider()); Engine e = engineFor(c.provider());
Path ca; Path ca;
try { try {
@@ -463,6 +463,11 @@ public final class PostgresEngine implements Engine {
return ConnectFailure.TLS; return ConnectFailure.TLS;
} }
String state = failure.getSQLState() == null ? "" : failure.getSQLState(); String state = failure.getSQLState() == null ? "" : failure.getSQLState();
// 08004 also when TLS was asked of a server that has it off: pgjdbc says "The server does not support SSL."
// (translated with the JVM's locale, but "SSL" stays), which is a TLS problem, not a refused password.
if (state.equals("08004") && failure.getMessage() != null && failure.getMessage().contains("SSL")) {
return ConnectFailure.TLS;
}
// 08004: the driver itself refuses, e.g. an empty password when the server asks for one. // 08004: the driver itself refuses, e.g. an empty password when the server asks for one.
if (state.equals("28P01") || state.equals("28000") || state.equals("08004")) { if (state.equals("28P01") || state.equals("28000") || state.equals("08004")) {
return ConnectFailure.AUTHENTICATION; return ConnectFailure.AUTHENTICATION;
@@ -0,0 +1,128 @@
package mx.quest.database.internal;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Locale;
import java.util.Optional;
import java.util.Set;
import mx.quest.database.spi.DatabaseProvider;
import mx.quest.database.spi.ProviderSettings;
/**
* Which provider the database plugin uses, and with which settings. The {@code provider} setting is {@code auto}
* (the default: the one provider plugin installed), {@code postgresql} or {@code mariadb}; the server's settings
* come from the chosen provider plugin (since 2.0.0).
*
* <p>Every problem is refused with a reason an operator can act on, in two kinds: {@link NoProviderException} when a
* plugin must be installed or removed, plain {@link IllegalArgumentException} when a setting must change. Both are
* fixed by a restart, which is what the runtime's status says.
*/
public final class ProviderChoice {
/** The provider setting's value that picks the one installed provider. */
public static final String AUTO = "auto";
/** The provider to use and the checked settings to use it with. */
public record Chosen(DatabaseProvider provider, DatabaseConfig config) {
}
/** A provider plugin is missing, or two offer the same product: install or remove one. */
public static final class NoProviderException extends IllegalArgumentException {
NoProviderException(String message) {
super(message);
}
}
private ProviderChoice() {
}
/**
* The provider the running application uses, with its running settings.
*
* @throws NoProviderException when the chosen provider plugin is not installed, or two are
* @throws IllegalArgumentException when a setting is missing or unusable
*/
public static Chosen running(DatabaseProps props, List<DatabaseProvider> installed) {
DatabaseProvider provider = pick(props.getProvider(), installed);
String plugin = plugin(provider.id());
ProviderSettings server = provider.runningSettings().orElseThrow(() -> tooOld(plugin));
if (server.isEmpty()) {
List<String> moved = props.legacyKeys();
if (!moved.isEmpty()) {
throw new IllegalArgumentException("the server settings moved to the " + plugin + " plugin in "
+ "database 2.0.0: move " + String.join(", ", moved) + " from plugin-settings/database.yml "
+ "to plugin-settings/" + plugin + ".yml (or enter them on that plugin's settings page)");
}
throw new IllegalArgumentException("no server is set: enter it on the " + plugin
+ " plugin's settings page");
}
return new Chosen(provider, check(props, provider, server));
}
/**
* One installed provider with the settings saved for it now, for the connection test.
*
* @throws IllegalArgumentException when the saved settings are missing or unusable
*/
public static Chosen saved(DatabaseProps props, DatabaseProvider provider) {
String plugin = plugin(provider.id());
ProviderSettings server = provider.savedSettings().orElseThrow(() -> tooOld(plugin));
if (server.isEmpty()) {
throw new IllegalArgumentException("no server is saved in the " + plugin + " plugin's settings");
}
return new Chosen(provider, check(props, provider, server));
}
/** The installed providers of products this plugin has SQL for, in the order found. */
public static List<DatabaseProvider> supported(List<DatabaseProvider> installed) {
return installed.stream().filter(p -> DatabaseConfig.PROVIDERS.contains(p.id())).toList();
}
/** The provider plugin's id for a product: {@code database-postgresql}, {@code database-mariadb}. */
public static String plugin(String product) {
return "database-" + product;
}
private static DatabaseProvider pick(String setting, List<DatabaseProvider> installed) {
String choice = Optional.ofNullable(DatabaseConfig.trimToNull(setting)).orElse(AUTO).toLowerCase(Locale.ROOT);
if (!choice.equals(AUTO) && !DatabaseConfig.PROVIDERS.contains(choice)) {
throw new IllegalArgumentException("unknown provider: " + choice + " (auto, postgresql or mariadb)");
}
List<DatabaseProvider> candidates = supported(installed);
if (choice.equals(AUTO)) {
Set<String> products = new LinkedHashSet<>(candidates.stream().map(DatabaseProvider::id).toList());
if (products.isEmpty()) {
throw new NoProviderException("no provider plugin is installed: install database-postgresql or "
+ "database-mariadb");
}
if (products.size() > 1) {
throw new IllegalArgumentException("both provider plugins are installed: choose one in the provider "
+ "setting");
}
choice = products.iterator().next();
}
String product = choice;
List<DatabaseProvider> matching = candidates.stream().filter(p -> p.id().equals(product)).toList();
if (matching.isEmpty()) {
throw new NoProviderException("the provider plugin for '" + product + "' (" + plugin(product)
+ ") is not installed");
}
if (matching.size() > 1) {
throw new NoProviderException("two provider plugins offer '" + product + "'; remove one");
}
return matching.get(0);
}
private static DatabaseConfig check(DatabaseProps props, DatabaseProvider provider, ProviderSettings server) {
try {
return DatabaseConfig.from(props, provider.id(), server);
} catch (IllegalArgumentException e) {
throw new IllegalArgumentException(plugin(provider.id()) + " settings: " + e.getMessage());
}
}
private static IllegalArgumentException tooOld(String plugin) {
return new NoProviderException("the " + plugin + " plugin is older than 2.0.0 and holds no server settings: "
+ "install " + plugin + " 2.0.0");
}
}
@@ -1,10 +1,19 @@
package mx.quest.database.spi; package mx.quest.database.spi;
import java.util.Optional;
import javax.sql.DataSource; import javax.sql.DataSource;
/** /**
* A database product, contributed by a provider plugin that ships the product's JDBC driver in its {@code lib/}. * A database product, contributed by a provider plugin that ships the product's JDBC driver in its {@code lib/}.
* The operator picks one by its {@link #id()} in the database plugin's {@code provider} setting. * When both providers are installed, the operator picks one by its {@link #id()} in the database plugin's
* {@code provider} setting; with one installed, that one is used.
*
* <p><b>The provider holds its server's settings</b> (since database 2.0.0): host, port, database, account,
* password and TLS are set on the provider plugin's own settings page, and handed over through
* {@link #runningSettings()} and {@link #savedSettings()}. The database plugin keeps only what applies to every
* product: the provider choice, the namespace and the limits. Those two methods hand over the password in clear and
* are for the database plugin alone; a consumer plugin never calls them. They are not a security boundary: plugins
* are trusted code in the same JVM, as the kernel's plugin guide says, and could read the settings file anyway.
* *
* <p><b>A provider brings the driver, not the SQL.</b> Every statement Runway runs on the provider's connections — * <p><b>A provider brings the driver, not the SQL.</b> Every statement Runway runs on the provider's connections —
* schema creation and removal, locks, the ownership checks, migrations, backup and restore — is written in the * schema creation and removal, locks, the ownership checks, migrations, backup and restore — is written in the
@@ -42,4 +51,29 @@ public interface DatabaseProvider {
* @return a new, unpooled data source * @return a new, unpooled data source
*/ */
DataSource dataSource(ConnectionSettings settings); DataSource dataSource(ConnectionSettings settings);
/**
* The server settings the running application started with: what the database plugin connects with. Read from
* the provider plugin's own app-level settings, the password in clear
* ({@code PluginSettings.appSecret("password")}).
*
* @return the settings; empty only from a provider built before database 2.0.0, which the database plugin
* reports as too old
* @since database 2.0.0
*/
default Optional<ProviderSettings> runningSettings() {
return Optional.empty();
}
/**
* The server settings as saved now, which the next restart applies ({@code PluginSettings.savedApp}): what the
* connection test on the database plugin's settings page tries, so an operator can check a change before
* restarting.
*
* @return the settings; empty only from a provider built before database 2.0.0
* @since database 2.0.0
*/
default Optional<ProviderSettings> savedSettings() {
return Optional.empty();
}
} }
@@ -0,0 +1,71 @@
package mx.quest.database.spi;
import java.util.Optional;
import java.util.function.Function;
/**
* Where a provider's server is and how to reach it, as the operator set it on the provider plugin's own settings page
* (since database 2.0.0). Raw values: the database plugin checks every one of them before use and reports the first
* it cannot use, so a provider passes them on unchanged and never validates or repairs them itself.
*
* <p>A provider reads these from its own app-level settings, declared under the same keys as the components below.
* {@link #read(Function)} does that from one lookup, so both providers read their settings the same way.
*
* @param host the server's host name or address
* @param port the port, or blank for the product's default
* @param database the database to connect to
* @param username the account
* @param password the account's password in clear, possibly blank; never logged ({@link #toString()} leaves it
* out)
* @param tls {@code verify-full}, {@code require} or {@code disable}; blank for {@code verify-full}
* @param caCertificate a PEM certificate to verify the server against, or blank for the JVM's trust store
* @param collation MariaDB's collation for consumer tables, or blank for the server's best; always blank for a
* product without the setting
*/
public record ProviderSettings(String host, String port, String database, String username, String password,
String tls, String caCertificate, String collation) {
/** The setting keys, as both providers declare them in their {@code plugin.yml}. */
public static final String HOST = "host";
public static final String PORT = "port";
public static final String DATABASE = "database";
public static final String USERNAME = "username";
public static final String PASSWORD = "password";
public static final String TLS = "tls";
public static final String CA_CERTIFICATE = "caCertificate";
public static final String COLLATION = "collation";
/**
* Reads every key through one lookup, a blank or missing value becoming {@code null}.
*
* @param setting answers a setting key with its value; for {@link #PASSWORD} the value in clear
* @return the settings
*/
public static ProviderSettings read(Function<String, Optional<String>> setting) {
return new ProviderSettings(value(setting, HOST), value(setting, PORT), value(setting, DATABASE),
value(setting, USERNAME), value(setting, PASSWORD), value(setting, TLS),
value(setting, CA_CERTIFICATE), value(setting, COLLATION));
}
/** Whether nothing that names a server is set: the provider has not been set up yet. */
public boolean isEmpty() {
return blank(host) && blank(database) && blank(username);
}
/** Everything but the password. */
@Override
public String toString() {
return "ProviderSettings[host=" + host + ", port=" + port + ", database=" + database + ", username="
+ username + ", tls=" + tls + ", caCertificate=" + (blank(caCertificate) ? "none" : "set")
+ ", collation=" + collation + "]";
}
private static String value(Function<String, Optional<String>> setting, String key) {
Optional<String> v = setting.apply(key);
return v == null ? null : v.filter(s -> !s.isBlank()).orElse(null);
}
private static boolean blank(String s) {
return s == null || s.isBlank();
}
}
@@ -0,0 +1,99 @@
package mx.quest.database.spi;
import java.util.Optional;
/**
* A provider's server settings as Spring binds them from the running application: register one as a bean with
* {@code @ConfigurationProperties("runway.plugin.<provider-id>")} and turn it into {@link ProviderSettings} with
* {@link #toSettings(Optional)}, passing the password from {@code PluginSettings.appSecret("password")} (it binds here
* only in its stored {@code ENC(...)} form, so it has no field). Both providers bind this way, so the keys can never
* differ from the ones {@link ProviderSettings} names.
*
* @since database 2.0.0
*/
public class ProviderSettingsProps {
private String host;
private String port;
private String database;
private String username;
private String tls;
private String caCertificate;
private String collation;
/**
* The bound values with the given password.
*
* @param password the password in clear, or empty
* @return the settings, a blank value as {@code null}
*/
public ProviderSettings toSettings(Optional<String> password) {
return ProviderSettings.read(key -> Optional.ofNullable(switch (key) {
case ProviderSettings.HOST -> host;
case ProviderSettings.PORT -> port;
case ProviderSettings.DATABASE -> database;
case ProviderSettings.USERNAME -> username;
case ProviderSettings.TLS -> tls;
case ProviderSettings.CA_CERTIFICATE -> caCertificate;
case ProviderSettings.COLLATION -> collation;
case ProviderSettings.PASSWORD -> password == null ? null : password.orElse(null);
default -> null;
}));
}
public String getHost() {
return host;
}
public void setHost(String host) {
this.host = host;
}
public String getPort() {
return port;
}
public void setPort(String port) {
this.port = port;
}
public String getDatabase() {
return database;
}
public void setDatabase(String database) {
this.database = database;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getTls() {
return tls;
}
public void setTls(String tls) {
this.tls = tls;
}
public String getCaCertificate() {
return caCertificate;
}
public void setCaCertificate(String caCertificate) {
this.caCertificate = caCertificate;
}
public String getCollation() {
return collation;
}
public void setCollation(String collation) {
this.collation = collation;
}
}
@@ -18,8 +18,11 @@
* *
* <h2>For a provider</h2> * <h2>For a provider</h2>
* Implement {@link mx.quest.database.spi.DatabaseProvider} in a plugin that {@code requires: database} and ships its * Implement {@link mx.quest.database.spi.DatabaseProvider} in a plugin that {@code requires: database} and ships its
* driver in {@code lib/}. The operator picks the provider by its {@link mx.quest.database.spi.DatabaseProvider#id()} * driver in {@code lib/}. The provider declares its server's settings (the keys in
* in the database plugin's settings. * {@link mx.quest.database.spi.ProviderSettings}) in its own {@code plugin.yml} and hands them over through
* {@link mx.quest.database.spi.DatabaseProvider#runningSettings()} and
* {@link mx.quest.database.spi.DatabaseProvider#savedSettings()}. With both providers installed, the operator picks
* one by its {@link mx.quest.database.spi.DatabaseProvider#id()} in the database plugin's settings.
* *
* <h2>Stability</h2> * <h2>Stability</h2>
* This package evolves additively within a major version of the database plugin: interfaces gain {@code default} * This package evolves additively within a major version of the database plugin: interfaces gain {@code default}
@@ -9,6 +9,7 @@ import java.nio.file.Path;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Optional;
import java.util.concurrent.CountDownLatch; import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference; import java.util.concurrent.atomic.AtomicReference;
@@ -21,6 +22,7 @@ import mx.quest.database.internal.DatabaseLifecycle;
import mx.quest.database.internal.DatabaseRuntime; import mx.quest.database.internal.DatabaseRuntime;
import mx.quest.database.spi.ConnectionSettings; import mx.quest.database.spi.ConnectionSettings;
import mx.quest.database.spi.DatabaseProvider; import mx.quest.database.spi.DatabaseProvider;
import mx.quest.database.spi.ProviderSettings;
import mx.quest.database.spi.Databases; import mx.quest.database.spi.Databases;
import mx.quest.runway.spi.BackupParticipant; import mx.quest.runway.spi.BackupParticipant;
import mx.quest.runway.spi.model.PluginInfo; import mx.quest.runway.spi.model.PluginInfo;
@@ -66,6 +68,11 @@ class DatabasePluginConfigTest {
touched.set(true); touched.set(true);
throw new IllegalStateException("must not be asked while starting"); throw new IllegalStateException("must not be asked while starting");
} }
@Override
public Optional<ProviderSettings> runningSettings() {
return Optional.of(ProviderSettings.read(key -> Optional.empty())); // installed, not set up
}
}); });
ctx.register(DatabasePluginConfig.class); ctx.register(DatabasePluginConfig.class);
ctx.refresh(); ctx.refresh();
@@ -107,10 +114,8 @@ class DatabasePluginConfigTest {
String startThread = Thread.currentThread().getName(); String startThread = Thread.currentThread().getName();
try (AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext()) { try (AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext()) {
ctx.getEnvironment().getPropertySources().addFirst(new MapPropertySource("test", Map.of( ctx.getEnvironment().getPropertySources().addFirst(new MapPropertySource("test", Map.of(
"runway.plugin.database.provider", "postgresql", "runway.plugin.database.host", "127.0.0.1", "runway.plugin.database.provider", "postgresql")));
"runway.plugin.database.port", "1", "runway.plugin.database.database", "runway", ctx.registerBean(PluginSettings.class, FakePluginSettings::new);
"runway.plugin.database.username", "runway", "runway.plugin.database.tls", "disable")));
ctx.registerBean(PluginSettings.class, () -> new FakePluginSettings().appSecret("password", "x"));
ctx.registerBean(PluginSiteFiles.class, () -> new TempDirSiteFiles(dir.resolve("sites"), "database")); ctx.registerBean(PluginSiteFiles.class, () -> new TempDirSiteFiles(dir.resolve("sites"), "database"));
ctx.registerBean(PluginInfo.class, () -> new PluginInfo("database", "1.0.0", dir.resolve("plugin"))); ctx.registerBean(PluginInfo.class, () -> new PluginInfo("database", "1.0.0", dir.resolve("plugin")));
ctx.registerBean(FakeSiteServices.class, FakeSiteServices::new); ctx.registerBean(FakeSiteServices.class, FakeSiteServices::new);
@@ -135,6 +140,12 @@ class DatabasePluginConfigTest {
} }
throw new IllegalStateException("no server here"); throw new IllegalStateException("no server here");
} }
@Override
public Optional<ProviderSettings> runningSettings() {
return Optional.of(new ProviderSettings("127.0.0.1", "1", "runway", "runway", "x", "disable", null,
null));
}
}); });
ctx.register(Binding.class, DatabasePluginConfig.class); ctx.register(Binding.class, DatabasePluginConfig.class);
long t0 = System.nanoTime(); long t0 = System.nanoTime();
@@ -158,6 +169,58 @@ class DatabasePluginConfigTest {
} }
} }
@Test
void oneXServerKeysLeftInTheDatabaseSettingsAreReportedAsMovedAndNeverUsed() throws Exception {
AtomicBoolean touched = new AtomicBoolean();
try (AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext()) {
// A 1.x database.yml after the upgrade: the server keys are still there, the provider page is empty.
ctx.getEnvironment().getPropertySources().addFirst(new MapPropertySource("test", Map.of(
"runway.plugin.database.provider", "postgresql", "runway.plugin.database.host", "127.0.0.1",
"runway.plugin.database.database", "runway", "runway.plugin.database.username", "runway",
"runway.plugin.database.password", "ENC(c2VjcmV0)", "runway.plugin.database.tls", "disable")));
ctx.registerBean(PluginSettings.class, FakePluginSettings::new);
ctx.registerBean(PluginSiteFiles.class, () -> new TempDirSiteFiles(dir.resolve("sites"), "database"));
ctx.registerBean(PluginInfo.class, () -> new PluginInfo("database", "2.0.0", dir.resolve("plugin")));
ctx.registerBean(FakeSiteServices.class, FakeSiteServices::new);
ctx.registerBean("otherPluginProvider", DatabaseProvider.class, () -> new DatabaseProvider() {
@Override
public String id() {
return "postgresql";
}
@Override
public String driverVersion() {
return "none";
}
@Override
public DataSource dataSource(ConnectionSettings settings) {
touched.set(true);
throw new IllegalStateException("must not connect with 1.x keys");
}
@Override
public Optional<ProviderSettings> runningSettings() {
return Optional.of(ProviderSettings.read(key -> Optional.empty()));
}
});
ctx.register(Binding.class, DatabasePluginConfig.class);
ctx.refresh();
ctx.getBean(DatabaseLifecycle.class).started(ctx.getBean(PluginInfo.class));
DatabaseRuntime runtime = ctx.getBean(DatabaseRuntime.class);
long deadline = System.nanoTime() + 5_000_000_000L;
while (runtime.status() == DatabaseRuntime.Status.CONNECTING && System.nanoTime() < deadline) {
Thread.sleep(20);
}
assertThat(runtime.status()).isEqualTo(DatabaseRuntime.Status.NOT_CONFIGURED);
assertThat(runtime.health().detail()).contains("moved to the database-postgresql plugin")
.contains("host, database, username, password, tls")
.contains("plugin-settings/database-postgresql.yml").doesNotContain("c2VjcmV0");
assertThat(touched).isFalse();
ctx.getBean(DatabaseLifecycle.class).stopping();
}
}
@Test @Test
void theCompiledClassesLinkNoHostInternals() throws IOException { void theCompiledClassesLinkNoHostInternals() throws IOException {
Path classes = Path.of("target", "classes"); Path classes = Path.of("target", "classes");
@@ -3,29 +3,34 @@ package mx.quest.database.internal;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.Assertions.assertThatThrownBy;
import java.util.Optional;
import mx.quest.database.spi.ConnectionSettings.Tls; import mx.quest.database.spi.ConnectionSettings.Tls;
import mx.quest.database.spi.ProviderSettings;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
class DatabaseConfigTest { class DatabaseConfigTest {
static DatabaseProps props() { static ProviderSettings server() {
DatabaseProps p = new DatabaseProps(); return server("db.example.com", null, null);
p.setProvider("postgresql"); }
p.setHost("db.example.com");
p.setDatabase("runway"); static ProviderSettings server(String host, String port, String tls) {
p.setUsername("runway"); return new ProviderSettings(host, port, "runway", "runway", "s3cret", tls, null, null);
return p; }
static ProviderSettings with(ProviderSettings s, String database, String ca, String collation) {
return new ProviderSettings(s.host(), s.port(), database, s.username(), s.password(), s.tls(), ca, collation);
} }
@Test @Test
void aCompleteSetOfSettingsIsCheckedWithSafeDefaults() { void aCompleteSetOfSettingsIsCheckedWithSafeDefaults() {
DatabaseConfig c = DatabaseConfig.from(props(), Optional.of("s3cret")); DatabaseConfig c = DatabaseConfig.from(new DatabaseProps(), "postgresql", server());
assertThat(c.tls()).isEqualTo(Tls.VERIFY_FULL); assertThat(c.tls()).isEqualTo(Tls.VERIFY_FULL);
assertThat(c.namespace()).isEqualTo("rw"); assertThat(c.namespace()).isEqualTo("rw");
assertThat(c.port()).isZero(); assertThat(c.port()).isZero();
assertThat(c.poolMax()).isEqualTo(10); assertThat(c.poolMax()).isEqualTo(10);
assertThat(c.password()).isEqualTo("s3cret");
assertThat(c.toString()).doesNotContain("s3cret"); assertThat(c.toString()).doesNotContain("s3cret");
assertThat(server().toString()).doesNotContain("s3cret");
} }
@Test @Test
@@ -33,44 +38,47 @@ class DatabaseConfigTest {
for (String bad : new String[] {"a,b", "h?ssl=false", "h/db", "u@h", "h:1:2:3", "address=(host=x)", "h h", for (String bad : new String[] {"a,b", "h?ssl=false", "h/db", "u@h", "h:1:2:3", "address=(host=x)", "h h",
"h;x", "-h", "h-.com", "1.2.3.256", "999.1.1.1", "[::1]x", "fe80::1%eth0", "a..b", "h.", "h;x", "-h", "h-.com", "1.2.3.256", "999.1.1.1", "[::1]x", "fe80::1%eth0", "a..b", "h.",
"::1::2"}) { "::1::2"}) {
DatabaseProps p = props(); assertThatThrownBy(() -> DatabaseConfig.from(new DatabaseProps(), "postgresql", server(bad, null, null)))
p.setHost(bad); .as(bad).isInstanceOf(IllegalArgumentException.class);
assertThatThrownBy(() -> DatabaseConfig.from(p, Optional.empty())).as(bad)
.isInstanceOf(IllegalArgumentException.class);
} }
for (String good : new String[] {"localhost", "db-1.internal", "10.0.0.5", "::1", "[2001:db8::1]", for (String good : new String[] {"localhost", "db-1.internal", "10.0.0.5", "::1", "[2001:db8::1]",
"2001:db8:0:0:0:0:0:1", "::ffff:10.0.0.1"}) { "2001:db8:0:0:0:0:0:1", "::ffff:10.0.0.1"}) {
DatabaseProps p = props(); assertThat(DatabaseConfig.from(new DatabaseProps(), "postgresql", server(good, null, null)).host())
p.setHost(good); .as(good).doesNotContain("[");
assertThat(DatabaseConfig.from(p, Optional.empty()).host()).as(good).doesNotContain("["); }
}
@Test
void thePortIsBlankForTheDefaultOrANumberInRange() {
DatabaseProps p = new DatabaseProps();
assertThat(DatabaseConfig.from(p, "mariadb", server("h", " ", null)).port()).isZero();
assertThat(DatabaseConfig.from(p, "mariadb", server("h", "3307", null)).port()).isEqualTo(3307);
for (String bad : new String[] {"0", "65536", "-1", "33o6", "3306;x"}) {
assertThatThrownBy(() -> DatabaseConfig.from(p, "mariadb", server("h", bad, null))).as(bad)
.hasMessageContaining("port");
} }
} }
@Test @Test
void theOtherFieldsAreCheckedToo() { void theOtherFieldsAreCheckedToo() {
DatabaseProps p = props(); DatabaseProps p = new DatabaseProps();
p.setDatabase("run way"); assertThatThrownBy(() -> DatabaseConfig.from(p, "postgresql", with(server(), "run way", null, null)))
assertThatThrownBy(() -> DatabaseConfig.from(p, Optional.empty())).hasMessageContaining("database name"); .hasMessageContaining("database name");
DatabaseProps q = props(); assertThatThrownBy(() -> DatabaseConfig.from(p, "postgresql", server("h", null, "prefer")))
q.setTls("prefer"); .hasMessageContaining("tls");
assertThatThrownBy(() -> DatabaseConfig.from(q, Optional.empty())).hasMessageContaining("tls"); assertThatThrownBy(() -> DatabaseConfig.from(p, "mysql", server())).hasMessageContaining("unknown provider");
DatabaseProps r = props(); assertThatThrownBy(() -> DatabaseConfig.from(p, " ", server())).hasMessageContaining("no provider");
r.setProvider("mysql"); assertThatThrownBy(() -> DatabaseConfig.from(p, "postgresql", with(server(), "runway", "not a certificate",
assertThatThrownBy(() -> DatabaseConfig.from(r, Optional.empty())).hasMessageContaining("unknown provider"); null))).hasMessageContaining("PEM");
DatabaseProps s = props(); assertThatThrownBy(() -> DatabaseConfig.from(p, "mariadb", with(server(), "runway", null, "utf8mb4; DROP")))
s.setCaCertificate("not a certificate"); .hasMessageContaining("collation");
assertThatThrownBy(() -> DatabaseConfig.from(s, Optional.empty())).hasMessageContaining("PEM"); assertThatThrownBy(() -> DatabaseConfig.from(p, "postgresql", new ProviderSettings("h", null, "runway",
DatabaseProps t = props(); null, null, null, null, null))).hasMessageContaining("username");
t.setCollation("utf8mb4; DROP"); DatabaseProps u = new DatabaseProps();
assertThatThrownBy(() -> DatabaseConfig.from(t, Optional.empty())).hasMessageContaining("collation");
DatabaseProps u = props();
u.setPoolMax(100000); u.setPoolMax(100000);
u.setStatementTimeoutSeconds(0); u.setStatementTimeoutSeconds(0);
DatabaseConfig c = DatabaseConfig.from(u, Optional.empty()); DatabaseConfig c = DatabaseConfig.from(u, "postgresql", server());
assertThat(c.poolMax()).isEqualTo(DatabaseConfig.POOL_MAX); assertThat(c.poolMax()).isEqualTo(DatabaseConfig.POOL_MAX);
assertThat(c.statementTimeout().toSeconds()).isEqualTo(DatabaseConfig.TIMEOUT_MIN_S); assertThat(c.statementTimeout().toSeconds()).isEqualTo(DatabaseConfig.TIMEOUT_MIN_S);
DatabaseProps v = props();
v.setProvider(null);
assertThatThrownBy(() -> DatabaseConfig.from(v, Optional.empty())).hasMessageContaining("no provider");
} }
} }
@@ -18,6 +18,7 @@ import java.util.Locale;
import java.util.Map; import java.util.Map;
import java.util.Optional; import java.util.Optional;
import java.util.Set; import java.util.Set;
import java.util.function.Supplier;
import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.Executors; import java.util.concurrent.Executors;
@@ -26,6 +27,7 @@ import javax.sql.DataSource;
import mx.quest.database.spi.ConnectionSettings; import mx.quest.database.spi.ConnectionSettings;
import mx.quest.database.spi.DatabaseConsumer; import mx.quest.database.spi.DatabaseConsumer;
import mx.quest.database.spi.DatabaseProvider; import mx.quest.database.spi.DatabaseProvider;
import mx.quest.database.spi.ProviderSettings;
import mx.quest.database.spi.PluginDatabase; import mx.quest.database.spi.PluginDatabase;
import mx.quest.database.spi.Scope; import mx.quest.database.spi.Scope;
import mx.quest.runway.spi.model.BackupReader; import mx.quest.runway.spi.model.BackupReader;
@@ -69,7 +71,23 @@ final class Harness implements AutoCloseable {
/** The provider the provider plugins will be: their own DataSource, pinned properties, no DriverManager. */ /** The provider the provider plugins will be: their own DataSource, pinned properties, no DriverManager. */
static DatabaseProvider provider(String engine) { static DatabaseProvider provider(String engine) {
return provider(engine, () -> null, () -> null);
}
/** A provider whose running and saved settings come from the suppliers ({@code null}: none, as before 2.0.0). */
static DatabaseProvider provider(String engine, Supplier<ProviderSettings> running,
Supplier<ProviderSettings> saved) {
return new DatabaseProvider() { return new DatabaseProvider() {
@Override
public Optional<ProviderSettings> runningSettings() {
return Optional.ofNullable(running.get());
}
@Override
public Optional<ProviderSettings> savedSettings() {
return Optional.ofNullable(saved.get());
}
@Override @Override
public String id() { public String id() {
return engine; return engine;
@@ -179,7 +197,13 @@ final class Harness implements AutoCloseable {
final DatabaseCore core; final DatabaseCore core;
final DatabasesImpl databases; final DatabasesImpl databases;
final DatabaseBackup backup; final DatabaseBackup backup;
// The provider's running server settings, as its settings page would hold them; tests change them freely.
volatile String host;
volatile String port;
volatile String username;
volatile String password; volatile String password;
/** What the provider's settings page has saved now (the connection test's input); the running ones if null. */
volatile ProviderSettings saved;
Harness(String engine, String namespace, Endpoint endpoint, Path work) throws IOException { Harness(String engine, String namespace, Endpoint endpoint, Path work) throws IOException {
this(engine, namespace, endpoint, work, new FakeSites(work.resolve("sites"))); this(engine, namespace, endpoint, work, new FakeSites(work.resolve("sites")));
@@ -196,15 +220,13 @@ final class Harness implements AutoCloseable {
this.files = new TempDirSiteFiles(sites.root, "database"); this.files = new TempDirSiteFiles(sites.root, "database");
props.setProvider(engine); props.setProvider(engine);
props.setNamespace(namespace); props.setNamespace(namespace);
props.setHost(endpoint.host()); host = endpoint.host();
props.setPort(endpoint.port()); port = String.valueOf(endpoint.port());
props.setDatabase(DATABASE); username = USER;
props.setUsername(USER);
props.setTls("disable");
password = endpoint.password(); password = endpoint.password();
providers.add(provider(engine)); providers.add(provider(engine, this::running, () -> saved != null ? saved : running()));
runtime = new DatabaseRuntime(() -> DatabaseConfig.from(props, Optional.ofNullable(password)), runtime = new DatabaseRuntime(() -> ProviderChoice.running(props, List.copyOf(providers)),
() -> List.copyOf(providers), work.resolve("run-" + System.nanoTime()), executor); work.resolve("run-" + System.nanoTime()), executor);
schemas = new SiteSchemas(runtime, files, sites); schemas = new SiteSchemas(runtime, files, sites);
migrator = new Migrator(runtime); migrator = new Migrator(runtime);
core = new DatabaseCore(runtime, schemas, migrator, sites, sites); core = new DatabaseCore(runtime, schemas, migrator, sites, sites);
@@ -219,6 +241,11 @@ final class Harness implements AutoCloseable {
migrator.parked(backup); migrator.parked(backup);
} }
/** The running server settings from the fields above, TLS off as the test servers run. */
ProviderSettings running() {
return new ProviderSettings(host, port, DATABASE, username, password, "disable", null, null);
}
Harness start() throws InterruptedException { Harness start() throws InterruptedException {
runtime.start(); runtime.start();
long deadline = System.nanoTime() + Duration.ofSeconds(30).toNanos(); long deadline = System.nanoTime() + Duration.ofSeconds(30).toNanos();
@@ -252,8 +279,10 @@ final class Harness implements AutoCloseable {
/** A raw connection as the test account, outside every pool. */ /** A raw connection as the test account, outside every pool. */
Connection raw() throws SQLException { Connection raw() throws SQLException {
return provider(engine).dataSource(DatabaseRuntime.settings(DatabaseConfig.from(props, ProviderSettings test = new ProviderSettings(endpoint.host(), String.valueOf(endpoint.port()), DATABASE, USER,
Optional.of(endpoint.password())), null, Duration.ofSeconds(30))).getConnection(); endpoint.password(), "disable", null, null);
return provider(engine).dataSource(DatabaseRuntime.settings(DatabaseConfig.from(props, engine, test), null,
Duration.ofSeconds(30))).getConnection();
} }
List<String> schemasInNamespace() throws SQLException { List<String> schemasInNamespace() throws SQLException {
@@ -0,0 +1,32 @@
package mx.quest.database.internal;
import static org.assertj.core.api.Assertions.assertThat;
import java.sql.SQLException;
import org.junit.jupiter.api.Test;
/** {@link PostgresEngine#classify}: what an operator is told when a connection fails. */
class PostgresEngineTest {
private final PostgresEngine engine = new PostgresEngine();
@Test
void tlsAskedOfAServerWithoutItIsATlsProblemNotARefusedPassword() {
assertThat(engine.classify(new SQLException("The server does not support SSL.", "08004")))
.isEqualTo(Engine.ConnectFailure.TLS);
assertThat(engine.classify(new SQLException("El servidor no soporta SSL.", "08004")))
.as("pgjdbc translates the message; SSL stays").isEqualTo(Engine.ConnectFailure.TLS);
}
@Test
void theOtherRefusalsKeepTheirMeaning() {
assertThat(engine.classify(new SQLException("The server requested password-based authentication, but no "
+ "password was provided.", "08004"))).isEqualTo(Engine.ConnectFailure.AUTHENTICATION);
assertThat(engine.classify(new SQLException("password authentication failed", "28P01")))
.isEqualTo(Engine.ConnectFailure.AUTHENTICATION);
assertThat(engine.classify(new SQLException("database \"x\" does not exist", "3D000")))
.isEqualTo(Engine.ConnectFailure.DATABASE_MISSING);
assertThat(engine.classify(new SQLException("Connection refused", "08001")))
.isEqualTo(Engine.ConnectFailure.UNREACHABLE);
}
}
@@ -0,0 +1,146 @@
package mx.quest.database.internal;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import java.util.List;
import java.util.Optional;
import javax.sql.DataSource;
import mx.quest.database.spi.ConnectionSettings;
import mx.quest.database.spi.DatabaseProvider;
import mx.quest.database.spi.ProviderSettings;
import org.junit.jupiter.api.Test;
/** {@link ProviderChoice}: which provider is used, whose settings, and the reason for every refusal. */
class ProviderChoiceTest {
private static final ProviderSettings RUNNING = new ProviderSettings("db.running", null, "runway", "runway",
"running-secret", "disable", null, null);
private static final ProviderSettings SAVED = new ProviderSettings("db.saved", "5433", "runway", "runway",
"saved-secret", "require", null, null);
private static final ProviderSettings EMPTY = ProviderSettings.read(key -> Optional.empty());
/** A 2.0.0 provider whose running and saved settings are given; {@code null} for one built before 2.0.0. */
static DatabaseProvider provider(String id, ProviderSettings running, ProviderSettings saved) {
return new DatabaseProvider() {
@Override
public String id() {
return id;
}
@Override
public String driverVersion() {
return "test";
}
@Override
public DataSource dataSource(ConnectionSettings settings) {
throw new UnsupportedOperationException();
}
@Override
public Optional<ProviderSettings> runningSettings() {
return Optional.ofNullable(running);
}
@Override
public Optional<ProviderSettings> savedSettings() {
return Optional.ofNullable(saved);
}
};
}
private static DatabaseProps choosing(String provider) {
DatabaseProps p = new DatabaseProps();
p.setProvider(provider);
return p;
}
@Test
void autoUsesTheOneInstalledProviderWithItsRunningSettings() {
DatabaseProvider pg = provider("postgresql", RUNNING, SAVED);
ProviderChoice.Chosen chosen = ProviderChoice.running(new DatabaseProps(), List.of(pg));
assertThat(chosen.provider()).isSameAs(pg);
assertThat(chosen.config().provider()).isEqualTo("postgresql");
assertThat(chosen.config().host()).isEqualTo("db.running");
assertThat(chosen.config().password()).isEqualTo("running-secret");
assertThat(ProviderChoice.running(choosing(" "), List.of(pg)).provider()).as("blank is auto").isSameAs(pg);
assertThat(ProviderChoice.running(choosing("AUTO"), List.of(provider("mariadb", RUNNING, null)))
.config().provider()).isEqualTo("mariadb");
}
@Test
void withBothInstalledAutoAsksForAChoiceAndANamedProductIsUsed() {
DatabaseProvider pg = provider("postgresql", RUNNING, null);
DatabaseProvider maria = provider("mariadb", RUNNING, null);
assertThatThrownBy(() -> ProviderChoice.running(new DatabaseProps(), List.of(pg, maria)))
.isNotInstanceOf(ProviderChoice.NoProviderException.class)
.hasMessageContaining("both provider plugins are installed");
assertThat(ProviderChoice.running(choosing("mariadb"), List.of(pg, maria)).provider()).isSameAs(maria);
assertThat(ProviderChoice.running(choosing("PostgreSQL"), List.of(pg, maria)).provider()).isSameAs(pg);
}
@Test
void aMissingOrDuplicatedProviderIsANoProviderProblem() {
assertThatThrownBy(() -> ProviderChoice.running(new DatabaseProps(), List.of()))
.isInstanceOf(ProviderChoice.NoProviderException.class).hasMessageContaining("no provider plugin");
assertThatThrownBy(() -> ProviderChoice.running(choosing("mariadb"),
List.of(provider("postgresql", RUNNING, null))))
.isInstanceOf(ProviderChoice.NoProviderException.class).hasMessageContaining("database-mariadb");
assertThatThrownBy(() -> ProviderChoice.running(new DatabaseProps(),
List.of(provider("postgresql", RUNNING, null), provider("postgresql", RUNNING, null))))
.isInstanceOf(ProviderChoice.NoProviderException.class).hasMessageContaining("remove one");
assertThatThrownBy(() -> ProviderChoice.running(new DatabaseProps(),
List.of(provider("oracle", RUNNING, null))))
.as("a product without SQL here counts as none").isInstanceOf(ProviderChoice.NoProviderException.class);
assertThatThrownBy(() -> ProviderChoice.running(choosing("mysql"), List.of(provider("postgresql", RUNNING,
null)))).isNotInstanceOf(ProviderChoice.NoProviderException.class)
.hasMessageContaining("unknown provider");
}
@Test
void aProviderBuiltBeforeTwoIsReportedAsTooOld() {
assertThatThrownBy(() -> ProviderChoice.running(new DatabaseProps(), List.of(provider("postgresql", null,
null)))).isInstanceOf(ProviderChoice.NoProviderException.class)
.hasMessageContaining("older than 2.0.0").hasMessageContaining("database-postgresql");
}
@Test
void anUnsetServerSaysWhereToSetItAndOneXKeysAreReportedAsMoved() {
DatabaseProvider pg = provider("postgresql", EMPTY, null);
assertThatThrownBy(() -> ProviderChoice.running(new DatabaseProps(), List.of(pg)))
.hasMessageContaining("no server is set").hasMessageContaining("database-postgresql");
DatabaseProps old = new DatabaseProps();
old.setHost("db.example");
old.setUsername("runway");
old.setPassword("ENC(abc)");
assertThatThrownBy(() -> ProviderChoice.running(old, List.of(pg)))
.hasMessageContaining("moved to the database-postgresql plugin")
.hasMessageContaining("host, username, password")
.hasMessageContaining("plugin-settings/database-postgresql.yml")
.hasMessageNotContaining("abc");
assertThat(ProviderChoice.running(old, List.of(provider("postgresql", RUNNING, null))).config().host())
.as("1.x keys are never used, even when still present").isEqualTo("db.running");
}
@Test
void anUnusableSettingNamesTheProviderPlugin() {
ProviderSettings bad = new ProviderSettings("db.example", "99999", "runway", "runway", null, null, null,
null);
assertThatThrownBy(() -> ProviderChoice.running(new DatabaseProps(), List.of(provider("mariadb", bad,
null)))).hasMessageStartingWith("database-mariadb settings: ").hasMessageContaining("port");
}
@Test
void theSavedSettingsAreThoseOfTheGivenProviderWhateverIsRunning() {
DatabaseProvider pg = provider("postgresql", RUNNING, SAVED);
ProviderChoice.Chosen chosen = ProviderChoice.saved(choosing("mariadb"), pg);
assertThat(chosen.config().host()).isEqualTo("db.saved");
assertThat(chosen.config().port()).isEqualTo(5433);
assertThat(chosen.config().password()).isEqualTo("saved-secret");
assertThatThrownBy(() -> ProviderChoice.saved(new DatabaseProps(), provider("postgresql", RUNNING, EMPTY)))
.hasMessageContaining("no server is saved");
assertThatThrownBy(() -> ProviderChoice.saved(new DatabaseProps(), provider("postgresql", RUNNING, null)))
.hasMessageContaining("older than 2.0.0");
}
}
@@ -27,6 +27,7 @@ import java.util.zip.GZIPOutputStream;
import mx.quest.database.spi.DatabaseException; import mx.quest.database.spi.DatabaseException;
import mx.quest.database.spi.DatabaseUnavailableException; import mx.quest.database.spi.DatabaseUnavailableException;
import mx.quest.database.spi.PluginDatabase; import mx.quest.database.spi.PluginDatabase;
import mx.quest.database.spi.ProviderSettings;
import mx.quest.database.spi.Scope; import mx.quest.database.spi.Scope;
import mx.quest.database.spi.ScopeNotReadyException; import mx.quest.database.spi.ScopeNotReadyException;
import mx.quest.runway.spi.model.SiteLifecycleEvent; import mx.quest.runway.spi.model.SiteLifecycleEvent;
@@ -187,28 +188,27 @@ class RealServerTest {
} }
assertThat(h.runtime.available()).isFalse(); assertThat(h.runtime.available()).isFalse();
assertThat(h.runtime.status()).isEqualTo(DatabaseRuntime.Status.CONNECTING); assertThat(h.runtime.status()).isEqualTo(DatabaseRuntime.Status.CONNECTING);
DatabaseProps typed = new DatabaseProps(); // The saved-settings test reads what the provider's page holds now, never the running settings.
typed.setProvider(engine); ConnectionTester tester = new ConnectionTester(h.runtime, h.props, () -> h.providers, work);
typed.setHost(endpoint.host()); assertThat(tester.testable()).containsExactly(engine);
typed.setPort(endpoint.port()); h.saved = saved(endpoint, Harness.DATABASE, endpoint.port(), Harness.USER, wrong);
typed.setDatabase(Harness.DATABASE); assertThat(tester.saved(engine).category()).isEqualTo(ConnectionTester.Category.AUTHENTICATION);
typed.setUsername(Harness.USER); h.saved = saved(endpoint, Harness.DATABASE, endpoint.port(), Harness.USER, endpoint.password());
typed.setTls("disable"); ConnectionTester.Result ok = tester.saved(engine);
ConnectionTester tester = new ConnectionTester(h.runtime, () -> h.providers, work); assertThat(ok.category()).isEqualTo(ConnectionTester.Category.OK);
assertThat(tester.newSettings(typed, wrong).category()).isEqualTo(ConnectionTester.Category.AUTHENTICATION); assertThat(ok.detail()).containsIgnoringCase(engine.equals("postgresql") ? "PostgreSQL" : "MariaDB");
assertThat(tester.newSettings(typed, endpoint.password()).category()) h.saved = saved(endpoint, "no_such_db_" + SEQ.incrementAndGet(), endpoint.port(), Harness.USER,
.isEqualTo(ConnectionTester.Category.OK); endpoint.password());
typed.setDatabase("no_such_db_" + SEQ.incrementAndGet()); assertThat(tester.saved(engine).category()).isEqualTo(ConnectionTester.Category.DATABASE_MISSING);
assertThat(tester.newSettings(typed, endpoint.password()).category()) h.saved = saved(endpoint, Harness.DATABASE, 1, Harness.USER, endpoint.password());
.isEqualTo(ConnectionTester.Category.DATABASE_MISSING); assertThat(tester.saved(engine).category()).isEqualTo(ConnectionTester.Category.UNREACHABLE);
typed.setDatabase(Harness.DATABASE); h.saved = saved(endpoint, Harness.DATABASE, 99999, Harness.USER, endpoint.password());
typed.setPort(1); assertThat(tester.saved(engine)).isEqualTo(new ConnectionTester.Result(
assertThat(tester.newSettings(typed, endpoint.password()).category()) ConnectionTester.Category.INVALID_SETTINGS, "database-" + engine + " settings: the port must be "
.isEqualTo(ConnectionTester.Category.UNREACHABLE); + "between 1 and 65535, or blank for the default"));
// A blank password is not sent to a different target. String other = engine.equals("postgresql") ? "mariadb" : "postgresql";
typed.setPort(endpoint.port()); assertThat(tester.saved(other).category()).isEqualTo(ConnectionTester.Category.NO_PROVIDER);
typed.setUsername("someone_else"); assertThat(h.runtime.status()).as("a test changes nothing").isEqualTo(DatabaseRuntime.Status.CONNECTING);
assertThat(tester.newSettings(typed, "").category()).isEqualTo(ConnectionTester.Category.AUTHENTICATION);
} finally { } finally {
root.detachAppender(logs); root.detachAppender(logs);
} }
@@ -218,13 +218,20 @@ class RealServerTest {
} }
} }
private static ProviderSettings saved(Harness.Endpoint endpoint, String database, int port, String user,
String password) {
return new ProviderSettings(endpoint.host(), String.valueOf(port), database, user, password, "disable", null,
null);
}
@Test @Test
void withoutSettingsOrProviderNothingConnects() throws Exception { void withoutSettingsOrProviderNothingConnects() throws Exception {
Harness.Endpoint endpoint = Harness.endpoint("postgresql").or(() -> Harness.endpoint("mariadb")).orElse(null); Harness.Endpoint endpoint = Harness.endpoint("postgresql").or(() -> Harness.endpoint("mariadb")).orElse(null);
assumeTrue(endpoint != null, "no database server configured (-Ddb.it.postgresql or -Ddb.it.mariadb)"); assumeTrue(endpoint != null, "no database server configured (-Ddb.it.postgresql or -Ddb.it.mariadb)");
Harness h = new Harness("postgresql", namespace("postgresql"), endpoint, work.resolve("nc")); Harness h = new Harness("postgresql", namespace("postgresql"), endpoint, work.resolve("nc"));
open.add(h); open.add(h);
h.props.setHost(null); h.host = null;
h.username = null;
h.start(); h.start();
assertThat(h.runtime.status()).isEqualTo(DatabaseRuntime.Status.NOT_CONFIGURED); assertThat(h.runtime.status()).isEqualTo(DatabaseRuntime.Status.NOT_CONFIGURED);
Harness p = new Harness("postgresql", namespace("postgresql"), endpoint, work.resolve("np")); Harness p = new Harness("postgresql", namespace("postgresql"), endpoint, work.resolve("np"));
+37
View File
@@ -0,0 +1,37 @@
<!-- The connection tests, rendered BELOW the generic settings form on /__app/plugins/database/settings (the kernel
renders an app-realm plugin's templates/admin-app.html there). Bare fragment; bindings in admin-app.th.xml read
the plugin's own beans. The tests take no typed values: a username box followed by a password box is a form the
browser fills in with the operator's own console login, which a test would then send to the server it names. -->
<div class="card mt-3" id="db-tests">
<div class="card-header"><h3 class="card-title" id="db-tests-title">Connection tests</h3></div>
<div class="card-body">
<p class="text-secondary" id="db-tests-intro">Settings saved here and on a provider's page apply at the next
restart. Test them first: the test connects once with the saved values and changes nothing.</p>
<div class="alert alert-success" id="db-test-ok" role="status"><span id="db-test-ok-text">ok</span></div>
<div class="alert alert-danger" id="db-test-error" role="alert"><span id="db-test-error-text">error</span></div>
<div class="mb-3">
<span class="text-secondary" id="db-now-label">Running now:</span>
<span class="fw-bold" id="db-now-status">Available</span>
<span class="text-secondary" id="db-now-detail">detail</span>
</div>
<form method="post" action="/__app/database/test-running" class="mb-3">
<input class="db-csrf" type="hidden" name="_csrf" value="">
<button type="submit" class="btn btn-outline-primary" id="db-test-running">Test the running
connection</button>
</form>
<p class="text-secondary mb-2" id="db-none">No provider plugin is installed: install database-postgresql or
database-mariadb.</p>
<div class="db-provider mb-2">
<form method="post" action="/__app/database/test-saved" class="d-inline">
<input class="db-csrf" type="hidden" name="_csrf" value="">
<input class="db-provider-in" type="hidden" name="provider" value="">
<button type="submit" class="btn btn-primary db-test-saved">Test the saved settings</button>
</form>
<a class="ms-2 db-provider-link" href="#">Edit them</a>
</div>
</div>
</div>
@@ -0,0 +1,38 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
Logic of the connection tests panel. It renders on the KERNEL-owned plugin settings page, which puts nothing of
this plugin in the model except the test result (flash attributes databaseTest / databaseTestError, set by the
console controller's redirect), so everything else comes from the plugin's beans: the running status from
databaseRuntime, the installed providers from databaseConnectionTester. The _csrf token comes from the page.
Provider links are built into a local variable: a URL processor may not call a bean.
-->
<thlogic>
<attr sel="#db-tests-title" th:text="#{database.panel.title}"/>
<attr sel="#db-tests-intro" th:text="#{database.panel.intro}"/>
<attr sel="#db-test-ok" th:if="${databaseTest != null}"/>
<attr sel="#db-test-ok-text" th:text="${databaseTest}"/>
<attr sel="#db-test-error" th:if="${databaseTestError != null}"/>
<attr sel="#db-test-error-text" th:text="${databaseTestError}"/>
<attr sel="#db-now-label" th:text="#{database.panel.now}"/>
<!-- th:if is evaluated before th:with, so the condition calls the bean itself. -->
<attr sel="#db-now-status" th:with="h=${@databaseRuntime.health()}"
th:text="#{'database.status.' + ${h.status().name()}(${h.detail()})}"/>
<attr sel="#db-now-detail" th:if="${@databaseRuntime.health().server() != null}"
th:text="${@databaseRuntime.health().server()}"/>
<attr sel=".db-csrf"
th:attr="name=${_csrf != null ? _csrf.parameterName : '_csrf'},value=${_csrf != null ? _csrf.token : ''}"/>
<attr sel="#db-test-running" th:text="#{database.panel.testRunning}"/>
<attr sel="#db-none" th:if="${@databaseConnectionTester.testable().isEmpty()}"
th:text="#{database.panel.none}"/>
<attr sel=".db-provider" th:each="p : ${@databaseConnectionTester.testable()}"
th:with="product=${#messages.msg('database.product.' + p)},
editUrl=${'/__app/plugins/database-' + p + '/settings'}"/>
<attr sel=".db-provider//.db-provider-in" th:value="${p}"/>
<attr sel=".db-provider//.db-test-saved" th:text="#{database.panel.testSaved(${product})}"/>
<attr sel=".db-provider//.db-provider-link" th:href="${editUrl}"
th:text="#{database.panel.edit(${product})}"/>
</thlogic>
+7 -57
View File
@@ -71,66 +71,16 @@
</div> </div>
</div> </div>
<!-- Connection tests --> <!-- Where the settings and the connection tests are (since 2.0.0) -->
<div class="col-lg-6"> <div class="col-lg-6">
<div class="card"> <div class="card">
<div class="card-header"><h3 class="card-title" id="db-test-title">Connection tests</h3></div> <div class="card-header"><h3 class="card-title" id="db-settings-title">Settings and tests</h3></div>
<div class="card-body"> <div class="card-body">
<form method="post" action="/__app/database/test-running" class="mb-3"> <p class="text-secondary" id="db-settings-text">The provider choice and the limits are on the
<input class="db-csrf" type="hidden" name="_csrf" value=""> Database plugin's settings page, together with the connection tests. The server, the account
<button type="submit" class="btn btn-outline-primary" id="db-test-running">Test running and TLS are on the provider plugin's settings page.</p>
connection</button> <a class="btn btn-outline-primary" href="/__app/plugins/database/settings#db-tests"
</form> id="db-settings-link">Settings and connection tests</a>
<p class="text-secondary small" id="db-test-new-help">Try other settings without saving them.</p>
<form method="post" action="/__app/database/test-new" autocomplete="off">
<input class="db-csrf" type="hidden" name="_csrf" value="">
<div class="row g-2">
<div class="col-md-4">
<label class="form-label" for="db-f-provider" id="db-fl-provider">Provider</label>
<select class="form-select" id="db-f-provider" name="provider">
<option value="postgresql">postgresql</option>
<option value="mariadb">mariadb</option>
</select>
</div>
<div class="col-md-5">
<label class="form-label" for="db-f-host" id="db-fl-host">Host</label>
<input class="form-control" id="db-f-host" name="host" type="text" value="">
</div>
<div class="col-md-3">
<label class="form-label" for="db-f-port" id="db-fl-port">Port</label>
<input class="form-control" id="db-f-port" name="port" type="text" value="">
</div>
<div class="col-md-4">
<label class="form-label" for="db-f-database" id="db-fl-database">Database</label>
<input class="form-control" id="db-f-database" name="database" type="text" value="">
</div>
<div class="col-md-4">
<label class="form-label" for="db-f-username" id="db-fl-username">Username</label>
<input class="form-control" id="db-f-username" name="username" type="text" value="">
</div>
<div class="col-md-4">
<label class="form-label" for="db-f-password" id="db-fl-password">Password</label>
<input class="form-control" id="db-f-password" name="password" type="password"
value="">
</div>
<div class="col-md-4">
<label class="form-label" for="db-f-tls" id="db-fl-tls">TLS</label>
<select class="form-select" id="db-f-tls" name="tls">
<option value="verify-full">verify-full</option>
<option value="require">require</option>
<option value="disable">disable</option>
</select>
</div>
<div class="col-md-8">
<label class="form-label" for="db-f-ca" id="db-fl-ca">CA certificate (PEM)</label>
<textarea class="form-control font-monospace" id="db-f-ca" name="caCertificate"
rows="2"></textarea>
</div>
</div>
<p class="text-secondary small mt-2" id="db-test-password-note">A blank password reuses the
saved one only for the same server, database, account and TLS settings.</p>
<button type="submit" class="btn btn-primary" id="db-test-new">Test these settings</button>
</form>
</div> </div>
</div> </div>
</div> </div>
+4 -14
View File
@@ -43,20 +43,10 @@
<attr sel="#db-last-error-text" th:text="${db.runtime().lastError()}"/> <attr sel="#db-last-error-text" th:text="${db.runtime().lastError()}"/>
<attr sel="#db-problem" th:if="${db.problem() != null}" th:text="${db.problem()}"/> <attr sel="#db-problem" th:if="${db.problem() != null}" th:text="${db.problem()}"/>
<!-- Connection tests --> <!-- Where the settings and the connection tests are -->
<attr sel="#db-test-title" th:text="#{database.console.tests}"/> <attr sel="#db-settings-title" th:text="#{database.console.settings}"/>
<attr sel="#db-test-running" th:text="#{database.console.testRunning}"/> <attr sel="#db-settings-text" th:text="#{database.console.settings.text}"/>
<attr sel="#db-test-new-help" th:text="#{database.console.testNew.help}"/> <attr sel="#db-settings-link" th:text="#{database.console.settings.link}"/>
<attr sel="#db-fl-provider" th:text="#{database.set.provider}"/>
<attr sel="#db-fl-host" th:text="#{database.set.host}"/>
<attr sel="#db-fl-port" th:text="#{database.set.port}"/>
<attr sel="#db-fl-database" th:text="#{database.set.database}"/>
<attr sel="#db-fl-username" th:text="#{database.set.username}"/>
<attr sel="#db-fl-password" th:text="#{database.set.password}"/>
<attr sel="#db-fl-tls" th:text="#{database.set.tls}"/>
<attr sel="#db-fl-ca" th:text="#{database.set.caCertificate}"/>
<attr sel="#db-test-password-note" th:text="#{database.console.testNew.password}"/>
<attr sel="#db-test-new" th:text="#{database.console.testNew}"/>
<!-- Migration problems --> <!-- Migration problems -->
<attr sel="#db-issues-title" th:text="#{database.console.issues}"/> <attr sel="#db-issues-title" th:text="#{database.console.issues}"/>
+6 -4
View File
@@ -2,7 +2,7 @@
> **Audience:** a developer starting a **new Runway plugin from scratch**. > **Audience:** a developer starting a **new Runway plugin from scratch**.
> **Scope:** the complete plugin contract of the Runway kernel at **SPI `1.1.0`** (Runway `1.1.0`; within `1.x` it > **Scope:** the complete plugin contract of the Runway kernel at **SPI `1.1.0`** (Runway `1.1.0`; within `1.x` it
> changes only additively — `1.1.0` added `PluginSettings.appSecret` — see the kernel's `docs/SPI-STABILITY.md`) — the descriptor, every extension > changes only additively — `1.1.0` added `PluginSettings.appSecret`, `1.2.0` `PluginSettings.savedApp` — see the kernel's `docs/SPI-STABILITY.md`) — the descriptor, every extension
> axis, the **service tier** through which a plugin reaches the kernel, the `POST`/CSRF rules, the build, the > axis, the **service tier** through which a plugin reaches the kernel, the `POST`/CSRF rules, the build, the
> install, how to verify, and the traps. Everything here is grounded in the kernel as built and verified against the > install, how to verify, and the traps. Everything here is grounded in the kernel as built and verified against the
> packaged host jar; a gap is called a gap. > packaged host jar; a gap is called a gap.
@@ -141,7 +141,7 @@ mainClass: com.acme.myplugin.MyPluginConfig # the @Configuration; omit for a c
# The LOWEST SPI level whose types you use (the newest type decides): ">=0.4.0" PluginSettings/PluginInfo/ # The LOWEST SPI level whose types you use (the newest type decides): ">=0.4.0" PluginSettings/PluginInfo/
# PluginLifecycle; ">=0.5.0" PluginSiteFiles, Sites, RequestContext, AccessCheck, Messages, SitePages, anonymous # PluginLifecycle; ">=0.5.0" PluginSiteFiles, Sites, RequestContext, AccessCheck, Messages, SitePages, anonymous
# routes, siteData; ">=0.6.0" ContentCatalogView, ContentChanges, SiteEventListener, @ConsoleScreen; ">=1.0.0" # routes, siteData; ">=0.6.0" ContentCatalogView, ContentChanges, SiteEventListener, @ConsoleScreen; ">=1.0.0"
# HeadContext.origin(); ">=1.1.0" PluginSettings.appSecret. A plugin loads on every 1.x kernel at or above the floor # HeadContext.origin(); ">=1.1.0" PluginSettings.appSecret; ">=1.2.0" PluginSettings.savedApp. A plugin loads on every 1.x kernel at or above the floor
# it declares; a kernel below it BLOCKS the plugin with a reason. A plugin with a mainClass MUST declare a floor >= 0.4.0: without one it is # it declares; a kernel below it BLOCKS the plugin with a reason. A plugin with a mainClass MUST declare a floor >= 0.4.0: without one it is
# blocked as "built for the pre-1.0 plugin contract" (a code-less library plugin is exempt). # blocked as "built for the pre-1.0 plugin contract" (a code-less library plugin is exempt).
requiresSpi: ">=0.6.0" requiresSpi: ">=0.6.0"
@@ -440,7 +440,9 @@ on every node. Nested structures: parse `values()` yourself. **Three settings su
- **App-level (`settings:`)** — platform concerns, `runway.plugin.<id>.*`, applied on **restart**, read through your - **App-level (`settings:`)** — platform concerns, `runway.plugin.<id>.*`, applied on **restart**, read through your
own `@ConfigurationProperties` bean (§5). A `secret` there binds as ciphertext: read it in clear with own `@ConfigurationProperties` bean (§5). A `secret` there binds as ciphertext: read it in clear with
`settings.appSecret(key)` (SPI `1.1.0`; declare `requiresSpi: ">=1.1.0"`). It answers only for a key your own `settings.appSecret(key)` (SPI `1.1.0`; declare `requiresSpi: ">=1.1.0"`). It answers only for a key your own
`settings:` declares `type: secret`, with the value the running application started with. `settings:` declares `type: secret`, with the value the running application started with. To check a saved change
before the restart applies it (a connection test, say), read `settings.savedApp(key)` (SPI `1.2.0`): any key your
`settings:` declares, as saved now, a secret in clear and a blank value as its declared default.
- **Per-site (`siteSettings:`)** — `PluginSettings`; react to a save with `SiteEventListener.onSettingsChanged`. - **Per-site (`siteSettings:`)** — `PluginSettings`; react to a save with `SiteEventListener.onSettingsChanged`.
- **Per-placement (`widgetSettings:`)** — nothing to read: they arrive as `WidgetView.config()`. - **Per-placement (`widgetSettings:`)** — nothing to read: they arrive as `WidgetView.config()`.
@@ -570,7 +572,7 @@ In-memory fakes with the kernel's input rules, so plugin tests need no kernel an
| Fake | For | | Fake | For |
|---|---| |---|---|
| `FakePluginSettings` | `.defaults(…)`, `.site(id, values)`, `.secret(id, key, clear)`, `.appSecret(key, clear)` (testkit `1.1.0`) | | `FakePluginSettings` | `.defaults(…)`, `.site(id, values)`, `.secret(id, key, clear)`, `.appSecret(key, clear)` (testkit `1.1.0`), `.savedApp(key, value)` (testkit `1.2.0`) |
| `TempDirSiteFiles(sitesRoot, pluginId)` | `PluginSiteFiles` over a temp folder, with the kernel's three confinement layers, the caps and the missing-site rule | | `TempDirSiteFiles(sitesRoot, pluginId)` | `PluginSiteFiles` over a temp folder, with the kernel's three confinement layers, the caps and the missing-site rule |
| `FakeSiteServices` | `Sites`, `RequestContext` (`.current(id)`), `AccessCheck` (`.grant(key)`), `Messages` (`.message(…)`), `SitePages` (`.page(…)`, `.nextInstall(outcome)`, `.installs()`) | | `FakeSiteServices` | `Sites`, `RequestContext` (`.current(id)`), `AccessCheck` (`.grant(key)`), `Messages` (`.message(…)`), `SitePages` (`.page(…)`, `.nextInstall(outcome)`, `.installs()`) |
| `FakeContentCatalog` | `ContentCatalogView`: `.entry(…)`, `.page(…)`, `.route(…)`, `.refreshed()` | | `FakeContentCatalog` | `ContentCatalogView`: `.entry(…)`, `.page(…)`, `.route(…)`, `.refreshed()` |
@@ -74,10 +74,11 @@ cp -r "$REPO/database/target/database" "$EXT/plugins/database"
cp -r "$REPO/database-$PROVIDER/target/database-$PROVIDER" "$EXT/plugins/database-$PROVIDER" cp -r "$REPO/database-$PROVIDER/target/database-$PROVIDER" "$EXT/plugins/database-$PROVIDER"
cp -r "$HERE/target/runway-demo-database" "$EXT/plugins/runway-demo-database" 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=$!; } boot() { ( cd "$SCRATCH" && exec "$JAVA" -jar "$JAR" --server.port="$PORT" --runway.storage.external="$EXT" ) >"$1" 2>&1 & PID=$!; }
settings() { # port settings() { # port. Since database 2.0.0 the server is the provider plugin's setting; the namespace stays.
umask 077 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' \ printf 'runway:\n plugin:\n database:\n namespace: %s\n' "$NS" > "$EXT/plugin-settings/database.yml"
"$PROVIDER" "$NS" "$DB_HOST" "$1" "$DB_NAME" "$DB_USER" "$DB_PASSWORD" > "$EXT/plugin-settings/database.yml" printf 'runway:\n plugin:\n database-%s:\n host: "%s"\n port: %s\n database: "%s"\n username: "%s"\n password: "%s"\n tls: disable\n' \
"$PROVIDER" "$DB_HOST" "$1" "$DB_NAME" "$DB_USER" "$DB_PASSWORD" > "$EXT/plugin-settings/database-$PROVIDER.yml"
umask 022 umask 022
} }
+2 -2
View File
@@ -13,7 +13,7 @@
<groupId>mx.quest</groupId> <groupId>mx.quest</groupId>
<artifactId>runway</artifactId> <artifactId>runway</artifactId>
<version>1.1.0</version> <version>1.2.0</version>
<packaging>pom</packaging> <packaging>pom</packaging>
<name>Runway</name> <name>Runway</name>
@@ -42,7 +42,7 @@
extended timestamp through the build JVM's default time zone, so the same source built in CST and extended timestamp through the build JVM's default time zone, so the same source built in CST and
in UTC differed by exactly 6 h inside the exec jar (found 2026-10-17 on a second host). in UTC differed by exactly 6 h inside the exec jar (found 2026-10-17 on a second host).
.mvn/jvm.config pins -Duser.timezone=UTC for the Maven JVM, which removes the host's zone. --> .mvn/jvm.config pins -Duser.timezone=UTC for the Maven JVM, which removes the host's zone. -->
<project.build.outputTimestamp>2026-10-29T15:02:00Z</project.build.outputTimestamp> <project.build.outputTimestamp>2026-10-30T17:20:00Z</project.build.outputTimestamp>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<!-- runway-spi and runway-spi-testkit attach a sources jar (release assets for third-party plugin authors, <!-- runway-spi and runway-spi-testkit attach a sources jar (release assets for third-party plugin authors,
docs/PLUGIN-DEVELOPMENT.md §3). Boot's parent manages 3.3.1; 3.4.0 is the version the build hosts' docs/PLUGIN-DEVELOPMENT.md §3). Boot's parent manages 3.3.1; 3.4.0 is the version the build hosts'
+1 -1
View File
@@ -7,7 +7,7 @@
<parent> <parent>
<groupId>mx.quest</groupId> <groupId>mx.quest</groupId>
<artifactId>runway</artifactId> <artifactId>runway</artifactId>
<version>1.1.0</version> <version>1.2.0</version>
</parent> </parent>
<artifactId>runway-app</artifactId> <artifactId>runway-app</artifactId>
@@ -1,6 +1,7 @@
package mx.quest.runway.backup; package mx.quest.runway.backup;
import java.io.IOException; import java.io.IOException;
import java.io.UncheckedIOException;
import java.nio.file.Files; import java.nio.file.Files;
import java.nio.file.Path; import java.nio.file.Path;
import java.util.List; import java.util.List;
@@ -20,6 +21,10 @@ import org.springframework.stereotype.Component;
* leftover scratch. A work dir whose recovery move itself fails is left untouched (its {@code old} preserved * leftover scratch. A work dir whose recovery move itself fails is left untouched (its {@code old} preserved
* for manual recovery), never deleted. * for manual recovery), never deleted.
* *
* <p>The site's logs and stats ride in the work dir until a restore has swapped and merged them, so the sweep
* finishes that too, with the same routine the restore uses ({@link BackupService#settle}): a site folder holding no
* {@code site.yml} — one a log write recreated mid-swap — is never mistaken for the site.
*
* <p>The scratch lives under {@code sites/.restore-work/}, a hidden name {@link * <p>The scratch lives under {@code sites/.restore-work/}, a hidden name {@link
* mx.quest.runway.storage.PathSafety#isSafeId} rejects, so it is never mistaken for a tenant. * mx.quest.runway.storage.PathSafety#isSafeId} rejects, so it is never mistaken for a tenant.
*/ */
@@ -49,20 +54,18 @@ public class BackupRestoreRecovery {
} }
for (Path workDir : workDirs) { for (Path workDir : workDirs) {
String siteId = workDir.getFileName().toString(); String siteId = workDir.getFileName().toString();
Path old = workDir.resolve("old");
Path siteDir = layout.siteDir(siteId); Path siteDir = layout.siteDir(siteId);
if (Files.exists(old) && !Files.exists(siteDir)) { try {
try { if (BackupService.settle(siteDir, workDir)) {
Files.move(old, siteDir);
log.warn("recovered site '{}' from an interrupted restore", siteId); log.warn("recovered site '{}' from an interrupted restore", siteId);
} catch (IOException e) {
// Recovery failed — DO NOT delete this work dir; `old` is the only copy of the site.
log.error("could not recover site '{}' automatically — its content is preserved at {}",
siteId, old, e);
continue;
} }
} catch (IOException | UncheckedIOException e) {
// Recovery failed — DO NOT delete this work dir: it may hold the only copy of the site, or its logs.
log.error("could not recover site '{}' automatically — its content is preserved at {}",
siteId, workDir, e);
continue;
} }
BackupService.deleteRecursively(workDir); // recovered or not needed — the leftovers are safe to drop BackupService.deleteRecursively(workDir); // settled — the leftovers (a staging copy) are safe to drop
} }
} }
} }
@@ -9,6 +9,7 @@ import java.io.InputStream;
import java.io.OutputStream; import java.io.OutputStream;
import java.io.UncheckedIOException; import java.io.UncheckedIOException;
import java.nio.file.AtomicMoveNotSupportedException; import java.nio.file.AtomicMoveNotSupportedException;
import java.nio.file.FileAlreadyExistsException;
import java.nio.file.Files; import java.nio.file.Files;
import java.nio.file.LinkOption; import java.nio.file.LinkOption;
import java.nio.file.Path; import java.nio.file.Path;
@@ -296,7 +297,7 @@ public class BackupService {
private void doRestore(String siteId, InputStream in, boolean keepRouting) throws IOException { private void doRestore(String siteId, InputStream in, boolean keepRouting) throws IOException {
Site live = keepRouting ? sites.find(siteId).orElseThrow(() -> new IOException("no site " + siteId)) : null; Site live = keepRouting ? sites.find(siteId).orElseThrow(() -> new IOException("no site " + siteId)) : null;
Staged staged = stageAndSwap(siteId, in); Staged staged = stageAndSwap(siteId, in, true);
if (live != null) { if (live != null) {
keepRouting(siteId, live); keepRouting(siteId, live);
} else { } else {
@@ -307,7 +308,9 @@ public class BackupService {
sites.evict(siteId); sites.evict(siteId);
events.publishEvent(new SiteChangedEvent(siteId, SiteChangedEvent.Kind.RESTORED)); events.publishEvent(new SiteChangedEvent(siteId, SiteChangedEvent.Kind.RESTORED));
importParticipants(siteId, staged.pluginData()); importParticipants(siteId, staged.pluginData());
deleteRecursively(staged.work()); if (staged.settled()) {
deleteRecursively(staged.work());
} // else: the site's previous logs wait in it for the next restore or start (swapIntoPlace)
log.info("restored site '{}' from backup", siteId); log.info("restored site '{}' from backup", siteId);
} }
@@ -384,7 +387,7 @@ public class BackupService {
if (sites.exists(newId)) { if (sites.exists(newId)) {
throw new IllegalStateException("a site with id '" + newId + "' already exists"); throw new IllegalStateException("a site with id '" + newId + "' already exists");
} }
Staged staged = stageAndSwap(newId, in); Staged staged = stageAndSwap(newId, in, false); // a new site starts its own logs
try { try {
// The staged site.yml still carries the SOURCE identity — no event has fired, so rewrite it now. // The staged site.yml still carries the SOURCE identity — no event has fired, so rewrite it now.
Site source = sites.find(newId).orElseThrow(() -> new IOException("restored site.yml is unreadable")); Site source = sites.find(newId).orElseThrow(() -> new IOException("restored site.yml is unreadable"));
@@ -420,19 +423,30 @@ public class BackupService {
} }
/** The result of staging a backup: the manifest, the plugin data to import, and the work dir to clean up. */ /** The result of staging a backup: the manifest, the plugin data to import, and the work dir to clean up. */
private record Staged(BackupManifest manifest, Map<String, Map<String, byte[]>> pluginData, Path work) { private record Staged(BackupManifest manifest, Map<String, Map<String, byte[]>> pluginData, Path work,
boolean settled) {
} }
/** /**
* Extracts + validates the archive into a staging dir and atomically swaps it into {@code siteId}'s folder. * Extracts + validates the archive into a staging dir and atomically swaps it into {@code siteId}'s folder.
* Publishes no event and imports no participant data — the caller owns the lifecycle (restore vs create), * Publishes no event and imports no participant data — the caller owns the lifecycle (restore vs create),
* so create can rewrite the identity before anything observes the swapped-in files. * so create can rewrite the identity before anything observes the swapped-in files. {@code keepTransient}: the
* live site's logs and stats stay with it (a restore), or are dropped (a new site starts its own).
*/ */
private Staged stageAndSwap(String siteId, InputStream in) throws IOException { private Staged stageAndSwap(String siteId, InputStream in, boolean keepTransient) throws IOException {
Path siteDir = layout.siteDir(siteId); Path siteDir = layout.siteDir(siteId);
Path work = workDir(siteId); Path work = workDir(siteId);
Path staging = work.resolve("staging"); Path staging = work.resolve("staging");
Path old = work.resolve("old"); Path old = work.resolve("old");
if (Files.exists(work, LinkOption.NOFOLLOW_LINKS)) {
// A previous swap may have left the site's logs (or, after a crash, the site itself) here: finish it
// first, and refuse rather than delete it when that fails.
try {
settle(siteDir, work);
} catch (UncheckedIOException e) {
throw e.getCause();
}
}
deleteRecursively(work); deleteRecursively(work);
Files.createDirectories(staging); Files.createDirectories(staging);
// TOCTOU guard: between the delete above and this create, a local attacker could plant a symlink at // TOCTOU guard: between the delete above and this create, a local attacker could plant a symlink at
@@ -492,8 +506,8 @@ public class BackupService {
throw new IOException("not a valid Runway site backup (missing manifest.yml or site content)"); throw new IOException("not a valid Runway site backup (missing manifest.yml or site content)");
} }
warnParticipantDrift(siteId, manifest, pluginData); warnParticipantDrift(siteId, manifest, pluginData);
swapIntoPlace(siteDir, staging, old); boolean settled = swapIntoPlace(siteDir, staging, old, keepTransient);
return new Staged(manifest, pluginData, work); return new Staged(manifest, pluginData, work, settled);
} }
/** /**
@@ -747,7 +761,7 @@ public class BackupService {
/** Transient per-site data (access/audit logs, bandwidth stats) excluded from the content backup. */ /** Transient per-site data (access/audit logs, bandwidth stats) excluded from the content backup. */
private static boolean isTransient(String rel) { private static boolean isTransient(String rel) {
return rel.equals("logs") || rel.startsWith("logs/") || rel.equals("stats") || rel.startsWith("stats/"); return TRANSIENT_DIRS.stream().anyMatch(dir -> rel.equals(dir) || rel.startsWith(dir + "/"));
} }
private static void collectPluginEntry(Map<String, Map<String, byte[]>> into, String rest, byte[] bytes) { private static void collectPluginEntry(Map<String, Map<String, byte[]>> into, String rest, byte[] bytes) {
@@ -772,27 +786,191 @@ public class BackupService {
} }
} }
/** Atomic same-filesystem swap: current → old, staged → live, drop old; restore the original on failure. */ /**
private static void swapIntoPlace(Path siteDir, Path staging, Path old) throws IOException { * Atomic same-filesystem swap: current → old, staged → live, drop old; restore the original on failure.
*
* <p><b>The site's logs and usage stats stay with the site</b> when {@code keepTransient} (a restore): a backup
* never carries them, so the swap alone would start the audit journal again from nothing — and a restore is
* exactly the act a journal must survive. They stay inside {@code old} until the new copy is in place, then
* {@link #settle} merges them in. Until that has succeeded the work folder is kept: the next restore of the
* site, or the next start ({@link BackupRestoreRecovery}), settles it again, so neither a crash nor a failed
* merge loses them. Whatever an archive carries under those names is discarded first: a backup never writes
* them, so a crafted one must not plant journal lines.
*
* <p>The log writer and the bandwidth flush create these folders on demand, so a write landing between the two
* renames recreates the site folder and the second rename fails. That folder (it holds no {@code site.yml}) is
* set aside as {@code late} and the rename retried once; its lines are merged like the others.
*
* @return whether the work folder holds nothing more of the site's and may be deleted
*/
private static boolean swapIntoPlace(Path siteDir, Path staging, Path old, boolean keepTransient)
throws IOException {
for (String name : TRANSIENT_DIRS) {
deleteRecursively(staging.resolve(name));
}
Path work = old.getParent();
Path late = work.resolve(LATE_DIR);
try { try {
if (Files.exists(siteDir)) { if (Files.exists(siteDir)) {
move(siteDir, old); move(siteDir, old);
} }
move(staging, siteDir); try {
move(staging, siteDir);
} catch (IOException recreated) {
if (!setAsideIfNotASite(siteDir, late)) {
throw recreated;
}
move(staging, siteDir);
}
} catch (IOException swapFailed) { } catch (IOException swapFailed) {
if (Files.exists(old) && !Files.exists(siteDir)) { if (Files.exists(old)) {
try { try {
move(old, siteDir); // roll back settle(siteDir, work); // rolls the original back, with any lines written meanwhile
} catch (IOException rollbackFailed) { } catch (IOException | UncheckedIOException rollbackFailed) {
// Leave `old` in place as the recovery copy — the startup sweep rolls it forward. Do NOT // Leave `old` in place as the recovery copy — the startup sweep rolls it forward. Do NOT
// delete it (it now holds the ONLY copy of the original site). // delete it (it may hold the ONLY copy of the original site).
swapFailed.addSuppressed(rollbackFailed); swapFailed.addSuppressed(rollbackFailed);
throw swapFailed;
} }
} }
throw swapFailed; throw swapFailed;
} }
if (keepTransient) {
try {
settle(siteDir, work);
} catch (IOException | UncheckedIOException e) {
// The restore itself succeeded. The site's previous logs stay in the work folder for the next try.
log.warn("could not carry the logs of site folder {} over the restore yet; the next restore of "
+ "the site or the next start does", siteDir, e);
return false;
}
}
deleteRecursively(late);
deleteRecursively(old); deleteRecursively(old);
return true;
}
/**
* Finishes what a swap left in its work folder: the site's previous copy ({@code old}) and the lines written
* while the site folder was away ({@code late}). Used after a swap, before the next restore of the same site,
* and by the startup sweep. A site folder holding no {@code site.yml} is never taken for the site.
* <ul>
* <li>{@code old} and no site folder: the swap never completed — {@code old} goes back, followed by the
* {@code late} lines;</li>
* <li>{@code old} and the site: the swap completed — the {@code late} and then the {@code old} lines go
* before the site's own;</li>
* <li>no {@code old}: a rollback put the original back — the {@code late} lines go after its own.</li>
* </ul>
* Each merged file is removed from the work folder, so a run that fails half-way can simply be repeated.
*
* @return whether the previous copy was rolled back into place
* @throws IOException when a move or a merge fails; the work folder must then be kept
*/
static boolean settle(Path siteDir, Path workDir) throws IOException {
Path old = workDir.resolve("old");
Path late = workDir.resolve(LATE_DIR);
if (!Files.exists(old, LinkOption.NOFOLLOW_LINKS)) {
mergeTransient(late, siteDir, false);
return false;
}
setAsideIfNotASite(siteDir, late);
if (!Files.exists(siteDir, LinkOption.NOFOLLOW_LINKS)) {
move(old, siteDir);
mergeTransient(late, siteDir, false);
return true;
}
mergeTransient(late, siteDir, true);
mergeTransient(old, siteDir, true);
return false;
}
/** The site folder's transient sub-folders, as {@link #isTransient(String)} names them. */
static final List<String> TRANSIENT_DIRS = List.of("logs", "stats");
/** Beside {@code old} in a restore's work folder: a site folder a late write recreated mid-swap. */
static final String LATE_DIR = "late";
/**
* Moves {@code siteDir} to {@code aside} when it exists but holds no {@code site.yml} — a folder a log or stats
* write recreated, not a site — merging it after whatever {@code aside} already holds.
*
* @return whether {@code siteDir} was set aside
*/
static boolean setAsideIfNotASite(Path siteDir, Path aside) throws IOException {
if (!Files.isDirectory(siteDir, LinkOption.NOFOLLOW_LINKS) || Files.exists(siteDir.resolve("site.yml"))) {
return false;
}
if (Files.exists(aside, LinkOption.NOFOLLOW_LINKS)) {
mergeTransient(siteDir, aside, false);
deleteRecursively(siteDir);
} else {
move(siteDir, aside);
}
return true;
}
/**
* Moves the transient files under {@code from} ({@link #TRANSIENT_DIRS}) into the site folder {@code into}.
* A file {@code into} lacks is moved; a log both have is joined, {@code from}'s lines first when
* {@code fromIsOlder} (the journal is read in file order, so the order of the lines is the order of the events);
* a stats file both have keeps {@code into}'s, which the bandwidth service rewrites whole from memory. Symlinks
* and other non-regular files are left behind. Missing folders are a no-op. A line the log writer appends to a
* joined file during the copy is lost: a window of one file copy, during a restore.
*/
static void mergeTransient(Path from, Path into, boolean fromIsOlder) throws IOException {
if (!Files.isDirectory(from, LinkOption.NOFOLLOW_LINKS) || !Files.isDirectory(into, LinkOption.NOFOLLOW_LINKS)) {
return;
}
for (String name : TRANSIENT_DIRS) {
Path root = from.resolve(name);
if (!Files.isDirectory(root, LinkOption.NOFOLLOW_LINKS)) {
continue;
}
List<Path> files;
try (Stream<Path> walk = Files.walk(root)) {
files = walk.filter(f -> Files.isRegularFile(f, LinkOption.NOFOLLOW_LINKS)).toList();
}
for (Path file : files) {
Path target = into.resolve(name).resolve(root.relativize(file).toString());
Files.createDirectories(target.getParent());
if (moveIfAbsent(file, target)) {
continue;
}
if (name.equals("logs") && Files.isRegularFile(target, LinkOption.NOFOLLOW_LINKS)) {
// Streamed through a sibling file: today's access log of a busy site can be large.
Path joined = target.resolveSibling(target.getFileName() + ".joining");
try (OutputStream out = Files.newOutputStream(joined)) {
Files.copy(fromIsOlder ? file : target, out);
Files.copy(fromIsOlder ? target : file, out);
}
move(joined, target);
}
Files.delete(file); // merged (or superseded): a re-run must not join it twice
}
}
}
/**
* Moves {@code file} to {@code target} unless {@code target} exists, atomically: a hard link fails when the
* name is taken, where a rename would replace a log the writer has just created. Falls back to a checked move
* on a filesystem without hard links.
*
* @return whether the file was moved
*/
private static boolean moveIfAbsent(Path file, Path target) throws IOException {
try {
Files.createLink(target, file);
} catch (FileAlreadyExistsException taken) {
return false;
} catch (UnsupportedOperationException noLinks) {
try {
Files.move(file, target); // no REPLACE_EXISTING: refuses an existing target
return true;
} catch (FileAlreadyExistsException taken) {
return false;
}
}
Files.delete(file);
return true;
} }
/** A same-filesystem rename, atomic where the filesystem supports it. */ /** A same-filesystem rename, atomic where the filesystem supports it. */
@@ -1,5 +1,6 @@
package mx.quest.runway.console; package mx.quest.runway.console;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse; import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
@@ -49,10 +50,13 @@ public class AppBackupsController {
private final AppActivityLog activity; private final AppActivityLog activity;
private final mx.quest.runway.backup.BackupProperties policy; private final mx.quest.runway.backup.BackupProperties policy;
private final mx.quest.runway.platform.PlatformSettingsStore platform;
public AppBackupsController(SiteStore sites, BackupService backups, PlatformAuthority platformAuthority, public AppBackupsController(SiteStore sites, BackupService backups, PlatformAuthority platformAuthority,
@Qualifier("operatorAwareMessageSource") MessageSource messages, @Qualifier("operatorAwareMessageSource") MessageSource messages,
AppActivityLog activity, mx.quest.runway.backup.BackupProperties policy) { AppActivityLog activity, mx.quest.runway.backup.BackupProperties policy,
mx.quest.runway.platform.PlatformSettingsStore platform) {
this.platform = platform;
this.policy = policy; this.policy = policy;
this.sites = sites; this.sites = sites;
this.backups = backups; this.backups = backups;
@@ -61,6 +65,9 @@ public class AppBackupsController {
this.activity = activity; this.activity = activity;
} }
/** Flash attribute naming the site whose hosts the Backups screen shows for review after a restore. */
static final String REVIEW_HOSTS = "reviewHostsOf";
/** One site row: its id and the backups stored for it on the server. */ /** One site row: its id and the backups stored for it on the server. */
public record SiteBackups(String siteId, List<StoredBackup> stored) { public record SiteBackups(String siteId, List<StoredBackup> stored) {
} }
@@ -73,6 +80,15 @@ public class AppBackupsController {
rows.add(new SiteBackups(site.id(), backups.list(site.id()))); rows.add(new SiteBackups(site.id(), backups.list(site.id())));
} }
model.addAttribute("rows", rows); model.addAttribute("rows", rows);
// After a restore (or a site created from a backup), how the site is reached now: the hosts and base URL may
// have come from the backup, so they are shown for review with the editor, read from the store as they stand.
if (model.getAttribute(REVIEW_HOSTS) instanceof String reviewed) {
sites.find(reviewed).ifPresent(site -> {
model.addAttribute("reviewSite", site);
// A site with no host is reached only if it is the default (catch-all) site; otherwise not at all.
model.addAttribute("reviewIsDefault", platform.get().defaultSite().filter(reviewed::equals).isPresent());
});
}
// Shown, not edited: a server folder that receives every site's archives is the host's (settings-homes.yml). // Shown, not edited: a server folder that receives every site's archives is the host's (settings-homes.yml).
String offsite = policy.getOffsiteDir(); String offsite = policy.getOffsiteDir();
model.addAttribute("offsiteDir", offsite == null || offsite.isBlank() ? null : offsite.trim()); model.addAttribute("offsiteDir", offsite == null || offsite.isBlank() ? null : offsite.trim());
@@ -83,8 +99,8 @@ public class AppBackupsController {
/** Stream a fresh backup of any site. */ /** Stream a fresh backup of any site. */
@GetMapping("/__app/backups/{siteId}/download") @GetMapping("/__app/backups/{siteId}/download")
public void download(@PathVariable String siteId, Authentication authentication, HttpServletResponse response) public void download(@PathVariable String siteId, Authentication authentication, HttpServletRequest request,
throws IOException { HttpServletResponse response) throws IOException {
platformAuthority.require(authentication); platformAuthority.require(authentication);
if (!sites.exists(siteId)) { if (!sites.exists(siteId)) {
throw new ResponseStatusException(HttpStatus.NOT_FOUND, "no such site"); throw new ResponseStatusException(HttpStatus.NOT_FOUND, "no such site");
@@ -92,13 +108,17 @@ public class AppBackupsController {
response.setContentType("application/zip"); response.setContentType("application/zip");
response.setHeader(HttpHeaders.CONTENT_DISPOSITION, response.setHeader(HttpHeaders.CONTENT_DISPOSITION,
"attachment; filename=\"" + siteId + "-backup-" + LocalDate.now() + ".zip\""); "attachment; filename=\"" + siteId + "-backup-" + LocalDate.now() + ".zip\"");
if (TenantBackupsController.isHead(request)) {
return; // the headers only: no archive is built, and nothing is downloaded
}
backups.backup(siteId, response.getOutputStream()); backups.backup(siteId, response.getOutputStream());
activity.record(authentication.getName(), "backup.downloaded", siteId + " (full)");
} }
/** Stream a <b>transfer</b> archive of any site — no credentials, accounts or origin hostnames. */ /** Stream a <b>transfer</b> archive of any site — no credentials, accounts or origin hostnames. */
@GetMapping("/__app/backups/{siteId}/download-transfer") @GetMapping("/__app/backups/{siteId}/download-transfer")
public void downloadForTransfer(@PathVariable String siteId, Authentication authentication, public void downloadForTransfer(@PathVariable String siteId, Authentication authentication,
HttpServletResponse response) throws IOException { HttpServletRequest request, HttpServletResponse response) throws IOException {
platformAuthority.require(authentication); platformAuthority.require(authentication);
if (!sites.exists(siteId)) { if (!sites.exists(siteId)) {
throw new ResponseStatusException(HttpStatus.NOT_FOUND, "no such site"); throw new ResponseStatusException(HttpStatus.NOT_FOUND, "no such site");
@@ -106,7 +126,11 @@ public class AppBackupsController {
response.setContentType("application/zip"); response.setContentType("application/zip");
response.setHeader(HttpHeaders.CONTENT_DISPOSITION, response.setHeader(HttpHeaders.CONTENT_DISPOSITION,
"attachment; filename=\"" + siteId + "-transfer-" + LocalDate.now() + ".zip\""); "attachment; filename=\"" + siteId + "-transfer-" + LocalDate.now() + ".zip\"");
if (TenantBackupsController.isHead(request)) {
return;
}
backups.backup(siteId, response.getOutputStream(), BackupService.BackupPurpose.TRANSFER); backups.backup(siteId, response.getOutputStream(), BackupService.BackupPurpose.TRANSFER);
activity.record(authentication.getName(), "backup.downloaded", siteId + " (transfer)");
} }
/** Save a stored backup of any site on the server. */ /** Save a stored backup of any site on the server. */
@@ -136,6 +160,7 @@ public class AppBackupsController {
backups.restore(siteId, in); backups.restore(siteId, in);
activity.record(authentication.getName(), "site.restored", siteId + " (upload)"); activity.record(authentication.getName(), "site.restored", siteId + " (upload)");
redirect.addFlashAttribute("flash", message("op.appbackups.restored", "Site restored.")); redirect.addFlashAttribute("flash", message("op.appbackups.restored", "Site restored."));
redirect.addFlashAttribute(REVIEW_HOSTS, siteId);
} catch (UnsupportedBackupFormatException e) { } catch (UnsupportedBackupFormatException e) {
redirect.addFlashAttribute("error", newerFormat(e)); redirect.addFlashAttribute("error", newerFormat(e));
} catch (IOException | RuntimeException e) { } catch (IOException | RuntimeException e) {
@@ -154,6 +179,7 @@ public class AppBackupsController {
backups.restoreStored(siteId, name); backups.restoreStored(siteId, name);
activity.record(authentication.getName(), "site.restored", siteId + "/" + name); activity.record(authentication.getName(), "site.restored", siteId + "/" + name);
redirect.addFlashAttribute("flash", message("op.appbackups.restored", "Site restored.")); redirect.addFlashAttribute("flash", message("op.appbackups.restored", "Site restored."));
redirect.addFlashAttribute(REVIEW_HOSTS, siteId);
} catch (UnsupportedBackupFormatException e) { } catch (UnsupportedBackupFormatException e) {
redirect.addFlashAttribute("error", newerFormat(e)); redirect.addFlashAttribute("error", newerFormat(e));
} catch (IOException | RuntimeException e) { } catch (IOException | RuntimeException e) {
@@ -196,6 +222,7 @@ public class AppBackupsController {
backups.createFromBackup(newId.strip(), name, splitHosts(hosts), in); backups.createFromBackup(newId.strip(), name, splitHosts(hosts), in);
activity.record(authentication.getName(), "site.created-from-backup", newId.strip()); activity.record(authentication.getName(), "site.created-from-backup", newId.strip());
redirect.addFlashAttribute("flash", message("op.appbackups.created", "Site created from backup.")); redirect.addFlashAttribute("flash", message("op.appbackups.created", "Site created from backup."));
redirect.addFlashAttribute(REVIEW_HOSTS, newId.strip());
} catch (UnsupportedBackupFormatException e) { } catch (UnsupportedBackupFormatException e) {
redirect.addFlashAttribute("error", newerFormat(e)); redirect.addFlashAttribute("error", newerFormat(e));
} catch (IllegalStateException e) { } catch (IllegalStateException e) {
@@ -1,5 +1,6 @@
package mx.quest.runway.console; package mx.quest.runway.console;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse; import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
@@ -7,6 +8,7 @@ import java.nio.file.Path;
import java.time.LocalDate; import java.time.LocalDate;
import mx.quest.runway.backup.BackupService; import mx.quest.runway.backup.BackupService;
import mx.quest.runway.backup.UnsupportedBackupFormatException; import mx.quest.runway.backup.UnsupportedBackupFormatException;
import mx.quest.runway.log.SiteLogService;
import mx.quest.runway.site.Site; import mx.quest.runway.site.Site;
import mx.quest.runway.site.SiteResolver; import mx.quest.runway.site.SiteResolver;
import org.slf4j.Logger; import org.slf4j.Logger;
@@ -50,6 +52,14 @@ import org.springframework.web.servlet.mvc.support.RedirectAttributes;
* A stored backup a delegated holder created stays on the server for an administrator (or the platform operator, on * A stored backup a delegated holder created stays on the server for an administrator (or the platform operator, on
* {@code /__app/backups}) to download or restore. Bound-tenancy only — a tenant can only ever back up or restore its * {@code /__app/backups}) to download or restore. Bound-tenancy only — a tenant can only ever back up or restore its
* own site. * own site.
*
* <p>Every act that took effect is recorded in the site's audit log, under the actions the application console
* records for the same acts in the platform's activity log: {@code backup.saved} and {@code backup.deleted} naming
* the backup, {@code backup.downloaded} ({@code full}, {@code transfer}, or {@code full} and the stored backup's
* name, when it is handed over; a HEAD request, or a range resuming one, is not a new download) and
* {@code site.restored} (the backup's name, or {@code (upload)}). Who
* took a copy of the site, or replaced it, is what an administrator reviewing the site needs to know. A refused
* act, or one that failed before changing anything, writes nothing.
*/ */
@Controller @Controller
public class TenantBackupsController { public class TenantBackupsController {
@@ -61,10 +71,15 @@ public class TenantBackupsController {
private final TenantAuthority tenantAuthority; private final TenantAuthority tenantAuthority;
private final MessageSource messages; private final MessageSource messages;
private final mx.quest.runway.backup.BackupProperties policy; private final mx.quest.runway.backup.BackupProperties policy;
private final mx.quest.runway.platform.PlatformSettingsStore platform;
private final SiteLogService siteLog;
public TenantBackupsController(SiteResolver siteResolver, BackupService backups, TenantAuthority tenantAuthority, public TenantBackupsController(SiteResolver siteResolver, BackupService backups, TenantAuthority tenantAuthority,
@Qualifier("operatorAwareMessageSource") MessageSource messages, @Qualifier("operatorAwareMessageSource") MessageSource messages,
mx.quest.runway.backup.BackupProperties policy) { mx.quest.runway.backup.BackupProperties policy,
mx.quest.runway.platform.PlatformSettingsStore platform, SiteLogService siteLog) {
this.siteLog = siteLog;
this.platform = platform;
this.policy = policy; this.policy = policy;
this.siteResolver = siteResolver; this.siteResolver = siteResolver;
this.backups = backups; this.backups = backups;
@@ -84,6 +99,12 @@ public class TenantBackupsController {
model.addAttribute("backupPolicyKeepKey", "op.backups.policy.keep." model.addAttribute("backupPolicyKeepKey", "op.backups.policy.keep."
+ (count > 0 ? "count" : "all") + (days > 0 ? "Days" : "")); + (count > 0 ? "count" : "all") + (days > 0 ? "Days" : ""));
model.addAttribute("transferOmissions", transferOmissions(site.id())); model.addAttribute("transferOmissions", transferOmissions(site.id()));
// After a restore: how the site is reached, for review. A restore from this console keeps the hosts and base URL
// (only the application console changes them), so they are shown as they stand, without an editor.
if (Boolean.TRUE.equals(model.getAttribute(AppBackupsController.REVIEW_HOSTS))) {
model.addAttribute("reviewSite", site);
model.addAttribute("reviewIsDefault", platform.get().defaultSite().filter(site.id()::equals).isPresent());
}
// Restore is destructive + master-only; hide its affordances from a non-master (the controller still enforces). // Restore is destructive + master-only; hide its affordances from a non-master (the controller still enforces).
boolean admin = tenantAuthority.isTenantAdmin(authentication, site.id()); boolean admin = tenantAuthority.isTenantAdmin(authentication, site.id());
model.addAttribute("canRestore", admin); model.addAttribute("canRestore", admin);
@@ -111,10 +132,11 @@ public class TenantBackupsController {
/** Save a new backup on the server. */ /** Save a new backup on the server. */
@PostMapping("/__admin/backups/create") @PostMapping("/__admin/backups/create")
@PreAuthorize("@authz.may('MANAGE_BACKUPS')") @PreAuthorize("@authz.may('MANAGE_BACKUPS')")
public String create(RedirectAttributes redirect) { public String create(Authentication authentication, RedirectAttributes redirect) {
Site site = boundTenancy(); Site site = boundTenancy();
try { try {
String name = backups.create(site.id()); String name = backups.create(site.id());
siteLog.audit(site.id(), actor(authentication), "backup.saved", name);
redirect.addFlashAttribute("flash", message("op.backups.created", "Backup created.") + " " + name); redirect.addFlashAttribute("flash", message("op.backups.created", "Backup created.") + " " + name);
} catch (IOException e) { } catch (IOException e) {
log.warn("backup create failed for {}", site.id(), e); log.warn("backup create failed for {}", site.id(), e);
@@ -129,13 +151,18 @@ public class TenantBackupsController {
*/ */
@GetMapping("/__admin/backups/download") @GetMapping("/__admin/backups/download")
@PreAuthorize("@authz.may('MANAGE_BACKUPS')") @PreAuthorize("@authz.may('MANAGE_BACKUPS')")
public void download(Authentication authentication, HttpServletResponse response) throws IOException { public void download(Authentication authentication, HttpServletRequest request, HttpServletResponse response)
throws IOException {
Site site = boundTenancy(); Site site = boundTenancy();
tenantAuthority.require(authentication, site.id()); tenantAuthority.require(authentication, site.id());
response.setContentType("application/zip"); response.setContentType("application/zip");
response.setHeader(HttpHeaders.CONTENT_DISPOSITION, response.setHeader(HttpHeaders.CONTENT_DISPOSITION,
"attachment; filename=\"" + site.id() + "-backup-" + LocalDate.now() + ".zip\""); "attachment; filename=\"" + site.id() + "-backup-" + LocalDate.now() + ".zip\"");
if (isHead(request)) {
return; // the headers only: no archive is built, and nothing is downloaded
}
backups.backup(site.id(), response.getOutputStream()); backups.backup(site.id(), response.getOutputStream());
siteLog.audit(site.id(), actor(authentication), "backup.downloaded", "full");
} }
@@ -149,12 +176,17 @@ public class TenantBackupsController {
*/ */
@GetMapping("/__admin/backups/download-transfer") @GetMapping("/__admin/backups/download-transfer")
@PreAuthorize("@authz.may('MANAGE_BACKUPS')") @PreAuthorize("@authz.may('MANAGE_BACKUPS')")
public void downloadForTransfer(HttpServletResponse response) throws IOException { public void downloadForTransfer(Authentication authentication, HttpServletRequest request,
HttpServletResponse response) throws IOException {
Site site = boundTenancy(); Site site = boundTenancy();
response.setContentType("application/zip"); response.setContentType("application/zip");
response.setHeader(HttpHeaders.CONTENT_DISPOSITION, response.setHeader(HttpHeaders.CONTENT_DISPOSITION,
"attachment; filename=\"" + site.id() + "-transfer-" + LocalDate.now() + ".zip\""); "attachment; filename=\"" + site.id() + "-transfer-" + LocalDate.now() + ".zip\"");
if (isHead(request)) {
return;
}
backups.backup(site.id(), response.getOutputStream(), BackupService.BackupPurpose.TRANSFER); backups.backup(site.id(), response.getOutputStream(), BackupService.BackupPurpose.TRANSFER);
siteLog.audit(site.id(), actor(authentication), "backup.downloaded", "transfer");
} }
/** /**
@@ -164,7 +196,8 @@ public class TenantBackupsController {
*/ */
@GetMapping("/__admin/backups/{name}/download") @GetMapping("/__admin/backups/{name}/download")
@PreAuthorize("@authz.may('MANAGE_BACKUPS')") @PreAuthorize("@authz.may('MANAGE_BACKUPS')")
public ResponseEntity<Resource> downloadStored(@PathVariable String name, Authentication authentication) { public ResponseEntity<Resource> downloadStored(@PathVariable String name, Authentication authentication,
HttpServletRequest request) {
Site site = boundTenancy(); Site site = boundTenancy();
tenantAuthority.require(authentication, site.id()); tenantAuthority.require(authentication, site.id());
Path file = backups.file(site.id(), name) Path file = backups.file(site.id(), name)
@@ -172,6 +205,12 @@ public class TenantBackupsController {
// Name the download from the RESOLVED file, never the raw path variable — the header must not echo // Name the download from the RESOLVED file, never the raw path variable — the header must not echo
// attacker-controlled input (CRLF / quotes) even though the store already rejects it as an unsafe id. // attacker-controlled input (CRLF / quotes) even though the store already rejects it as an unsafe id.
String filename = file.getFileName().toString(); String filename = file.getFileName().toString();
// Recorded when the file is handed over, before it streams (after this method returns, with HEAD and
// resumable ranges handled by the framework). A HEAD request takes no copy, and a range that does not start
// at the beginning continues a download already recorded, so neither writes a line.
if (!isHead(request) && startsAtTheBeginning(request.getHeader(HttpHeaders.RANGE))) {
siteLog.audit(site.id(), actor(authentication), "backup.downloaded", "full " + filename);
}
return ResponseEntity.ok() return ResponseEntity.ok()
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + filename + "\"") .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + filename + "\"")
.contentType(MediaType.parseMediaType("application/zip")) .contentType(MediaType.parseMediaType("application/zip"))
@@ -181,9 +220,11 @@ public class TenantBackupsController {
/** Delete a stored backup. */ /** Delete a stored backup. */
@PostMapping("/__admin/backups/{name}/delete") @PostMapping("/__admin/backups/{name}/delete")
@PreAuthorize("@authz.may('MANAGE_BACKUPS')") @PreAuthorize("@authz.may('MANAGE_BACKUPS')")
public String delete(@PathVariable String name, RedirectAttributes redirect) { public String delete(@PathVariable String name, Authentication authentication, RedirectAttributes redirect) {
Site site = boundTenancy(); Site site = boundTenancy();
backups.delete(site.id(), name); if (backups.delete(site.id(), name)) {
siteLog.audit(site.id(), actor(authentication), "backup.deleted", name);
}
redirect.addFlashAttribute("flash", message("op.backups.deleted", "Backup deleted.")); redirect.addFlashAttribute("flash", message("op.backups.deleted", "Backup deleted."));
return "redirect:/__admin/backups"; return "redirect:/__admin/backups";
} }
@@ -195,7 +236,9 @@ public class TenantBackupsController {
tenantAuthority.require(authentication, site.id()); tenantAuthority.require(authentication, site.id());
try { try {
backups.restoreStored(site.id(), name, true); // a site manager never changes how the site is reached backups.restoreStored(site.id(), name, true); // a site manager never changes how the site is reached
siteLog.audit(site.id(), actor(authentication), "site.restored", name);
redirect.addFlashAttribute("flash", message("op.backups.restored", "Site restored from the backup.")); redirect.addFlashAttribute("flash", message("op.backups.restored", "Site restored from the backup."));
redirect.addFlashAttribute(AppBackupsController.REVIEW_HOSTS, Boolean.TRUE);
} catch (UnsupportedBackupFormatException e) { } catch (UnsupportedBackupFormatException e) {
redirect.addFlashAttribute("error", newerFormat(e)); redirect.addFlashAttribute("error", newerFormat(e));
} catch (IOException | RuntimeException e) { } catch (IOException | RuntimeException e) {
@@ -217,7 +260,9 @@ public class TenantBackupsController {
} }
try (InputStream in = file.getInputStream()) { try (InputStream in = file.getInputStream()) {
backups.restore(site.id(), in, true); // a site manager never changes how the site is reached backups.restore(site.id(), in, true); // a site manager never changes how the site is reached
siteLog.audit(site.id(), actor(authentication), "site.restored", "(upload)");
redirect.addFlashAttribute("flash", message("op.backups.restored", "Site restored from the backup.")); redirect.addFlashAttribute("flash", message("op.backups.restored", "Site restored from the backup."));
redirect.addFlashAttribute(AppBackupsController.REVIEW_HOSTS, Boolean.TRUE);
} catch (UnsupportedBackupFormatException e) { } catch (UnsupportedBackupFormatException e) {
redirect.addFlashAttribute("error", newerFormat(e)); redirect.addFlashAttribute("error", newerFormat(e));
} catch (IOException | RuntimeException e) { } catch (IOException | RuntimeException e) {
@@ -227,6 +272,20 @@ public class TenantBackupsController {
return "redirect:/__admin/backups"; return "redirect:/__admin/backups";
} }
/** Whether a {@code Range} header (or none) asks for the file from its first byte. */
static boolean startsAtTheBeginning(String range) {
return range == null || range.isBlank() || range.strip().replace(" ", "").startsWith("bytes=0-");
}
/** A HEAD request (a link checker, a preview) asks for the headers only: it builds and records nothing. */
static boolean isHead(HttpServletRequest request) {
return "HEAD".equalsIgnoreCase(request.getMethod());
}
private static String actor(Authentication authentication) {
return authentication == null ? "unknown" : authentication.getName();
}
private String message(String code, String fallback) { private String message(String code, String fallback) {
return messages.getMessage(code, null, fallback, LocaleContextHolder.getLocale()); return messages.getMessage(code, null, fallback, LocaleContextHolder.getLocale());
} }
@@ -6,14 +6,16 @@ import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse; import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException; import java.io.IOException;
import java.util.Set; import java.util.Set;
import mx.quest.runway.web.FilterOrder;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.ObjectProvider; import org.springframework.beans.factory.ObjectProvider;
import org.springframework.boot.servlet.filter.OrderedFormContentFilter; import org.springframework.boot.servlet.filter.OrderedFormContentFilter;
/** /**
* Spring Boot's {@code FormContentFilter}, minus plugin routes. Boot registers that filter outermost (order * Spring Boot's {@code FormContentFilter}, minus plugin routes. Boot registers that filter early (order
* {@code -9900}) so a {@code PUT}/{@code PATCH}/{@code DELETE} form body becomes request parameters for * {@code -9900}; Runway places it at {@link FilterOrder#CORE_FORM_CONTENT}, inside the access log and the site
* binding, so its {@code 413} is logged for the site) so a {@code PUT}/{@code PATCH}/{@code DELETE} form body becomes request parameters for
* {@code @RequestParam}; it does that by <b>reading the body</b>, so a plugin route used to receive an empty * {@code @RequestParam}; it does that by <b>reading the body</b>, so a plugin route used to receive an empty
* {@code RouteRequest.form()} and {@code body()} for those methods — and a {@code _csrf} field in such a body was not * {@code RouteRequest.form()} and {@code body()} for those methods — and a {@code _csrf} field in such a body was not
* found either ({@code RouteBodyMethodsE2ETest}). A request whose method and path match a registered route * found either ({@code RouteBodyMethodsE2ETest}). A request whose method and path match a registered route
@@ -51,6 +53,7 @@ public class RouteAwareFormContentFilter extends OrderedFormContentFilter {
public RouteAwareFormContentFilter(ObjectProvider<EndpointContributorRegistry> registry, long cap) { public RouteAwareFormContentFilter(ObjectProvider<EndpointContributorRegistry> registry, long cap) {
this.registry = registry; this.registry = registry;
this.cap = Math.max(0, cap); this.cap = Math.max(0, cap);
setOrder(FilterOrder.CORE_FORM_CONTENT);
} }
@Override @Override
@@ -1,6 +1,5 @@
package mx.quest.runway.log; package mx.quest.runway.log;
import mx.quest.runway.site.SiteResolver;
import mx.quest.runway.web.FilterOrder; import mx.quest.runway.web.FilterOrder;
import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean; import org.springframework.boot.web.servlet.FilterRegistrationBean;
@@ -8,19 +7,18 @@ import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
/** /**
* Registers {@link AccessLogFilter} as the innermost filter ({@link FilterOrder#CORE_ACCESS_LOG}), so its * Registers {@link AccessLogFilter} at {@link FilterOrder#CORE_ACCESS_LOG}, just inside the abuse floor, so it logs
* post-phase observes the final response status of every public request, and enables {@link LogProperties}. * every public request the floor lets through with its final status, and enables {@link LogProperties}.
*/ */
@Configuration(proxyBeanMethods = false) @Configuration(proxyBeanMethods = false)
@EnableConfigurationProperties(LogProperties.class) @EnableConfigurationProperties(LogProperties.class)
public class AccessLogConfig { public class AccessLogConfig {
@Bean @Bean
public FilterRegistrationBean<AccessLogFilter> accessLogFilterRegistration(SiteResolver siteResolver, public FilterRegistrationBean<AccessLogFilter> accessLogFilterRegistration(SiteLogService siteLog,
SiteLogService siteLog,
LogProperties properties) { LogProperties properties) {
FilterRegistrationBean<AccessLogFilter> registration = new FilterRegistrationBean<>( FilterRegistrationBean<AccessLogFilter> registration = new FilterRegistrationBean<>(
new AccessLogFilter(siteResolver, siteLog, properties.isAccessLogUserAgent())); new AccessLogFilter(siteLog, properties.isAccessLogUserAgent()));
registration.setOrder(FilterOrder.CORE_ACCESS_LOG); registration.setOrder(FilterOrder.CORE_ACCESS_LOG);
registration.addUrlPatterns("/*"); registration.addUrlPatterns("/*");
registration.setName("accessLogFilter"); registration.setName("accessLogFilter");
@@ -5,8 +5,7 @@ import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse; import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException; import java.io.IOException;
import mx.quest.runway.site.Site; import mx.quest.runway.site.SiteContextFilter;
import mx.quest.runway.site.SiteResolver;
import mx.quest.runway.web.ClientIp; import mx.quest.runway.web.ClientIp;
import mx.quest.runway.web.LogSafe; import mx.quest.runway.web.LogSafe;
import mx.quest.runway.web.RequestPaths; import mx.quest.runway.web.RequestPaths;
@@ -15,9 +14,16 @@ import org.slf4j.LoggerFactory;
import org.springframework.web.filter.OncePerRequestFilter; import org.springframework.web.filter.OncePerRequestFilter;
/** /**
* The innermost filter ({@code FilterOrder.CORE_ACCESS_LOG}): it logs one event per <b>public</b> request from * The access log: one event per <b>public</b> request, written from its {@code post} phase, once every inner filter
* its {@code post} phase, so it observes the <b>final</b> status set by every inner filter and the handler. * and the handler have finished, so the status it records is the one the request was answered with. (The exception:
* Being innermost is the whole point — an outer position would log a not-yet-decided status. * an exception escaping the chain, which only a plugin's own MVC controller can let through, is logged with the
* status set before it, while the container answers {@code 500}.) It sits at {@code FilterOrder.CORE_ACCESS_LOG}, just inside the abuse floor and outside every
* other filter, so it sees every request the floor lets through however it is answered: by a page, an endpoint
* route, Spring Security (a login attempt, a CSRF {@code 403}), a tenant gate (a suspended or over-quota site's
* {@code 503}), a refused slow body ({@code 408}) or an oversized form refused unread ({@code 413}). A filter that answers without calling the chain is invisible
* to every filter inside it, which is why this one is not innermost: there, until 1.1.2, a password-guessing run
* against a site's login left no line at all. Rejections by the floor itself are reported, throttled, by
* {@code EdgeRejectionRecorder} instead.
* *
* <p>It is a <b>public-traffic</b> log, not an audit trail: it skips the internal surfaces (anything under * <p>It is a <b>public-traffic</b> log, not an audit trail: it skips the internal surfaces (anything under
* {@code /__…} — the app/admin/preview/assets/CSP-report consoles — plus {@code /app/…} and {@code /actuator}), * {@code /__…} — the app/admin/preview/assets/CSP-report consoles — plus {@code /app/…} and {@code /actuator}),
@@ -25,29 +31,24 @@ import org.springframework.web.filter.OncePerRequestFilter;
* {@link ClientIp#of} (never a raw forwarded header). * {@link ClientIp#of} (never a raw forwarded header).
* *
* <p>It emits to two sinks: the operator's {@code runway.access} SLF4J logger (the whole-platform stream), and — * <p>It emits to two sinks: the operator's {@code runway.access} SLF4J logger (the whole-platform stream), and —
* when a site is bound (a public tenant request) — that site's own {@link SiteLogService#access per-site access * when a site answered (a public tenant request) — that site's own {@link SiteLogService#access per-site access
* log}. This filter runs <em>inside</em> the site-context filter, so the tenant binding is still live in the * log}. The site is read from the {@link SiteContextFilter#SITE_ID_ATTRIBUTE request attribute} the site-context
* post phase. * filter leaves, not from {@code SiteResolver.current()}: that filter is inner of this one and has cleared its
* thread binding by the time this {@code post} runs. A request refused before the site is resolved has no site and
* goes to the platform log only.
*/ */
public class AccessLogFilter extends OncePerRequestFilter { public class AccessLogFilter extends OncePerRequestFilter {
private static final Logger log = LoggerFactory.getLogger("runway.access"); private static final Logger log = LoggerFactory.getLogger("runway.access");
private final SiteResolver siteResolver;
private final SiteLogService siteLog; private final SiteLogService siteLog;
private final boolean logUserAgent; private final boolean logUserAgent;
public AccessLogFilter(SiteResolver siteResolver, SiteLogService siteLog, boolean logUserAgent) { public AccessLogFilter(SiteLogService siteLog, boolean logUserAgent) {
this.siteResolver = siteResolver;
this.siteLog = siteLog; this.siteLog = siteLog;
this.logUserAgent = logUserAgent; this.logUserAgent = logUserAgent;
} }
/** Pre-{@code logUserAgent} form, kept so existing call sites (and tests) compile unchanged: agent off. */
public AccessLogFilter(SiteResolver siteResolver, SiteLogService siteLog) {
this(siteResolver, siteLog, false);
}
@Override @Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
throws ServletException, IOException { throws ServletException, IOException {
@@ -69,9 +70,8 @@ public class AccessLogFilter extends OncePerRequestFilter {
log.info("{} {} {} -> {} ({}ms)", ip, request.getMethod(), log.info("{} {} {} -> {} ({}ms)", ip, request.getMethod(),
request.getRequestURI(), response.getStatus(), millis); request.getRequestURI(), response.getStatus(), millis);
} }
Site site = siteResolver.current().orElse(null); if (request.getAttribute(SiteContextFilter.SITE_ID_ATTRIBUTE) instanceof String siteId) {
if (site != null) { siteLog.access(siteId, ip, request.getMethod(), request.getRequestURI(), response.getStatus());
siteLog.access(site.id(), ip, request.getMethod(), request.getRequestURI(), response.getStatus());
} }
} }
} }
@@ -62,6 +62,14 @@ public class SiteLogService {
private final SiteLogConfigService configs; private final SiteLogConfigService configs;
private final LogProperties props; private final LogProperties props;
private final BlockingQueue<LogEvent> queue; private final BlockingQueue<LogEvent> queue;
/**
* Queue slots only audit events may take. Access and audit lines share the queue, and a flood that gets past the
* protection edge (a credential-stuffing run, two events per attempt) would otherwise drop audit lines, the
* {@code login.failure} records that are the evidence of that very attack, as often as access lines. With an
* eighth of the queue held back, access lines are dropped first.
*/
private final int auditReserve;
static final int AUDIT_RESERVE_DIVISOR = 8;
private final AtomicLong dropped = new AtomicLong(); private final AtomicLong dropped = new AtomicLong();
private static final long DROP_WARN_INTERVAL_MS = 60_000L; private static final long DROP_WARN_INTERVAL_MS = 60_000L;
private volatile long lastDropWarnAt; private volatile long lastDropWarnAt;
@@ -73,7 +81,9 @@ public class SiteLogService {
this.layout = layout; this.layout = layout;
this.configs = configs; this.configs = configs;
this.props = props; this.props = props;
this.queue = new ArrayBlockingQueue<>(Math.max(16, props.getQueueCapacity())); int capacity = Math.max(16, props.getQueueCapacity());
this.queue = new ArrayBlockingQueue<>(capacity);
this.auditReserve = capacity / AUDIT_RESERVE_DIVISOR;
} }
@PostConstruct @PostConstruct
@@ -113,6 +123,16 @@ public class SiteLogService {
List.of(clean(actor), clean(action), clean(detail)))); List.of(clean(actor), clean(action), clean(detail))));
} }
/** Accepts events without starting the writer, so a test can fill the queue. */
void acceptWithoutWriting() {
running = true;
}
/** Events waiting to be written (tests). */
int queued() {
return queue.size();
}
/** The number of events dropped because the queue was full (best-effort observability). */ /** The number of events dropped because the queue was full (best-effort observability). */
public long droppedCount() { public long droppedCount() {
return dropped.get(); return dropped.get();
@@ -219,7 +239,9 @@ public class SiteLogService {
if (!running) { if (!running) {
return; return;
} }
if (!queue.offer(event)) { boolean accepted = event.kind() == LogKind.ACCESS && queue.remainingCapacity() <= auditReserve
? false : queue.offer(event);
if (!accepted) {
long total = dropped.incrementAndGet(); long total = dropped.incrementAndGet();
// A saturated queue silently losing events (audit lines included) is exactly what an operator needs // A saturated queue silently losing events (audit lines included) is exactly what an operator needs
// told — but the drop path must stay non-blocking and un-spammy, so warn at most once a minute. // told — but the drop path must stay non-blocking and un-spammy, so warn at most once a minute.
@@ -13,6 +13,8 @@ import mx.quest.runway.spi.service.ContentChanges;
import mx.quest.runway.spi.service.PluginSettings; import mx.quest.runway.spi.service.PluginSettings;
import mx.quest.runway.spi.service.PluginSiteFiles; import mx.quest.runway.spi.service.PluginSiteFiles;
import mx.quest.runway.storage.StorageLayout; import mx.quest.runway.storage.StorageLayout;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InjectionPoint; import org.springframework.beans.factory.InjectionPoint;
import org.springframework.beans.factory.ObjectProvider; import org.springframework.beans.factory.ObjectProvider;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
@@ -49,6 +51,8 @@ import org.springframework.core.env.Environment;
@Configuration(proxyBeanMethods = false) @Configuration(proxyBeanMethods = false)
public class PluginScopedServices { public class PluginScopedServices {
private static final Logger log = LoggerFactory.getLogger(PluginScopedServices.class);
private final PluginOwnership ownership; private final PluginOwnership ownership;
private final SitePluginConfigService siteConfig; private final SitePluginConfigService siteConfig;
private final SecretCipher cipher; private final SecretCipher cipher;
@@ -99,7 +103,26 @@ public class PluginScopedServices {
"kernel code reads per-site plugin settings through SitePluginConfigService"); "kernel code reads per-site plugin settings through SitePluginConfigService");
return settings.computeIfAbsent(plugin.id(), id -> new PluginSettingsImpl(id, return settings.computeIfAbsent(plugin.id(), id -> new PluginSettingsImpl(id,
plugin.descriptor().siteSettings(), plugin.descriptor().settings(), plugin.descriptor().siteSettings(), plugin.descriptor().settings(),
key -> environment == null ? null : environment.getProperty(key), siteConfig, cipher)); key -> environment == null ? null : environment.getProperty(key), key -> savedApp(id, key),
siteConfig, cipher));
}
/**
* One saved app-level value in its stored form; {@code null} when unset, without a layout, or when the file cannot
* be read or parsed. A hand-edited file with a syntax error must not turn the plugin's check into an error page,
* and the parser's message is not logged: it can quote the offending line, which may hold a password.
*/
private String savedApp(String pluginId, String key) {
if (layout == null) {
return null;
}
try {
return PluginSettingsService.saved(layout, pluginId).get(key);
} catch (RuntimeException e) {
log.warn("plugin '{}': its saved settings file could not be read ({})", pluginId,
e.getClass().getSimpleName());
return null;
}
} }
/** {@link PluginSiteFiles} bound to the injecting plugin's subtree {@code sites/<id>/plugins/<pluginId>/}. */ /** {@link PluginSiteFiles} bound to the injecting plugin's subtree {@code sites/<id>/plugins/<pluginId>/}. */
@@ -174,8 +174,20 @@ public class PluginSettingsService {
// ---- file I/O (nested YAML under runway.plugin.<id>) ------------------------------------------------ // ---- file I/O (nested YAML under runway.plugin.<id>) ------------------------------------------------
/** Flat map of {@code <settingKey> → stored string value} read from the file (empty if absent/unreadable). */ /** Flat map of {@code <settingKey> → stored string value} read from the file (empty if absent/unreadable). */
@SuppressWarnings("unchecked")
private Map<String, String> readSubtree(String pluginId) { private Map<String, String> readSubtree(String pluginId) {
return saved(layout, pluginId);
}
/**
* One plugin's app-level settings as saved in {@code external/plugin-settings/<id>.yml}, flat
* {@code <settingKey> → stored string value}: empty when the file is absent. Secrets stay in their stored form.
* What {@code PluginSettings.savedApp} reads, so it and the form never disagree on what is saved.
*
* @throws UncheckedIOException when the file exists but cannot be read
* @throws RuntimeException the YAML parser's own exception when the file is not valid YAML
*/
@SuppressWarnings("unchecked")
public static Map<String, String> saved(StorageLayout layout, String pluginId) {
Path file = layout.pluginSettingsFile(pluginId); // traversal-safe Path file = layout.pluginSettingsFile(pluginId); // traversal-safe
if (!Files.isRegularFile(file)) { if (!Files.isRegularFile(file)) {
return Map.of(); return Map.of();
@@ -41,6 +41,7 @@ public final class PluginSettingsImpl implements PluginSettings {
private final Map<String, PluginSettingDef> schema; private final Map<String, PluginSettingDef> schema;
private final Map<String, PluginSettingDef> appSchema; private final Map<String, PluginSettingDef> appSchema;
private final Function<String, String> appValues; private final Function<String, String> appValues;
private final Function<String, String> savedAppValues;
private final SitePluginConfigService config; private final SitePluginConfigService config;
private final SecretCipher cipher; private final SecretCipher cipher;
private final Map<String, Memo> memo = new ConcurrentHashMap<>(); private final Map<String, Memo> memo = new ConcurrentHashMap<>();
@@ -74,6 +75,24 @@ public final class PluginSettingsImpl implements PluginSettings {
public PluginSettingsImpl(String pluginId, List<PluginSettingDef> siteSettings, List<PluginSettingDef> appSettings, public PluginSettingsImpl(String pluginId, List<PluginSettingDef> siteSettings, List<PluginSettingDef> appSettings,
Function<String, String> appValues, SitePluginConfigService config, Function<String, String> appValues, SitePluginConfigService config,
SecretCipher cipher) { SecretCipher cipher) {
this(pluginId, siteSettings, appSettings, appValues, key -> null, config, cipher);
}
/**
* @param pluginId the plugin this instance answers for
* @param siteSettings that plugin's declared {@code siteSettings:} schema
* @param appSettings that plugin's declared app-level {@code settings:} schema
* @param appValues resolves a full property key ({@code runway.plugin.<id>.<key>}) to the value the
* running environment holds, or {@code null}
* @param savedAppValues resolves a setting key to the value saved in the plugin's app-level settings file now,
* in its stored form, or {@code null}
* @param config the per-site settings store
* @param cipher decrypts {@code ENC(...)} secrets
*/
public PluginSettingsImpl(String pluginId, List<PluginSettingDef> siteSettings, List<PluginSettingDef> appSettings,
Function<String, String> appValues, Function<String, String> savedAppValues,
SitePluginConfigService config, SecretCipher cipher) {
this.savedAppValues = Objects.requireNonNull(savedAppValues, "savedAppValues");
this.pluginId = Objects.requireNonNull(pluginId, "pluginId"); this.pluginId = Objects.requireNonNull(pluginId, "pluginId");
this.schema = byKey(siteSettings); this.schema = byKey(siteSettings);
this.appSchema = byKey(appSettings); this.appSchema = byKey(appSettings);
@@ -166,6 +185,29 @@ public final class PluginSettingsImpl implements PluginSettings {
PathSafety.KEY_SEPARATOR + "app" + PathSafety.KEY_SEPARATOR + key, key); PathSafety.KEY_SEPARATOR + "app" + PathSafety.KEY_SEPARATOR + key, key);
} }
/**
* A key this plugin declared in its own app-level {@code settings:}, as saved in its settings file now: the saved
* value when not blank (a secret decrypted), else a non-secret's declared default. The file is read on each call,
* which suits the one use, checking settings before the restart that applies them.
*/
@Override
public Optional<String> savedApp(String key) {
PluginSettingDef def = key == null ? null : appSchema.get(key);
if (def == null) {
return Optional.empty();
}
String raw = savedAppValues.apply(key);
if (isSecret(def)) {
return reveal(raw, "the application (saved, not yet applied)",
PathSafety.KEY_SEPARATOR + "saved" + PathSafety.KEY_SEPARATOR + key, key);
}
if (raw != null && !raw.isBlank()) {
return Optional.of(raw);
}
Object fallback = def.defaultValue();
return fallback == null ? Optional.empty() : Optional.of(String.valueOf(fallback));
}
/** A stored secret in clear: empty when blank or undecryptable, a non-{@code ENC(...)} value unchanged. */ /** A stored secret in clear: empty when blank or undecryptable, a non-{@code ENC(...)} value unchanged. */
private Optional<String> reveal(String value, String scope, String warnKey, String key) { private Optional<String> reveal(String value, String scope, String warnKey, String key) {
if (value == null || value.isBlank()) { if (value == null || value.isBlank()) {
@@ -15,9 +15,9 @@ import org.slf4j.LoggerFactory;
* <h2>The blind spot this closes</h2> * <h2>The blind spot this closes</h2>
* {@link EdgeRejectFilter} sits at {@code FilterOrder.CORE_PROTECTION}, the outermost slot after the forwarded * {@link EdgeRejectFilter} sits at {@code FilterOrder.CORE_PROTECTION}, the outermost slot after the forwarded
* header gate, and a reject <b>does not call the chain</b>. {@code AccessLogFilter} sits at * header gate, and a reject <b>does not call the chain</b>. {@code AccessLogFilter} sits at
* {@code CORE_ACCESS_LOG}, the innermost. So every edge {@code 403}/{@code 429} short-circuits <i>before</i> * {@code CORE_ACCESS_LOG}, inside the floor (on purpose: see the throttling below). So every edge
* anything logs it: the request appears in no log anywhere in the product, and the access log never carried a * {@code 403}/{@code 429} short-circuits <i>before</i> anything logs it: without this recorder the request
* {@code User-Agent} to begin with. The practical result was that nobody could answer either half of the * appears in no log anywhere in the product, and the access log carries a {@code User-Agent} only when asked to. The practical result was that nobody could answer either half of the
* obvious question — <i>was a crawler throttled</i>, and <i>why was this request rejected</i>. * obvious question — <i>was a crawler throttled</i>, and <i>why was this request rejected</i>.
* *
* <p>A rejection is also emitted <b>before</b> {@code CORE_SITE_CONTEXT}, so there is no resolved site and it * <p>A rejection is also emitted <b>before</b> {@code CORE_SITE_CONTEXT}, so there is no resolved site and it
@@ -20,6 +20,7 @@ import org.springframework.core.Ordered;
* <pre> * <pre>
* CORE_FORWARDED Integer.MIN_VALUE EDGE_INGRESS TrustedForwardedHeaderFilter (gates X-Forwarded-*) * CORE_FORWARDED Integer.MIN_VALUE EDGE_INGRESS TrustedForwardedHeaderFilter (gates X-Forwarded-*)
* CORE_PROTECTION MIN_VALUE + 1 EDGE_INGRESS EdgeRejectFilter (the O(1) reject seam) * CORE_PROTECTION MIN_VALUE + 1 EDGE_INGRESS EdgeRejectFilter (the O(1) reject seam)
* CORE_ACCESS_LOG -500 (own slot) AccessLogFilter (one line per request past the floor)
* CORE_BANDWIDTH -300 EDGE_EGRESS BandwidthFilter (meters the on-the-wire bytes) * CORE_BANDWIDTH -300 EDGE_EGRESS BandwidthFilter (meters the on-the-wire bytes)
* CORE_SITE_METRICS -290 EDGE_EGRESS SiteRequestMetricsFilter (per-site request timing) * CORE_SITE_METRICS -290 EDGE_EGRESS SiteRequestMetricsFilter (per-site request timing)
* CORE_COMPRESSION -200 EDGE_EGRESS CompressionFilter (brotli / gzip, one decision) * CORE_COMPRESSION -200 EDGE_EGRESS CompressionFilter (brotli / gzip, one decision)
@@ -30,13 +31,13 @@ import org.springframework.core.Ordered;
* CORE_SITE_RELOAD 56 TENANT SiteReloadFilter (loopback /__reload/**) * CORE_SITE_RELOAD 56 TENANT SiteReloadFilter (loopback /__reload/**)
* CORE_CONSOLE_HOST 57 TENANT ConsoleHostFilter (operator console off site hosts) * CORE_CONSOLE_HOST 57 TENANT ConsoleHostFilter (operator console off site hosts)
* CORE_ROUTE_FORM_CAPTURE 58 TENANT RouteFormCaptureFilter (reads a plugin route's form body) * CORE_ROUTE_FORM_CAPTURE 58 TENANT RouteFormCaptureFilter (reads a plugin route's form body)
* CORE_FORM_CONTENT 59 TENANT RouteAwareFormContentFilter (PUT/PATCH/DELETE forms)
* CORE_SUSPENDED_SITE 60 TENANT SuspendedSiteFilter (503s a suspended tenant) * CORE_SUSPENDED_SITE 60 TENANT SuspendedSiteFilter (503s a suspended tenant)
* CORE_QUARANTINED_SITE 65 TENANT QuarantinedSiteFilter (503s a quarantined admin) * CORE_QUARANTINED_SITE 65 TENANT QuarantinedSiteFilter (503s a quarantined admin)
* CORE_MAINTENANCE 68 TENANT MaintenanceSiteFilter (503s a self-maintenance tenant) * CORE_MAINTENANCE 68 TENANT MaintenanceSiteFilter (503s a self-maintenance tenant)
* CORE_BANDWIDTH_LIMIT 69 TENANT BandwidthLimitFilter (503s a tenant over its quota) * CORE_BANDWIDTH_LIMIT 69 TENANT BandwidthLimitFilter (503s a tenant over its quota)
* CORE_EDGE_MODE 70 TENANT (reserved — read-only edge/replica topology, later) * CORE_EDGE_MODE 70 TENANT (reserved — read-only edge/replica topology, later)
* CORE_SECURITY 100 SECURITY the Spring Security FilterChainProxy * CORE_SECURITY 100 SECURITY the Spring Security FilterChainProxy
* CORE_ACCESS_LOG Integer.MAX_VALUE innermost AccessLogFilter (final status, post-chain)
* </pre> * </pre>
* *
* <h2>Why these values</h2> * <h2>Why these values</h2>
@@ -197,13 +198,33 @@ public final class FilterOrder {
/** /**
* The kernel route dispatcher for {@code EndpointContributor} routes (robots.txt, sitemap, …) — a terminal * The kernel route dispatcher for {@code EndpointContributor} routes (robots.txt, sitemap, …) — a terminal
* application handler, inner of the plugin APPLICATION window so a plugin filter can still wrap it. It * application handler, inner of the plugin APPLICATION window so a plugin filter can still wrap it. It
* short-circuits a matched route, so such responses are not seen by the (inner) access log — endpoint/bot * short-circuits a matched route; the access log, far outside it, still records the answer.
* traffic is a separate category from the public page access log.
*/ */
public static final int CORE_ENDPOINT_DISPATCH = Integer.MAX_VALUE - 100; public static final int CORE_ENDPOINT_DISPATCH = Integer.MAX_VALUE - 100;
/** {@code AccessLogFilter} — innermost, so its post observes the final status after every inner filter. */ /**
public static final int CORE_ACCESS_LOG = Ordered.LOWEST_PRECEDENCE; * {@code AccessLogFilter} — inner of the whole EDGE_INGRESS band (the kernel's reject floor and any plugin
* ingress filter) and outer of everything else, so every request that gets past the abuse floor is logged,
* whoever answers it: a tenant gate's {@code 503}, Spring Security (a login attempt, a CSRF {@code 403}), a
* slow body's {@code 408}, an endpoint route, a page. Its {@code post} runs after every inner filter has
* returned, so the status it reads is final.
*
* <p>Until 1.1.2 it sat innermost ({@code Integer.MAX_VALUE}), and every filter that answered without calling
* the chain answered unseen: a password-guessing run against a site's {@code /login} left no line at all.
* Floor rejections stay out on purpose: a flood the floor turns away in O(1) must not become a flood of log
* writes; {@code EdgeRejectionRecorder} reports them, throttled, under {@code runway.protect}.
*/
public static final int CORE_ACCESS_LOG = -500;
/**
* {@code RouteAwareFormContentFilter} (Boot's {@code FormContentFilter}, which parses a {@code PUT}/{@code PATCH}/
* {@code DELETE} form body into parameters, bounded). Boot's own order is {@code -9900}, outer of the access log,
* where its {@code 413} for an oversized body went unlogged. Here it is inner of the site binding, so the refusal
* is in that site's log too, and inner of {@link #CORE_ROUTE_FORM_CAPTURE}, which must read a route's body
* first; and outer of the tenant gates, every plugin TENANT filter and the security chain, which read
* parameters (the CSRF check above all).
*/
public static final int CORE_FORM_CONTENT = 59;
private FilterOrder() { private FilterOrder() {
} }
@@ -0,0 +1,167 @@
package mx.quest.runway.web;
import java.nio.ByteBuffer;
import org.eclipse.jetty.http.HttpException;
import org.eclipse.jetty.http.HttpStatus;
import org.eclipse.jetty.io.Content;
import org.eclipse.jetty.server.Handler;
import org.eclipse.jetty.server.Request;
import org.eclipse.jetty.server.Response;
import org.eclipse.jetty.util.Callback;
/**
* Refuses a request body that arrives more slowly than a minimum rate, on <b>every</b> read of the body: the
* servlet input stream, form parameters and multipart parts alike.
*
* <p><b>Why a handler of our own.</b> Jetty 12's own minimum request data rate is checked only where a servlet reads
* the body through {@code getInputStream()}. Form parameters ({@code getParameter}, which Spring Security's login
* reads) and multipart parts are parsed through Jetty's core request instead, and that path never checks it, so a
* client could trickle a form for as long as it kept sending something inside each idle interval, holding a request
* thread all the while. Measured on 1.1.0: form and multipart posts dripped at 20 bytes a second were held until the
* 30-second idle timeout. This handler sits under the server and wraps the core request, so every body read passes
* through it.
*
* <p><b>What is measured.</b> Only the time spent <em>waiting for the client</em>: from a read that found no data to
* the next one that did. Time the application spends before or between reads does not count, so a server that is
* slow to read is never blamed. The check keeps a balance: every byte received earns one, every second of waiting
* costs the rate's worth, and the balance is capped at {@link #CREDIT_SECONDS} of the rate, so a body sent fast at
* first cannot buy an hour of dripping later. It runs when data arrives: once the waiting time reaches one second and
* the balance is negative, the read fails with {@code 408 Request Timeout} and so does every later read. A client
* pausing between packets is therefore cut when its next packet arrives, at most one idle timeout later. A chunk that completes the body is never refused: once the client has finished, no thread
* is waiting on it any more, and a small form whose only packet arrived late (a network stall) is not punished for
* it; the body counts as complete at its last chunk or, with a {@code Content-Length}, at its last byte. A client that
* sends nothing at all is left to the connection idle timeout.
*
* <p>The refusal is answered {@code 408} however the application handled the failed read: a form or multipart parser
* would report it as {@code 400}, as if the body were malformed, and code reading the stream itself could leave an
* empty {@code 200} (see {@link RefusalStatusResponse}).
*/
final class RequestBodyRateHandler extends Handler.Wrapper {
/** Waiting shorter than this is never judged: a single network stall must not look like a slow client. */
static final long GRACE_NANOS = 1_000_000_000L;
/**
* The most waiting a body may have banked by arriving fast earlier: 30 seconds' worth of the rate, the connection
* idle timeout's default. Without a cap, a client that sent most of a large body at line speed and then dripped
* the rest could hold the thread for the body's size divided by the rate (16 MiB at 4 KiB/s: over an hour).
*/
static final long CREDIT_SECONDS = 30;
private final long bytesPerSecond;
private final long creditSeconds;
/** @param bytesPerSecond the slowest a body may arrive; must be positive (0 means "do not install") */
RequestBodyRateHandler(long bytesPerSecond) {
this(bytesPerSecond, CREDIT_SECONDS);
}
/** As {@link #RequestBodyRateHandler(long)}, with the credit cap in seconds (tests use a short one). */
RequestBodyRateHandler(long bytesPerSecond, long creditSeconds) {
if (bytesPerSecond <= 0 || creditSeconds <= 0) {
throw new IllegalArgumentException("rate and credit must be positive: " + bytesPerSecond + ", "
+ creditSeconds);
}
this.bytesPerSecond = bytesPerSecond;
this.creditSeconds = creditSeconds;
}
long bytesPerSecond() {
return bytesPerSecond;
}
@Override
public boolean handle(Request request, Response response, Callback callback) throws Exception {
RateCheckedRequest checked = new RateCheckedRequest(request, bytesPerSecond, creditSeconds);
return super.handle(checked, new RefusalStatusResponse(checked, response), callback);
}
/**
* Keeps the refusal's status. A form or multipart parser reports any failed read as {@code 400 Bad Request}
* ("unable to parse form content"), which would tell the client its body was malformed when it was only slow; and
* code that reads the stream itself lets the failure escape as an {@code IOException}, which Jetty handles like a
* client that went away, completing the response with the status it already had ({@code 200}, empty). Once this
* request's body was refused, a client error status set on the response becomes {@code 408}, and so does whatever
* status the response is committed with.
*/
private static final class RefusalStatusResponse extends Response.Wrapper {
private final RateCheckedRequest request;
RefusalStatusResponse(RateCheckedRequest request, Response wrapped) {
super(request, wrapped);
this.request = request;
}
@Override
public void write(boolean last, ByteBuffer content, Callback callback) {
if (request.refused != null && !isCommitted() && getStatus() != HttpStatus.REQUEST_TIMEOUT_408) {
super.setStatus(HttpStatus.REQUEST_TIMEOUT_408);
}
super.write(last, content, callback);
}
@Override
public void setStatus(int code) {
super.setStatus(request.refused != null && code >= 400 && code != HttpStatus.REQUEST_TIMEOUT_408
&& code < 500 ? HttpStatus.REQUEST_TIMEOUT_408 : code);
}
}
/** The request whose body reads are measured. Reads of one request are serial, as Jetty's demand model makes them. */
private static final class RateCheckedRequest extends Request.Wrapper {
private final long bytesPerSecond;
private final long creditCap;
private long received;
private long waitedNanos;
private long waitingSince = -1;
/** Bytes received minus the rate times the time waited, capped at {@link #creditCap}; negative = too slow. */
private long credit;
private Content.Chunk refused;
RateCheckedRequest(Request wrapped, long bytesPerSecond, long creditSeconds) {
super(wrapped);
this.bytesPerSecond = bytesPerSecond;
this.creditCap = bytesPerSecond * creditSeconds;
}
@Override
public Content.Chunk read() {
if (refused != null) {
return refused;
}
Content.Chunk chunk = super.read();
long now = System.nanoTime();
if (chunk == null) {
if (waitingSince < 0) {
waitingSince = now;
}
return null;
}
long waited = 0;
if (waitingSince >= 0) {
waited = now - waitingSince;
waitedNanos += waited;
waitingSince = -1;
}
if (Content.Chunk.isFailure(chunk)) {
return chunk;
}
int bytes = chunk.remaining();
received += bytes;
// Each byte earns credit and each second of waiting costs the rate's worth; earning is capped, so a body
// sent fast at first cannot bank more than CREDIT_SECONDS of waiting for a drip later.
credit = Math.min(creditCap, credit + bytes - bytesPerSecond * (waited / 1_000_000) / 1000);
boolean complete = chunk.isLast() || (getLength() >= 0 && received >= getLength());
if (!complete && waitedNanos >= GRACE_NANOS && credit < 0) {
chunk.release();
refused = Content.Chunk.from(new HttpException.RuntimeException(HttpStatus.REQUEST_TIMEOUT_408,
"request body slower than " + bytesPerSecond + " bytes/s"), true);
return refused;
}
return chunk;
}
}
}
@@ -16,15 +16,22 @@ import org.springframework.context.annotation.Configuration;
/** /**
* Keeps slow clients from holding request threads: a minimum rate for request bodies ({@code * Keeps slow clients from holding request threads: a minimum rate for request bodies ({@code
* runway.http.min-request-data-rate}, bytes per second; Settings → Server settings → Request limits), applied to every * runway.http.min-request-data-rate}, bytes per second; Settings → Server settings → Request limits), applied to every
* connector Jetty has when the server is built. * read of a request body by {@link RequestBodyRateHandler}, installed when the server is built.
* *
* <p><b>Why.</b> A servlet reads a request body on a request thread and blocks while it waits. Jetty's idle timeout * <p><b>Why.</b> A servlet reads a request body on a request thread and blocks while it waits. Jetty's idle timeout
* limits one stalled read, not the whole body, so a client that sends a byte inside every idle interval kept a thread * limits one stalled read, not the whole body, so a client that sends a byte inside every idle interval kept a thread
* for as long as it liked, and a few of them (with uploads allowed up to 256 MB) could take the pool. With a minimum * for as long as it liked, and a few of them (with uploads allowed up to 256 MB) could take the pool. With a minimum
* rate Jetty answers {@code 408 Request Timeout} as soon as the body has arrived more slowly than the rate since its * rate the request is answered {@code 408 Request Timeout} once the body arrives more slowly than the rate; time the
* first byte; time the application spends before reading does not count, because the rate is measured on what has * application spends before reading does not count. Measured on Jetty 12.1.8 with Runway 1.1.1: form, multipart and
* arrived. Measured on Jetty 12.1.8: a client sending one byte a second against 1 KiB/s was cut after about two * stream bodies dripped at 20 bytes a second against 4 KiB/s were answered {@code 408} after two seconds, on both
* seconds, and a server pausing three seconds before reading a body that arrived at once still answered {@code 200}. * login pages and a plugin's form route, and a server pausing three seconds before reading a body that arrived at
* once still answered {@code 200}.
*
* <p><b>One check, under every read.</b> Jetty's own minimum rate is checked only where the body is read through
* {@code getInputStream()}; form parameters and multipart parts are parsed through Jetty's core request and escaped
* it (1.1.0 shipped with that gap: a dripped login form was held until the idle timeout). {@link
* RequestBodyRateHandler} wraps the core request under the server, so every read passes it, and Jetty's own check
* is turned off so that the two cannot race ({@link #apply}).
* *
* <p><b>What it does not cover.</b> Slow header senders cost a connection, not a thread (Jetty parses headers without * <p><b>What it does not cover.</b> Slow header senders cost a connection, not a thread (Jetty parses headers without
* one); a proxy's connection cap is the limit there. A client that reads a response slowly is bounded by the * one); a proxy's connection cap is the limit there. A client that reads a response slowly is bounded by the
@@ -45,21 +52,34 @@ public class SlowClientConfig {
} }
/** /**
* Sets the minimum request data rate on every HTTP configuration of {@code server}'s connectors. * Installs the body-rate check on {@code server}: a {@link RequestBodyRateHandler} directly under the server, and
* Jetty's own minimum request data rate set to {@code 0} on every HTTP configuration of its connectors.
*
* <p>Jetty's own check covers {@code getInputStream()} only, and fires above this handler, so the two raced on
* the stream path: when Jetty's won, the failure escaped as an {@code IOException} that the application chain
* turned into an empty {@code 200} (measured on a plugin route that reads its form from the stream). One check,
* under every read, answers {@code 408} on every path. Boot has set the server's handler before its customizers
* run, and wraps the result in its own statistics handler afterwards.
* *
* @param bytesPerSecond the rate; 0 turns the check off * @param bytesPerSecond the rate; 0 turns the check off
* @return how many HTTP configurations were changed * @return how many HTTP configurations had Jetty's own check set to 0
*/ */
static int apply(Server server, long bytesPerSecond) { static int apply(Server server, long bytesPerSecond) {
int changed = 0; int changed = 0;
for (Connector connector : server.getConnectors()) { for (Connector connector : server.getConnectors()) {
for (ConnectionFactory factory : connector.getConnectionFactories()) { for (ConnectionFactory factory : connector.getConnectionFactories()) {
if (factory instanceof HttpConfiguration.ConnectionFactory http) { if (factory instanceof HttpConfiguration.ConnectionFactory http) {
http.getHttpConfiguration().setMinRequestDataRate(bytesPerSecond); http.getHttpConfiguration().setMinRequestDataRate(0);
changed++; changed++;
} }
} }
} }
if (bytesPerSecond > 0 && server.getHandler() != null
&& !(server.getHandler() instanceof RequestBodyRateHandler)) {
RequestBodyRateHandler rate = new RequestBodyRateHandler(bytesPerSecond);
rate.setHandler(server.getHandler());
server.setHandler(rate);
}
if (bytesPerSecond > 0) { if (bytesPerSecond > 0) {
log.info("request bodies slower than {} bytes/s are refused (runway.http.min-request-data-rate)", log.info("request bodies slower than {} bytes/s are refused (runway.http.min-request-data-rate)",
bytesPerSecond); bytesPerSecond);
@@ -320,10 +320,11 @@ runway:
trusted-cidrs: trusted-cidrs:
- "127.0.0.1/32" - "127.0.0.1/32"
- "::1/128" - "::1/128"
# How slowly a client may send a request body, in bytes per second, before Jetty answers 408 and frees the # How slowly a client may send a request body (any: forms, uploads, raw), in bytes per second, before Runway
# request thread (SlowClientConfig). Measured from the body's first byte on what has arrived, so a server that is # answers 408 and frees the request thread (SlowClientConfig, RequestBodyRateHandler). Only time spent waiting for
# slow to read is never blamed. 4096 is below any real connection; 0 turns the check off. Also on Settings -> # the client counts, so a server that is slow to read is never blamed, and a body that has arrived complete is never
# Server settings -> Request limits. # refused. 4096 is below any real connection; 0 turns the check off. Also on Settings -> Server settings -> Request
# limits.
http: http:
min-request-data-rate: 4096 min-request-data-rate: 4096
# Stored-backup retention (app-level, not tenant-editable). After a site backup is written, its own # Stored-backup retention (app-level, not tenant-editable). After a site backup is written, its own
@@ -633,6 +633,15 @@ op.sites.hosts.hint=Comma-separated. Leave empty to make this site reachable onl
op.sites.base=Base URL op.sites.base=Base URL
op.sites.base.hint=The origin every absolute link of the site is built on: canonical links, the sitemap, structured data, social cards. Leave it empty to use https:// and the first host. Set it when the site is served over http, on another port, or under another of its hosts (www). No path. op.sites.base.hint=The origin every absolute link of the site is built on: canonical links, the sitemap, structured data, social cards. Leave it empty to use https:// and the first host. Set it when the site is served over http, on another port, or under another of its hosts (www). No path.
op.sites.base.row=Links: {0} op.sites.base.row=Links: {0}
op.sites.hosts.short=Hosts
op.restore.review.title=Review how site {0} is reached
op.restore.review.hint=The restore applied the hosts and base URL saved in the backup. Check them, and correct them here if this installation reaches the site differently; saving does what Sites → Edit hosts does.
op.restore.review.noHosts=none: the site is reached only as the catch-all default site
op.restore.review.unreachable=none: no address reaches this site until you give it a host
op.restore.review.noBase=none: there is no host to build it from
op.restore.review.derived=not set, so {0} (https:// and the first host)
op.restore.review.kept.title=How the site is reached
op.restore.review.kept.hint=A restore made here keeps the site's hosts and base URL. Check them: only a platform administrator can change them, on the application console.
op.sites.edit=Edit op.sites.edit=Edit
op.sites.edit.title=Edit site op.sites.edit.title=Edit site
op.sites.edit.locales=Available languages op.sites.edit.locales=Available languages
@@ -1185,6 +1194,7 @@ op.audit.action.site.created-from-backup=Site created from backup
op.audit.action.demo.installed=Demo site installed op.audit.action.demo.installed=Demo site installed
op.audit.action.backup.saved=Backup saved op.audit.action.backup.saved=Backup saved
op.audit.action.backup.deleted=Backup deleted op.audit.action.backup.deleted=Backup deleted
op.audit.action.backup.downloaded=Backup downloaded
op.audit.action.site-template.created=Site template created op.audit.action.site-template.created=Site template created
op.audit.action.site-template.imported=Site template imported op.audit.action.site-template.imported=Site template imported
op.audit.action.site-template.deleted=Site template deleted op.audit.action.site-template.deleted=Site template deleted
@@ -1216,6 +1226,12 @@ op.audit.action.page.unpublished=Page unpublished
op.audit.action.user.created=User created op.audit.action.user.created=User created
op.audit.action.user.password-reset=User password reset op.audit.action.user.password-reset=User password reset
op.audit.action.user.deleted=User deleted op.audit.action.user.deleted=User deleted
op.audit.action.user.updated=User changed
op.audit.action.user.suspended=User suspended
op.audit.action.user.resumed=User resumed
op.audit.action.static.uploaded=Static file uploaded
op.audit.action.static.folder-created=Static folder created
op.audit.action.static.deleted=Static file or folder deleted
op.audit.action.logs.settings-changed=Log settings changed op.audit.action.logs.settings-changed=Log settings changed
op.audit.action.site-config.changed=Site settings changed op.audit.action.site-config.changed=Site settings changed
@@ -1488,7 +1504,7 @@ op.ks.runway.csp.frame-ancestors.help=Which sites may show these pages in a fram
op.ks.runway.endpoints.max-form-bytes=Largest request before sign-in (bytes) op.ks.runway.endpoints.max-form-bytes=Largest request before sign-in (bytes)
op.ks.runway.endpoints.max-form-bytes.help=The most a visitor who is not signed in may send in one request, on any path. Default 262144 (256 KiB). op.ks.runway.endpoints.max-form-bytes.help=The most a visitor who is not signed in may send in one request, on any path. Default 262144 (256 KiB).
op.ks.runway.http.min-request-data-rate=Slowest request body (bytes per second) op.ks.runway.http.min-request-data-rate=Slowest request body (bytes per second)
op.ks.runway.http.min-request-data-rate.help=A request body arriving more slowly is answered 408 Request Timeout, so a client sending a byte now and then cannot hold a request thread. Measured on what has arrived since the body's first byte. Default 4096; 0 turns the check off. op.ks.runway.http.min-request-data-rate.help=A request body arriving more slowly is answered 408 Request Timeout: login and other forms, uploads and raw bodies alike, so a client sending a byte now and then cannot keep a request thread. Only time spent waiting for the client counts, and a body that has arrived complete is never refused. Sending part of a body fast earns at most 30 seconds of waiting. Default 4096; 0 turns the check off.
op.ks.runway.endpoints.max-body-bytes=Largest request to a plugin (bytes) op.ks.runway.endpoints.max-body-bytes=Largest request to a plugin (bytes)
op.ks.runway.endpoints.max-body-bytes.help=The most a signed-in user may send to a plugin's route. Default 10485760 (10 MiB). op.ks.runway.endpoints.max-body-bytes.help=The most a signed-in user may send to a plugin's route. Default 10485760 (10 MiB).
op.ks.spring.servlet.multipart.max-file-size=Largest uploaded file op.ks.spring.servlet.multipart.max-file-size=Largest uploaded file
@@ -634,6 +634,15 @@ op.sites.hosts.hint=Separados por comas. Déjelo vacío para que el sitio solo s
op.sites.base=URL base op.sites.base=URL base
op.sites.base.hint=El origen sobre el que se construyen todos los enlaces absolutos del sitio: enlaces canónicos, el mapa del sitio, los datos estructurados y las tarjetas para redes sociales. Déjelo vacío para usar https:// y el primer host. Fíjelo cuando el sitio se sirva por http, en otro puerto o con otro de sus hosts (www). Sin ruta. op.sites.base.hint=El origen sobre el que se construyen todos los enlaces absolutos del sitio: enlaces canónicos, el mapa del sitio, los datos estructurados y las tarjetas para redes sociales. Déjelo vacío para usar https:// y el primer host. Fíjelo cuando el sitio se sirva por http, en otro puerto o con otro de sus hosts (www). Sin ruta.
op.sites.base.row=Enlaces: {0} op.sites.base.row=Enlaces: {0}
op.sites.hosts.short=Hosts
op.restore.review.title=Revise cómo se llega al sitio {0}
op.restore.review.hint=La restauración aplicó los hosts y la URL base guardados en la copia. Revíselos y corríjalos aquí si esta instalación llega al sitio de otra forma; guardar hace lo mismo que Sitios → Editar hosts.
op.restore.review.noHosts=ninguno: al sitio solo se llega como sitio predeterminado (catch-all)
op.restore.review.unreachable=ninguno: ninguna dirección llega a este sitio hasta que le dé un host
op.restore.review.noBase=ninguna: no hay host con el que construirla
op.restore.review.derived=sin fijar, así que {0} (https:// y el primer host)
op.restore.review.kept.title=Cómo se llega al sitio
op.restore.review.kept.hint=Una restauración hecha aquí conserva los hosts y la URL base del sitio. Revíselos: solo un administrador de la plataforma puede cambiarlos, en la consola de la aplicación.
op.sites.edit=Editar op.sites.edit=Editar
op.sites.edit.title=Editar sitio op.sites.edit.title=Editar sitio
op.sites.edit.locales=Idiomas disponibles op.sites.edit.locales=Idiomas disponibles
@@ -1186,6 +1195,7 @@ op.audit.action.site.created-from-backup=Sitio creado desde una copia de segurid
op.audit.action.demo.installed=Sitio de demostración instalado op.audit.action.demo.installed=Sitio de demostración instalado
op.audit.action.backup.saved=Copia de seguridad guardada op.audit.action.backup.saved=Copia de seguridad guardada
op.audit.action.backup.deleted=Copia de seguridad eliminada op.audit.action.backup.deleted=Copia de seguridad eliminada
op.audit.action.backup.downloaded=Copia de seguridad descargada
op.audit.action.site-template.created=Plantilla de sitio creada op.audit.action.site-template.created=Plantilla de sitio creada
op.audit.action.site-template.imported=Plantilla de sitio importada op.audit.action.site-template.imported=Plantilla de sitio importada
op.audit.action.site-template.deleted=Plantilla de sitio eliminada op.audit.action.site-template.deleted=Plantilla de sitio eliminada
@@ -1217,6 +1227,12 @@ op.audit.action.page.unpublished=Página despublicada
op.audit.action.user.created=Usuario creado op.audit.action.user.created=Usuario creado
op.audit.action.user.password-reset=Contraseña de usuario restablecida op.audit.action.user.password-reset=Contraseña de usuario restablecida
op.audit.action.user.deleted=Usuario eliminado op.audit.action.user.deleted=Usuario eliminado
op.audit.action.user.updated=Usuario modificado
op.audit.action.user.suspended=Usuario suspendido
op.audit.action.user.resumed=Usuario reactivado
op.audit.action.static.uploaded=Archivo estático subido
op.audit.action.static.folder-created=Carpeta estática creada
op.audit.action.static.deleted=Archivo o carpeta estática eliminada
op.audit.action.logs.settings-changed=Ajustes de registros modificados op.audit.action.logs.settings-changed=Ajustes de registros modificados
op.audit.action.site-config.changed=Ajustes del sitio modificados op.audit.action.site-config.changed=Ajustes del sitio modificados
@@ -1489,7 +1505,7 @@ op.ks.runway.csp.frame-ancestors.help=Qué sitios pueden mostrar estas páginas
op.ks.runway.endpoints.max-form-bytes=Solicitud máxima sin sesión (bytes) op.ks.runway.endpoints.max-form-bytes=Solicitud máxima sin sesión (bytes)
op.ks.runway.endpoints.max-form-bytes.help=Lo máximo que un visitante sin sesión puede enviar en una solicitud, en cualquier ruta. Por omisión 262144 (256 KiB). op.ks.runway.endpoints.max-form-bytes.help=Lo máximo que un visitante sin sesión puede enviar en una solicitud, en cualquier ruta. Por omisión 262144 (256 KiB).
op.ks.runway.http.min-request-data-rate=Cuerpo de solicitud más lento (bytes por segundo) op.ks.runway.http.min-request-data-rate=Cuerpo de solicitud más lento (bytes por segundo)
op.ks.runway.http.min-request-data-rate.help=Un cuerpo de solicitud que llega más despacio recibe 408 Request Timeout, así que un cliente que envía un byte de vez en cuando no puede ocupar un hilo de solicitud. Se mide sobre lo recibido desde el primer byte del cuerpo. Por omisión 4096; 0 desactiva la comprobación. op.ks.runway.http.min-request-data-rate.help=Un cuerpo de solicitud que llega más despacio recibe 408 Request Timeout: formularios (también el de inicio de sesión), subidas y cuerpos sin formato por igual, así que un cliente que envía un byte de vez en cuando no puede retener un hilo de solicitud. Solo cuenta el tiempo de espera por el cliente, y un cuerpo que ya llegó completo nunca se rechaza. Enviar rápido parte del cuerpo da como máximo 30 segundos de espera. Por omisión 4096; 0 desactiva la comprobación.
op.ks.runway.endpoints.max-body-bytes=Solicitud máxima a un complemento (bytes) op.ks.runway.endpoints.max-body-bytes=Solicitud máxima a un complemento (bytes)
op.ks.runway.endpoints.max-body-bytes.help=Lo máximo que un usuario con sesión puede enviar a una ruta de un complemento. Por omisión 10485760 (10 MiB). op.ks.runway.endpoints.max-body-bytes.help=Lo máximo que un usuario con sesión puede enviar a una ruta de un complemento. Por omisión 10485760 (10 MiB).
op.ks.spring.servlet.multipart.max-file-size=Archivo subido máximo op.ks.spring.servlet.multipart.max-file-size=Archivo subido máximo
@@ -12,6 +12,20 @@
</div> </div>
</div> </div>
<div class="card mb-3 border-primary" id="bk-review">
<div class="card-header"><h3 class="card-title" id="bk-review-title">How the site is reached</h3></div>
<div class="card-body">
<p class="text-secondary" id="bk-review-hint">A restore made here keeps the site's hosts and base URL.
Check them; only a platform administrator can change them.</p>
<dl class="row mb-0">
<dt class="col-sm-2" id="bk-review-l-hosts">Hosts</dt>
<dd class="col-sm-10 font-monospace" id="bk-review-hosts">example.com</dd>
<dt class="col-sm-2" id="bk-review-l-base">Base URL</dt>
<dd class="col-sm-10 font-monospace mb-0" id="bk-review-base">https://example.com</dd>
</dl>
</div>
</div>
<div class="row"> <div class="row">
<div class="col-md-6"> <div class="col-md-6">
<div class="card mb-3"> <div class="card mb-3">
@@ -7,6 +7,15 @@
<attr sel="#bk-pretitle" th:text="#{op.realm.tenant}"/> <attr sel="#bk-pretitle" th:text="#{op.realm.tenant}"/>
<attr sel="#bk-heading" th:text="#{op.backups.heading}"/> <attr sel="#bk-heading" th:text="#{op.backups.heading}"/>
<!-- After a restore (${reviewSite}): how the site is reached, read-only — a restore here keeps them. -->
<attr sel="#bk-review" th:if="${reviewSite != null}"/>
<attr sel="#bk-review-title" th:text="#{op.restore.review.kept.title}"/>
<attr sel="#bk-review-hint" th:text="#{op.restore.review.kept.hint}"/>
<attr sel="#bk-review-l-hosts" th:text="#{op.sites.hosts.short}"/>
<attr sel="#bk-review-hosts" th:text="${reviewSite == null or reviewSite.hosts().isEmpty()} ? (${reviewIsDefault} ? #{op.restore.review.noHosts} : #{op.restore.review.unreachable}) : ${#strings.listJoin(reviewSite.hosts(), ', ')}"/>
<attr sel="#bk-review-l-base" th:text="#{op.sites.base}"/>
<attr sel="#bk-review-base" th:text="${reviewSite?.baseUrl() != null} ? ${reviewSite.baseUrl()} : (${reviewSite == null or reviewSite.hosts().isEmpty()} ? #{op.restore.review.noBase} : #{op.restore.review.derived('https://' + ${reviewSite.hosts().get(0)})})"/>
<attr sel="#bk-l-make" th:text="#{op.backups.make}"/> <attr sel="#bk-l-make" th:text="#{op.backups.make}"/>
<attr sel="#bk-make-hint" th:text="#{op.backups.make.hint}"/> <attr sel="#bk-make-hint" th:text="#{op.backups.make.hint}"/>
<attr sel="#bk-download-now" th:if="${canDownloadFull}" th:text="#{op.backups.downloadNow}"/> <attr sel="#bk-download-now" th:if="${canDownloadFull}" th:text="#{op.backups.downloadNow}"/>
@@ -44,7 +44,7 @@
<label class="form-label wi-label" for="wi-input">key</label> <label class="form-label wi-label" for="wi-input">key</label>
<input class="form-control wi-input-text" type="text" id="wi-input" name="key" value=""> <input class="form-control wi-input-text" type="text" id="wi-input" name="key" value="">
<textarea class="form-control wi-input-area" name="key" rows="3"></textarea> <textarea class="form-control wi-input-area" name="key" rows="3"></textarea>
<input class="form-control wi-input-secret" type="password" name="key" autocomplete="off" <input class="form-control wi-input-secret" type="password" name="key" autocomplete="new-password"
placeholder="leave blank to keep"> placeholder="leave blank to keep">
<label class="form-check"> <label class="form-check">
<input class="form-check-input wi-input-bool" type="checkbox" name="key" value="true"> <input class="form-check-input wi-input-bool" type="checkbox" name="key" value="true">
@@ -16,6 +16,38 @@
</div> </div>
</div> </div>
<div class="card mb-3 border-primary" id="ab-review">
<div class="card-header"><h3 class="card-title" id="ab-review-title">Review how the site is reached</h3></div>
<div class="card-body">
<p class="text-secondary" id="ab-review-hint">The restore applied the hosts and base URL saved in the
backup. Check them, and correct them here if this installation reaches the site differently.</p>
<dl class="row mb-3">
<dt class="col-sm-2" id="ab-review-l-hosts">Hosts</dt>
<dd class="col-sm-10 font-monospace" id="ab-review-hosts">example.com</dd>
<dt class="col-sm-2" id="ab-review-l-base">Base URL</dt>
<dd class="col-sm-10 font-monospace" id="ab-review-base">https://example.com</dd>
</dl>
<form id="ab-review-form" method="post" action="#">
<input id="ab-review-csrf" type="hidden" name="_csrf" value="">
<div class="row">
<div class="col-md-6 mb-2">
<label class="form-label" id="ab-review-l-hosts-input" for="ab-review-hosts-input">Hosts</label>
<input class="form-control" id="ab-review-hosts-input" name="hosts" autocomplete="off"
placeholder="example.com, www.example.com">
<small class="form-hint" id="ab-review-hosts-hint">Comma-separated.</small>
</div>
<div class="col-md-6 mb-2">
<label class="form-label" id="ab-review-l-base-input" for="ab-review-base-input">Base URL</label>
<input class="form-control" id="ab-review-base-input" name="baseUrl" type="url" maxlength="300"
autocomplete="off" spellcheck="false">
<small class="form-hint" id="ab-review-base-hint">The origin of the site's absolute links.</small>
</div>
</div>
<button type="submit" class="btn btn-primary" id="ab-review-save">Save hosts</button>
</form>
</div>
</div>
<div class="card mb-3"> <div class="card mb-3">
<div class="card-header"><h3 class="card-title" id="cs-l">Create a site from a backup</h3></div> <div class="card-header"><h3 class="card-title" id="cs-l">Create a site from a backup</h3></div>
<div class="card-body"> <div class="card-body">
@@ -5,6 +5,27 @@
<attr sel="#ab-pretitle" th:text="#{op.realm.application}"/> <attr sel="#ab-pretitle" th:text="#{op.realm.application}"/>
<attr sel="#ab-heading" th:text="#{op.appbackups.heading}"/> <attr sel="#ab-heading" th:text="#{op.appbackups.heading}"/>
<!-- After a restore or a site created from a backup (${reviewSite}): the site's hosts and base URL as they stand,
with the same editor as Sites -> Edit hosts (it posts there, so that route's checks and activity line apply).
Restoring here already required a platform administrator, who may edit any site's hosts. -->
<attr sel="#ab-review" th:if="${reviewSite != null}"/>
<attr sel="#ab-review-title" th:text="#{op.restore.review.title(${reviewSite?.id()})}"/>
<attr sel="#ab-review-hint" th:text="#{op.restore.review.hint}"/>
<attr sel="#ab-review-l-hosts" th:text="#{op.sites.hosts.short}"/>
<attr sel="#ab-review-hosts" th:text="${reviewSite == null or reviewSite.hosts().isEmpty()} ? (${reviewIsDefault} ? #{op.restore.review.noHosts} : #{op.restore.review.unreachable}) : ${#strings.listJoin(reviewSite.hosts(), ', ')}"/>
<attr sel="#ab-review-l-base" th:text="#{op.sites.base}"/>
<attr sel="#ab-review-base" th:text="${reviewSite?.baseUrl() != null} ? ${reviewSite.baseUrl()} : (${reviewSite == null or reviewSite.hosts().isEmpty()} ? #{op.restore.review.noBase} : #{op.restore.review.derived('https://' + ${reviewSite.hosts().get(0)})})"/>
<attr sel="#ab-review-form" th:attr="action='/__app/sites/' + ${reviewSite?.id()} + '/hosts'"/>
<attr sel="#ab-review-csrf"
th:attr="name=${_csrf != null ? _csrf.parameterName : '_csrf'},value=${_csrf != null ? _csrf.token : ''}"/>
<attr sel="#ab-review-l-hosts-input" th:text="#{op.sites.hosts}"/>
<attr sel="#ab-review-hosts-input" th:attr="value=${reviewSite == null ? '' : #strings.listJoin(reviewSite.hosts(), ', ')}"/>
<attr sel="#ab-review-hosts-hint" th:text="#{op.sites.hosts.hint}"/>
<attr sel="#ab-review-l-base-input" th:text="#{op.sites.base}"/>
<attr sel="#ab-review-base-input" th:attr="value=${reviewSite?.baseUrl()},placeholder=${reviewSite == null or reviewSite.hosts().isEmpty() ? '' : 'https://' + reviewSite.hosts().get(0)}"/>
<attr sel="#ab-review-base-hint" th:text="#{op.sites.base.hint}"/>
<attr sel="#ab-review-save" th:text="#{op.sites.hosts.save}"/>
<attr sel="#cs-l" th:text="#{op.appbackups.create}"/> <attr sel="#cs-l" th:text="#{op.appbackups.create}"/>
<attr sel="#cs-hint" th:text="#{op.appbackups.create.hint}"/> <attr sel="#cs-hint" th:text="#{op.appbackups.create.hint}"/>
<attr sel="#cs-csrf" <attr sel="#cs-csrf"
@@ -58,7 +58,7 @@
<form id="ma-reset-form" method="post" class="row g-2"> <form id="ma-reset-form" method="post" class="row g-2">
<input class="ma-csrf" type="hidden" name="_csrf" value=""> <input class="ma-csrf" type="hidden" name="_csrf" value="">
<div class="col-md-6"><select class="form-select a11y-user" name="principalId" aria-label="User"><option class="ma-opt">m</option></select></div> <div class="col-md-6"><select class="form-select a11y-user" name="principalId" aria-label="User"><option class="ma-opt">m</option></select></div>
<div class="col-md-4"><input class="form-control a11y-newpass" name="password" type="password" placeholder="New password" aria-label="New password"></div> <div class="col-md-4"><input class="form-control a11y-newpass" name="password" type="password" autocomplete="new-password" placeholder="New password" aria-label="New password"></div>
<div class="col-md-2"><button type="submit" class="btn btn-outline-secondary w-100" id="ma-reset-btn">Reset</button></div> <div class="col-md-2"><button type="submit" class="btn btn-outline-secondary w-100" id="ma-reset-btn">Reset</button></div>
</form> </form>
</div> </div>
@@ -3,13 +3,15 @@
<head><meta charset="utf-8"><title>setting row</title></head> <head><meta charset="utf-8"><title>setting row</title></head>
<body> <body>
<!-- One setting's row, inserted by the settings form once per field (selected by the .sr-row class, never an <!-- One setting's row, inserted by the settings form once per field (selected by the .sr-row class, never an
id, because the form repeats it). Only the input variant matching the field's inputKind survives. --> id, because the form repeats it). Only the input variant matching the field's inputKind survives.
A secret is "new-password": browsers ignore "off" on a text box followed by a password box and fill in the
operator's own console login, which a save would then store as the plugin's credential. -->
<div class="sr-row mb-3"> <div class="sr-row mb-3">
<label class="form-label sr-label" for="sr-input">key</label> <label class="form-label sr-label" for="sr-input">key</label>
<input class="form-control sr-text" type="text" name="key" value=""> <input class="form-control sr-text" type="text" name="key" value="">
<textarea class="form-control sr-area" name="key" rows="3"></textarea> <textarea class="form-control sr-area" name="key" rows="3"></textarea>
<input class="form-control sr-secret" type="password" name="key" autocomplete="off" <input class="form-control sr-secret" type="password" name="key" autocomplete="new-password"
placeholder="leave blank to keep"> placeholder="leave blank to keep">
<select class="form-select sr-select" name="key"> <select class="form-select sr-select" name="key">
<option class="sr-opt" value="">value</option> <option class="sr-opt" value="">value</option>
@@ -71,6 +71,67 @@ class BackupRestoreRecoveryTest {
"the scratch work dir is cleared"); "the scratch work dir is cleared");
} }
/** The swap completed but the crash came before the logs were carried: they are merged, older lines first. */
@Test
void aCompletedSwapGetsItsLogsMergedOnStartup() throws IOException {
Path siteDir = layout.siteDir("demo");
Files.createDirectories(siteDir.resolve("logs"));
Files.writeString(siteDir.resolve("site.yml"), "id: demo\nname: RESTORED\n", StandardCharsets.UTF_8);
Files.writeString(siteDir.resolve("logs/audit-2026-10-30.log"), "AFTER\n", StandardCharsets.UTF_8);
Path old = workOld("demo");
Files.createDirectories(old.resolve("logs"));
Files.writeString(old.resolve("site.yml"), "id: demo\nname: BEFORE\n", StandardCharsets.UTF_8);
Files.writeString(old.resolve("logs/audit-2026-10-30.log"), "BEFORE\n", StandardCharsets.UTF_8);
Files.writeString(old.resolve("logs/audit-2026-10-29.log"), "YESTERDAY\n", StandardCharsets.UTF_8);
recovery.recover();
assertEquals("id: demo\nname: RESTORED\n", Files.readString(siteDir.resolve("site.yml")), "the restore stands");
assertEquals("BEFORE\nAFTER\n", Files.readString(siteDir.resolve("logs/audit-2026-10-30.log")),
"a day both have is joined in order");
assertEquals("YESTERDAY\n", Files.readString(siteDir.resolve("logs/audit-2026-10-29.log")));
assertFalse(Files.exists(layout.sites().resolve(BackupService.WORK_DIR).resolve("demo")));
}
/**
* A log write recreated the site folder between the two renames, and the process died: that folder holds only
* logs. It must not count as the site (which would delete `old`, the only copy); the site is rolled forward and
* the late lines follow its own.
*/
@Test
void aSiteFolderHoldingOnlyLateLogsIsNotMistakenForTheSite() throws IOException {
Path siteDir = layout.siteDir("demo");
Files.createDirectories(siteDir.resolve("logs"));
Files.writeString(siteDir.resolve("logs/access-2026-10-30.log"), "LATE\n", StandardCharsets.UTF_8);
Path old = workOld("demo");
Files.createDirectories(old.resolve("logs"));
Files.writeString(old.resolve("site.yml"), "id: demo\n", StandardCharsets.UTF_8);
Files.writeString(old.resolve("logs/access-2026-10-30.log"), "EARLIER\n", StandardCharsets.UTF_8);
recovery.recover();
assertEquals("id: demo\n", Files.readString(siteDir.resolve("site.yml")), "the original site is back");
assertEquals("EARLIER\nLATE\n", Files.readString(siteDir.resolve("logs/access-2026-10-30.log")));
assertFalse(Files.exists(layout.sites().resolve(BackupService.WORK_DIR).resolve("demo")));
}
/** A rollback put the site back but could not merge the lines written meanwhile: they follow its own. */
@Test
void lateLinesLeftByARollbackAreMergedAfterTheSitesOwn() throws IOException {
Path siteDir = layout.siteDir("demo");
Files.createDirectories(siteDir.resolve("logs"));
Files.writeString(siteDir.resolve("site.yml"), "id: demo\n", StandardCharsets.UTF_8);
Files.writeString(siteDir.resolve("logs/access-2026-10-30.log"), "OWN\n", StandardCharsets.UTF_8);
Path late = layout.sites().resolve(BackupService.WORK_DIR).resolve("demo").resolve(BackupService.LATE_DIR);
Files.createDirectories(late.resolve("logs"));
Files.writeString(late.resolve("logs/access-2026-10-30.log"), "LATE\n", StandardCharsets.UTF_8);
recovery.recover();
assertEquals("OWN\nLATE\n", Files.readString(siteDir.resolve("logs/access-2026-10-30.log")));
assertFalse(Files.exists(layout.sites().resolve(BackupService.WORK_DIR).resolve("demo")));
}
@Test @Test
void noWorkDirIsANoOp() { void noWorkDirIsANoOp() {
recovery.recover(); // must not throw when sites/.restore-work does not exist recovery.recover(); // must not throw when sites/.restore-work does not exist
@@ -4,6 +4,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assumptions.assumeFalse;
import java.io.ByteArrayInputStream; import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream; import java.io.ByteArrayOutputStream;
@@ -492,6 +493,113 @@ class BackupServiceTest {
assertTrue(sawContent, "real site content is still archived"); assertTrue(sawContent, "real site content is still archived");
} }
/** A restore replaces the content, not the site's history: its audit log and stats stay as they were. */
@Test
void aRestoreKeepsTheLiveSitesLogsAndStats() throws IOException {
ByteArrayOutputStream archive = new ByteArrayOutputStream();
svc.backup("demo", archive);
write(siteDir.resolve("logs/audit-2026-10-30.log"), "LIVE-AUDIT");
write(siteDir.resolve("stats/bandwidth.csv"), "LIVE-STATS");
write(siteDir.resolve("templates/_master.html"), "MASTER_BROKEN");
svc.restore("demo", new ByteArrayInputStream(archive.toByteArray()));
assertEquals("MASTER_V1", read(siteDir.resolve("templates/_master.html")), "the content is restored");
assertEquals("LIVE-AUDIT", read(siteDir.resolve("logs/audit-2026-10-30.log")), "the audit log survives");
assertEquals("LIVE-STATS", read(siteDir.resolve("stats/bandwidth.csv")), "the stats survive");
}
/** A backup never writes logs or stats, so whatever an archive carries under those names is discarded. */
@Test
void aRestoreDiscardsLogsAndStatsCarriedByTheArchive() throws IOException {
ByteArrayOutputStream original = new ByteArrayOutputStream();
svc.backup("demo", original);
ByteArrayOutputStream crafted = new ByteArrayOutputStream();
try (ZipInputStream in = new ZipInputStream(new ByteArrayInputStream(original.toByteArray()));
ZipOutputStream out = new ZipOutputStream(crafted)) {
ZipEntry e;
while ((e = in.getNextEntry()) != null) {
out.putNextEntry(new ZipEntry(e.getName()));
in.transferTo(out);
out.closeEntry();
}
for (String planted : List.of("site/logs/audit-2026-10-30.log", "site/logs/audit-2026-10-29.log",
"site/stats/bandwidth.csv")) {
out.putNextEntry(new ZipEntry(planted));
out.write("PLANTED".getBytes(StandardCharsets.UTF_8));
out.closeEntry();
}
}
// The live site has an audit log of its own, and no stats yet.
write(siteDir.resolve("logs/audit-2026-10-30.log"), "LIVE-AUDIT");
svc.restore("demo", new ByteArrayInputStream(crafted.toByteArray()));
assertEquals("LIVE-AUDIT", read(siteDir.resolve("logs/audit-2026-10-30.log")), "the live log is kept");
assertFalse(Files.exists(siteDir.resolve("logs/audit-2026-10-29.log")), "no planted day is added");
assertFalse(Files.exists(siteDir.resolve("stats")), "no planted stats appear");
}
private Path work(String siteId) {
return layout.sites().resolve(BackupService.WORK_DIR).resolve(siteId);
}
/** A merge that fails is kept, never deleted, and a repeated run finishes it without joining anything twice. */
@Test
void aFailedLogMergeIsKeptAndFinishedByTheNextRun() throws IOException {
write(siteDir.resolve("logs/audit-2026-10-30.log"), "NEW\n");
Path old = work("demo").resolve("old");
write(old.resolve("site.yml"), "id: demo\n");
write(old.resolve("logs/audit-2026-10-29.log"), "YESTERDAY\n");
Path unreadable = old.resolve("logs/audit-2026-10-30.log");
write(unreadable, "OLD\n");
unreadable.toFile().setReadable(false);
// As root (some CI containers) a file stays readable whatever its mode: the failure cannot be staged there.
assumeFalse(Files.isReadable(unreadable), "the file can be made unreadable");
try {
assertThrows(IOException.class, () -> BackupService.settle(siteDir, work("demo")));
} finally {
assertTrue(unreadable.toFile().setReadable(true));
}
assertTrue(Files.exists(unreadable), "the unmerged log is kept");
BackupService.settle(siteDir, work("demo"));
assertEquals("OLD\nNEW\n", read(siteDir.resolve("logs/audit-2026-10-30.log")), "joined once, in order");
assertEquals("YESTERDAY\n", read(siteDir.resolve("logs/audit-2026-10-29.log")), "moved once");
}
/** Logs a previous restore could not carry over are merged by the next restore of the site, not deleted. */
@Test
void theNextRestoreFinishesLogsAPreviousOneLeftBehind() throws IOException {
ByteArrayOutputStream archive = new ByteArrayOutputStream();
svc.backup("demo", archive);
write(work("demo").resolve("old/site.yml"), "id: demo\n");
write(work("demo").resolve("old/logs/audit-2026-10-29.log"), "LEFT-BEHIND\n");
svc.restore("demo", new ByteArrayInputStream(archive.toByteArray()));
assertEquals("LEFT-BEHIND\n", read(siteDir.resolve("logs/audit-2026-10-29.log")));
assertFalse(Files.exists(work("demo")), "the work folder is cleared once settled");
}
/** A new site starts its own logs: a leftover folder under its id (no site.yml) is not adopted. */
@Test
void aSiteCreatedFromABackupDoesNotAdoptLeftoverLogs() throws IOException {
new SiteStore(layout, new YamlStore()).save(new Site("src", "Source", List.of("src.test"), Locale.ENGLISH,
List.of(Locale.ENGLISH), "https://src.test", SiteStatus.ACTIVE));
write(layout.siteDir("src").resolve("templates/home.html"), "SRC_CONTENT");
ByteArrayOutputStream archive = new ByteArrayOutputStream();
svc.backup("src", archive);
Path stray = layout.siteDir("clone");
write(stray.resolve("logs/audit-2026-10-30.log"), "STRAY");
svc.createFromBackup("clone", "Cloned", List.of("clone.test"), new ByteArrayInputStream(archive.toByteArray()));
assertTrue(Files.exists(stray.resolve("site.yml")), "the site is created");
assertFalse(Files.exists(stray.resolve("logs")), "no leftover log becomes the new site's journal");
}
// ---- a restore must not make every page look edited today ------------------------------------ // ---- a restore must not make every page look edited today ------------------------------------
/** /**
@@ -131,6 +131,64 @@ class AppBackupsScreenTest {
assertTrue(sites.exists("acme"), "the source site is untouched"); assertTrue(sites.exists("acme"), "the source site is untouched");
} }
/**
* A restore applies the hosts and base URL saved in the backup, so the screen then shows them for review with the
* hosts editor; saving it goes through Sites -> Edit hosts and changes the site.
*/
@Test
void aRestoreIsFollowedByTheRestoredHostsWithTheirEditor() throws Exception {
Site original = sites.find("acme").orElseThrow();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
backups.backup("acme", baos); // carries acme.test and https://acme.test
try {
sites.save(new Site("acme", "Acme", List.of("acme.live"), Locale.ENGLISH, List.of(Locale.ENGLISH), null,
SiteStatus.ACTIVE));
MockHttpSession admin = sessionFor("admin");
MockMultipartFile file = new MockMultipartFile("file", "acme.zip", "application/zip", baos.toByteArray());
mvc.perform(multipart("/__app/backups/acme/restore").file(file).session(admin)
.with(csrf()))
.andExpect(status().is3xxRedirection())
.andExpect(flash().attribute(AppBackupsController.REVIEW_HOSTS, "acme"));
String page = mvc.perform(get("/__app/backups").session(admin))
.andExpect(status().isOk()).andReturn().getResponse().getContentAsString();
assertTrue(page.contains("Review how site acme is reached"), "the review card is shown");
assertTrue(page.contains(">acme.test<"), "the hosts as restored from the backup, not acme.live");
assertTrue(page.contains(">https://acme.test<"), "the restored base URL");
assertTrue(page.contains("action=\"/__app/sites/acme/hosts\""), "the editor posts to Sites -> Edit hosts");
assertTrue(page.contains("value=\"acme.test\""), "the editor starts from the hosts as they stand");
String plain = mvc.perform(get("/__app/backups").session(admin))
.andExpect(status().isOk()).andReturn().getResponse().getContentAsString();
assertFalse(plain.contains("Review how site"), "no review card without a restore");
mvc.perform(org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post("/__app/sites/acme/hosts")
.session(admin).with(csrf()).param("hosts", "acme.fixed").param("baseUrl", ""))
.andExpect(status().is3xxRedirection());
assertEquals(List.of("acme.fixed"), sites.find("acme").orElseThrow().hosts(), "corrected from the review");
} finally {
sites.save(original);
}
}
/** A site created from a backup without hosts is not the default site: the review says nothing reaches it. */
@Test
void aSiteCreatedWithoutHostsIsReportedUnreachableNotAsTheDefault() throws Exception {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
backups.backup("acme", baos);
MockHttpSession admin = sessionFor("admin");
MockMultipartFile file = new MockMultipartFile("file", "acme.zip", "application/zip", baos.toByteArray());
mvc.perform(multipart("/__app/backups/create-site").file(file).session(admin).with(csrf())
.param("newId", "hostless").param("name", "Hostless").param("hosts", ""))
.andExpect(status().is3xxRedirection())
.andExpect(flash().attribute(AppBackupsController.REVIEW_HOSTS, "hostless"));
String page = mvc.perform(get("/__app/backups").session(admin))
.andExpect(status().isOk()).andReturn().getResponse().getContentAsString();
assertTrue(page.contains("Review how site hostless is reached"));
assertTrue(page.contains("none: no address reaches this site until you give it a host"), "not the default");
assertFalse(page.contains("catch-all default site"), "it is not the default site");
}
/** An archive from a newer Runway: the operator is told to upgrade, and nothing is replaced or created. */ /** An archive from a newer Runway: the operator is told to upgrade, and nothing is replaced or created. */
@Test @Test
void aNewerFormatBackupIsRefusedWithTheUpgradeMessage() throws Exception { void aNewerFormatBackupIsRefusedWithTheUpgradeMessage() throws Exception {
@@ -103,7 +103,9 @@ class AuditViewTest {
"permissions.role-inherit-removed", "page.saved", "page.deleted", "page.published", "permissions.role-inherit-removed", "page.saved", "page.deleted", "page.published",
"page.unpublished", "user.created", "user.password-reset", "user.deleted", "page.unpublished", "user.created", "user.password-reset", "user.deleted",
"plugin.settings-changed", "logs.settings-changed", "site-config.changed", "master.assigned", "plugin.settings-changed", "logs.settings-changed", "site-config.changed", "master.assigned",
"master.unassigned", "site.created", "site.hosts-updated", "backup.saved", "master.unassigned", "site.created", "site.hosts-updated", "backup.saved", "backup.deleted",
"backup.downloaded", "site.restored", "user.updated", "user.suspended", "user.resumed",
"static.uploaded", "static.folder-created", "static.deleted",
"platform.kernel-settings-changed", "platform.kernel-setting-adopted")) { "platform.kernel-settings-changed", "platform.kernel-setting-adopted")) {
assertTrue(en.contains(recorded), "a label for " + recorded); assertTrue(en.contains(recorded), "a label for " + recorded);
} }
@@ -2,10 +2,17 @@ package mx.quest.runway.console;
import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.ArgumentMatchers.startsWith;
import static org.mockito.Mockito.clearInvocations;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestBuilders.formLogin; import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestBuilders.formLogin;
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf; import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf;
import static org.springframework.security.test.web.servlet.setup.SecurityMockMvcConfigurers.springSecurity; import static org.springframework.security.test.web.servlet.setup.SecurityMockMvcConfigurers.springSecurity;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.head;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.multipart; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.multipart;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
@@ -23,6 +30,7 @@ import java.util.Set;
import mx.quest.runway.authz.GrantFile; import mx.quest.runway.authz.GrantFile;
import mx.quest.runway.authz.GrantStore; import mx.quest.runway.authz.GrantStore;
import mx.quest.runway.backup.BackupService; import mx.quest.runway.backup.BackupService;
import mx.quest.runway.log.SiteLogService;
import mx.quest.runway.security.PasswordEncoders; import mx.quest.runway.security.PasswordEncoders;
import mx.quest.runway.security.PasswordStrength; import mx.quest.runway.security.PasswordStrength;
import mx.quest.runway.security.Roles; import mx.quest.runway.security.Roles;
@@ -46,6 +54,7 @@ import org.springframework.mock.web.MockHttpSession;
import org.springframework.mock.web.MockMultipartFile; import org.springframework.mock.web.MockMultipartFile;
import org.springframework.test.context.DynamicPropertyRegistry; import org.springframework.test.context.DynamicPropertyRegistry;
import org.springframework.test.context.DynamicPropertySource; import org.springframework.test.context.DynamicPropertySource;
import org.springframework.test.context.bean.override.mockito.MockitoSpyBean;
import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult; import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.request.RequestPostProcessor; import org.springframework.test.web.servlet.request.RequestPostProcessor;
@@ -104,6 +113,8 @@ class TenantBackupsScreenTest {
private SiteResolver siteResolver; private SiteResolver siteResolver;
@Autowired @Autowired
private BackupService backups; private BackupService backups;
@MockitoSpyBean
private SiteLogService siteLog;
private MockMvc mvc; private MockMvc mvc;
@BeforeEach @BeforeEach
@@ -189,6 +200,75 @@ class TenantBackupsScreenTest {
} }
} }
// --- the site's audit log ----------------------------------------------------------------------
/** Each act that took effect is one line in the site's own audit log, with who did it and what. */
@Test
void everyBackupActIsRecordedInTheSitesAuditLog() throws Exception {
MockHttpSession admin = sessionFor("admin");
clearInvocations(siteLog);
mvc.perform(post("/__admin/backups/create").session(admin).with(csrf()))
.andExpect(status().is3xxRedirection());
String name = backups.list("acme").get(0).name();
verify(siteLog).audit("acme", "admin", "backup.saved", name);
mvc.perform(get("/__admin/backups/download").session(admin)).andExpect(status().isOk());
verify(siteLog).audit("acme", "admin", "backup.downloaded", "full");
mvc.perform(get("/__admin/backups/download-transfer").session(admin)).andExpect(status().isOk());
verify(siteLog).audit("acme", "admin", "backup.downloaded", "transfer");
mvc.perform(get("/__admin/backups/" + name + "/download").session(admin)).andExpect(status().isOk());
verify(siteLog).audit("acme", "admin", "backup.downloaded", "full " + name);
mvc.perform(post("/__admin/backups/" + name + "/restore").session(admin).with(csrf()))
.andExpect(flash().attributeExists("flash"));
verify(siteLog).audit("acme", "admin", "site.restored", name);
byte[] zip = mvc.perform(get("/__admin/backups/download").session(admin)).andReturn()
.getResponse().getContentAsByteArray();
mvc.perform(multipart("/__admin/backups/restore")
.file(new MockMultipartFile("file", "acme.zip", "application/zip", zip))
.session(admin).with(csrf()))
.andExpect(flash().attributeExists("flash"));
verify(siteLog).audit("acme", "admin", "site.restored", "(upload)");
mvc.perform(post("/__admin/backups/" + name + "/delete").session(admin).with(csrf()))
.andExpect(status().is3xxRedirection());
verify(siteLog).audit("acme", "admin", "backup.deleted", name);
}
/** A refused, failed or empty act writes nothing: the log says what happened, not what was tried. */
@Test
void aRefusedOrFailedBackupActIsNotRecorded() throws Exception {
String name = storedBackup();
MockHttpSession keeper = sessionFor("keeper");
MockHttpSession admin = sessionFor("admin");
clearInvocations(siteLog);
mvc.perform(get("/__admin/backups/download").session(keeper)).andExpect(status().isForbidden());
mvc.perform(get("/__admin/backups/" + name + "/download").session(keeper))
.andExpect(status().isForbidden());
// A HEAD request (a link checker, a preview) takes no copy: answered, not recorded.
for (String path : List.of("/__admin/backups/download", "/__admin/backups/download-transfer",
"/__admin/backups/" + name + "/download")) {
mvc.perform(head(path).session(admin))
.andExpect(status().isOk())
.andExpect(header().string("Content-Disposition", Matchers.containsString("attachment")));
}
// A range that resumes a download is not a new one.
mvc.perform(get("/__admin/backups/" + name + "/download").session(admin).header("Range", "bytes=10-"))
.andExpect(status().isPartialContent());
mvc.perform(post("/__admin/backups/" + name + "/restore").session(keeper).with(csrf()))
.andExpect(status().isForbidden());
mvc.perform(post("/__admin/backups/no-such-backup.zip/delete").session(admin).with(csrf()))
.andExpect(status().is3xxRedirection());
mvc.perform(post("/__admin/backups/no-such-backup.zip/restore").session(admin).with(csrf()))
.andExpect(flash().attributeExists("error"));
mvc.perform(multipart("/__admin/backups/restore")
.file(new MockMultipartFile("file", "junk.zip", "application/zip", new byte[] {1, 2, 3}))
.session(admin).with(csrf()))
.andExpect(flash().attributeExists("error"));
verify(siteLog, never()).audit(anyString(), anyString(), startsWith("backup."), anyString());
verify(siteLog, never()).audit(anyString(), anyString(), eq("site.restored"), anyString());
}
/** Without MANAGE_BACKUPS at all, nothing — not even a transfer copy. */ /** Without MANAGE_BACKUPS at all, nothing — not even a transfer copy. */
@Test @Test
void anOperatorWithoutTheGrantGetsNoDownloadOfAnyKind() throws Exception { void anOperatorWithoutTheGrantGetsNoDownloadOfAnyKind() throws Exception {
@@ -284,6 +364,31 @@ class TenantBackupsScreenTest {
assertEquals("ORIGINAL_CONTENT", Files.readString(home, StandardCharsets.UTF_8), "the page was restored"); assertEquals("ORIGINAL_CONTENT", Files.readString(home, StandardCharsets.UTF_8), "the page was restored");
} }
/** After a restore the screen shows how the site is reached, read-only: a restore here keeps the hosts. */
@Test
void aRestoreIsFollowedByTheSitesHostsForReview() throws Exception {
MockHttpSession admin = sessionFor("admin");
mvc.perform(post("/__admin/backups/create").session(admin).with(csrf())).andExpect(status().is3xxRedirection());
mvc.perform(get("/__admin/backups").session(admin)).andExpect(status().isOk()); // the create's redirect
String name = backups.list("acme").get(0).name();
mvc.perform(post("/__admin/backups/" + name + "/restore").session(admin).with(csrf()))
.andExpect(status().is3xxRedirection())
.andExpect(flash().attribute(AppBackupsController.REVIEW_HOSTS, Boolean.TRUE));
MvcResult shown = mvc.perform(get("/__admin/backups").session(admin)).andExpect(status().isOk()).andReturn();
String page = shown.getResponse().getContentAsString();
assertTrue(page.contains("id=\"bk-review\""), "the review card is shown");
assertTrue(page.contains("How the site is reached"));
assertTrue(page.contains("only a platform administrator can change them"));
assertTrue(page.contains(">localhost<"), "the site's host");
assertTrue(page.contains("not set, so https://localhost (https:// and the first host)"), "the derived base URL");
assertTrue(!page.contains("/__app/sites/acme/hosts"), "no editor on the site console");
String plain = mvc.perform(get("/__admin/backups").session(admin))
.andExpect(status().isOk()).andReturn().getResponse().getContentAsString();
assertTrue(!plain.contains("id=\"bk-review\""), "no review card without a restore");
}
/** An archive from a newer Runway is refused on both restore paths, with the upgrade message. */ /** An archive from a newer Runway is refused on both restore paths, with the upgrade message. */
@Test @Test
void aNewerFormatBackupIsRefusedWithTheUpgradeMessage() throws Exception { void aNewerFormatBackupIsRefusedWithTheUpgradeMessage() throws Exception {
@@ -85,8 +85,7 @@ class RouteAwareFormContentFilterTest {
} }
@Test @Test
void itKeepsBootsOrder() { void itSitsInsideTheAccessLogAndTheSiteBindingSoItsRefusalsAreLogged() {
assertEquals(org.springframework.boot.servlet.filter.OrderedFormContentFilter.DEFAULT_ORDER, assertEquals(mx.quest.runway.web.FilterOrder.CORE_FORM_CONTENT, filter(registry()).getOrder());
filter(registry()).getOrder());
} }
} }
@@ -4,8 +4,11 @@ import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when; import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import ch.qos.logback.classic.Logger; import ch.qos.logback.classic.Logger;
import ch.qos.logback.classic.spi.ILoggingEvent; import ch.qos.logback.classic.spi.ILoggingEvent;
@@ -17,10 +20,12 @@ import org.junit.jupiter.api.Test;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse; import org.springframework.mock.web.MockHttpServletResponse;
import java.util.Optional; import mx.quest.runway.site.SiteContextFilter;
import mx.quest.runway.site.SiteResolver;
/** The access log fires from the post-phase (final status) for public traffic, and skips internal surfaces. */ /**
* The access log fires from the post-phase (final status) for public traffic, and skips internal surfaces. Which
* requests reach it on the running application, whoever answers them, is {@code AccessLogCoverageEndToEndTest}.
*/
class AccessLogFilterTest { class AccessLogFilterTest {
private Logger accessLogger; private Logger accessLogger;
@@ -39,10 +44,10 @@ class AccessLogFilterTest {
accessLogger.detachAppender(appender); accessLogger.detachAppender(appender);
} }
private static AccessLogFilter filter() { private final SiteLogService siteLog = mock(SiteLogService.class);
SiteResolver resolver = mock(SiteResolver.class);
when(resolver.current()).thenReturn(Optional.empty()); private AccessLogFilter filter() {
return new AccessLogFilter(resolver, mock(SiteLogService.class)); return new AccessLogFilter(siteLog, false);
} }
private void runWithFinalStatus(String path, int finalStatus) throws Exception { private void runWithFinalStatus(String path, int finalStatus) throws Exception {
@@ -94,4 +99,25 @@ class AccessLogFilterTest {
assertEquals(1, appender.list.size(), "the access log fires from finally even on an exception"); assertEquals(1, appender.list.size(), "the access log fires from finally even on an exception");
assertTrue(appender.list.get(0).getFormattedMessage().contains("/about")); assertTrue(appender.list.get(0).getFormattedMessage().contains("/about"));
} }
@Test
void theSiteThatAnsweredGetsTheLineFromTheRequestAttribute() throws Exception {
// The site-context filter is inner of this one: by the post-phase its thread binding is gone, and only the
// attribute it set on the request says which site answered.
MockHttpServletRequest request = new MockHttpServletRequest("POST", "/login");
request.setRequestURI("/login");
request.setRemoteAddr("198.51.100.4");
filter().doFilter(request, new MockHttpServletResponse(), (req, res) -> {
req.setAttribute(SiteContextFilter.SITE_ID_ATTRIBUTE, "acme");
((HttpServletResponse) res).setStatus(403);
});
verify(siteLog).access("acme", "198.51.100.4", "POST", "/login", 403);
}
@Test
void aRequestNoSiteAnsweredGoesToThePlatformLogOnly() throws Exception {
runWithFinalStatus("/about", 404);
assertEquals(1, appender.list.size());
verify(siteLog, never()).access(anyString(), anyString(), anyString(), anyString(), anyInt());
}
} }
@@ -103,7 +103,14 @@ class SiteInsightsServiceTest {
line(TODAY, "11:29:00", "GET", "/.well-known/security.txt", 404), line(TODAY, "11:29:00", "GET", "/.well-known/security.txt", 404),
line(TODAY, "11:30:00", "GET", "/actuator/health", 200), line(TODAY, "11:30:00", "GET", "/actuator/health", 200),
line(TODAY, "11:31:00", "GET", "/app/x", 404), line(TODAY, "11:31:00", "GET", "/app/x", 404),
line(TODAY, "11:32:00", "GET", "/broken", 500)); // neither 2xx nor 404 line(TODAY, "11:32:00", "GET", "/broken", 500), // neither 2xx nor 404
// Answers the access log has carried since 1.1.2 (refusals and login traffic): none is a view.
line(TODAY, "11:40:00", "POST", "/login", 403), // a bot's post without a form token
line(TODAY, "11:41:00", "POST", "/login", 302), // a login attempt
line(TODAY, "11:42:00", "POST", "/login", 408), // a refused slow body
line(TODAY, "11:43:00", "GET", "/members", 302), // sent to the login page
line(TODAY, "11:44:00", "GET", "/members", 403), // signed in, not allowed
line(TODAY, "11:45:00", "GET", "/", 503)); // suspended, maintenance, quota
Report r = service().report("acme", 7); Report r = service().report("acme", 7);
@@ -117,7 +124,7 @@ class SiteInsightsServiceTest {
assertEquals(TODAY + " 11:10:00", row(r.topNotFound(), "/missing").lastSeen()); assertEquals(TODAY + " 11:10:00", row(r.topNotFound(), "/missing").lastSeen());
assertEquals(1, row(r.topNotFound(), "/img/logo.png").count()); assertEquals(1, row(r.topNotFound(), "/img/logo.png").count());
assertEquals(2, r.topNotFound().size()); assertEquals(2, r.topNotFound().size());
assertEquals(20, r.linesScanned()); assertEquals(26, r.linesScanned());
assertEquals(1, r.filesScanned()); assertEquals(1, r.filesScanned());
assertFalse(r.lineCapReached()); assertFalse(r.lineCapReached());
assertFalse(r.approximate()); assertFalse(r.approximate());
@@ -161,4 +161,22 @@ class SiteLogServiceTest {
assertEquals(3, lines.size()); assertEquals(3, lines.size());
assertTrue(lines.get(2).endsWith("/page-19999\t200"), lines.get(2)); // the newest line survives assertTrue(lines.get(2).endsWith("/page-19999\t200"), lines.get(2)); // the newest line survives
} }
@Test
void underAFloodAccessLinesAreDroppedBeforeAuditLines() {
props.setQueueCapacity(16); // reserve: 16 / 8 = 2 slots for audit only
SiteLogService svc = new SiteLogService(layout, configs, props);
svc.acceptWithoutWriting();
for (int i = 0; i < 20; i++) {
svc.access("acme", "203.0.113.9", "POST", "/login", 302);
}
assertEquals(14, svc.queued(), "access lines stop short of the audit reserve");
assertEquals(6, svc.droppedCount());
svc.audit("acme", "-", "login.failure", "user=a");
svc.audit("acme", "-", "login.failure", "user=b");
assertEquals(16, svc.queued(), "the reserve takes the audit lines the flood would have crowded out");
assertEquals(6, svc.droppedCount());
svc.audit("acme", "-", "login.failure", "user=c");
assertEquals(7, svc.droppedCount(), "a full queue drops an audit line too: the reserve is not unbounded");
}
} }
@@ -421,6 +421,41 @@ class PluginContributionPolicyTest {
"p2 declared no app-level secret, so the environment's value is not handed out"); "p2 declared no app-level secret, so the environment's value is not handed out");
} }
@Test
void theFactoryHandsAPluginItsOwnSavedAppSettingsFromItsOwnFileOnly() throws Exception {
assumeTrue(PluginFixture.compilerAvailable());
String schema = "settings:\n - { key: apiKey, type: secret, label: l }\n"
+ " - { key: host, type: string, label: l }\n";
PluginDescriptor d1 = PluginDescriptor.read(new ByteArrayInputStream(("id: p1\nversion: 1.0.0\nmainClass: x.Y\n"
+ schema).getBytes(StandardCharsets.UTF_8)));
PluginDescriptor d2 = PluginDescriptor.read(new ByteArrayInputStream(("id: p2\nversion: 1.0.0\nmainClass: x.Y\n"
+ schema).getBytes(StandardCharsets.UTF_8)));
PluginOwnership owners = PluginOwnership.of(new PluginRuntime(
List.of(new LoadedPlugin(d1, root.resolve("p1")), new LoadedPlugin(d2, root.resolve("p2"))), loader,
Map.of(), false));
mx.quest.runway.storage.StorageProperties props = new mx.quest.runway.storage.StorageProperties();
props.setExternal(root.resolve("external-saved"));
mx.quest.runway.storage.StorageLayout layout = mx.quest.runway.storage.StorageLayout.from(props);
java.nio.file.Path p1File = layout.pluginSettingsFile("p1");
java.nio.file.Files.createDirectories(p1File.getParent());
java.nio.file.Files.writeString(p1File, "runway:\n plugin:\n p1:\n host: saved.example\n"
+ " apiKey: p1-saved\n");
org.springframework.mock.env.MockEnvironment env = new org.springframework.mock.env.MockEnvironment()
.withProperty("runway.plugin.p1.host", "running.example");
PluginScopedServices scoped = new PluginScopedServices(owners,
new SitePluginConfigService(layout, null, event -> { }), null, layout, 1024, env);
PluginSettings p1 = scoped.pluginSettings(pointIn(head("p1", "k", false).getClass(), "key"));
PluginSettings p2 = scoped.pluginSettings(pointIn(head("p2", "k", false).getClass(), "key"));
assertEquals(Optional.of("saved.example"), p1.savedApp("host"), "the file as saved, not the environment");
assertEquals(Optional.of("p1-saved"), p1.savedApp("apiKey"), "its own saved secret (plaintext as written)");
assertEquals(Optional.empty(), p2.savedApp("host"), "p2 has no file of its own: p1's is never read for it");
assertEquals(Optional.empty(), p2.savedApp("apiKey"));
java.nio.file.Files.writeString(p1File, "runway:\n plugin:\n p1:\n host: [unclosed\n");
assertEquals(Optional.empty(), p1.savedApp("host"), "an unparsable file answers empty, never throws");
}
@Test @Test
void anInjectionPointInAPluginsOwnJarBindsToThatPlugin() throws Exception { void anInjectionPointInAPluginsOwnJarBindsToThatPlugin() throws Exception {
assumeTrue(PluginFixture.compilerAvailable()); assumeTrue(PluginFixture.compilerAvailable());
@@ -273,4 +273,90 @@ class PluginSettingsImplTest {
assertEquals(Optional.empty(), bare.appSecret("password"), assertEquals(Optional.empty(), bare.appSecret("password"),
"an implementation written against SPI 1.0 still compiles and answers empty"); "an implementation written against SPI 1.0 still compiles and answers empty");
} }
// ---- saved app-level settings (SPI 1.2.0) -------------------------------------------------------
private void saveAppFile(String plugin, String yaml) throws IOException {
Path file = layout.pluginSettingsFile(plugin);
Files.createDirectories(file.getParent());
Files.writeString(file, yaml);
}
/** As the kernel wires it: the saved values come from the plugin's own settings file. */
private PluginSettingsImpl withSavedApp(String plugin) {
return new PluginSettingsImpl(plugin, SCHEMA, APP_SCHEMA, environment::get,
key -> mx.quest.runway.plugin.PluginSettingsService.saved(layout, plugin).get(key), config, cipher);
}
@Test
void aSavedAppSettingIsReadFromTheFileNotFromTheRunningEnvironment() throws IOException {
environment.put("runway.plugin.database.host", "running.example");
environment.put("runway.plugin.database.password", "running-secret");
saveAppFile("database", "runway:\n plugin:\n database:\n host: saved.example\n password: "
+ cipher.encrypt("saved-secret") + "\n");
PluginSettingsImpl settings = withSavedApp("database");
assertEquals(Optional.of("saved.example"), settings.savedApp("host"));
assertEquals(Optional.of("saved-secret"), settings.savedApp("password"), "a saved secret, decrypted");
assertEquals(Optional.of("running-secret"), settings.appSecret("password"), "appSecret keeps the running one");
}
@Test
void aSaveAfterStartupIsSeenOnTheNextCall() throws IOException {
PluginSettingsImpl settings = withSavedApp("database");
saveAppFile("database", "runway:\n plugin:\n database:\n host: first.example\n");
assertEquals(Optional.of("first.example"), settings.savedApp("host"));
saveAppFile("database", "runway:\n plugin:\n database:\n host: second.example\n");
assertEquals(Optional.of("second.example"), settings.savedApp("host"), "read from the file each time");
}
@Test
void anUnsavedOrBlankSettingFallsBackToTheDeclaredDefaultExceptASecret() throws IOException {
PluginSettingsImpl settings = withSavedApp("database");
assertEquals(Optional.of("localhost"), settings.savedApp("host"), "no file: the declared default");
assertEquals(Optional.empty(), settings.savedApp("password"), "a secret has no default");
saveAppFile("database", "runway:\n plugin:\n database:\n host: ' '\n password: ''\n");
assertEquals(Optional.of("localhost"), settings.savedApp("host"));
assertEquals(Optional.empty(), settings.savedApp("password"));
}
@Test
void onlyTheCallersOwnDeclaredAppKeysAreRead() throws IOException {
saveAppFile("database", "runway:\n plugin:\n database:\n undeclared: x\n smtpPassword: y\n");
saveAppFile("other", "runway:\n plugin:\n other:\n host: not-mine\n");
PluginSettingsImpl settings = withSavedApp("database");
assertEquals(Optional.empty(), settings.savedApp("undeclared"));
assertEquals(Optional.empty(), settings.savedApp("smtpPassword"), "declared only in siteSettings:");
assertEquals(Optional.empty(), settings.savedApp(null));
assertEquals(Optional.of("localhost"), settings.savedApp("host"), "another plugin's file is never read");
}
@Test
void aSavedSecretThatCannotBeDecryptedIsEmptyAndAPlaintextOneIsReturned() throws IOException {
PluginSettingsImpl settings = withSavedApp("database");
saveAppFile("database", "runway:\n plugin:\n database:\n password: hand-written\n");
assertEquals(Optional.of("hand-written"), settings.savedApp("password"));
saveAppFile("database", "runway:\n plugin:\n database:\n password: " + cipher.encrypt("s")
+ "\n");
cipherBroken = true;
assertEquals(Optional.empty(), settings.savedApp("password"));
}
@Test
void theOlderConstructorsAndTheSpiDefaultHaveNoSavedValues() {
environment.put("runway.plugin.database.host", "running.example");
assertEquals(Optional.of("localhost"), withApp("database").savedApp("host"),
"no saved-values lookup: only the declared default");
mx.quest.runway.spi.service.PluginSettings bare = new mx.quest.runway.spi.service.PluginSettings() {
@Override
public SettingsView site(String siteId) {
return new SettingsView(java.util.Map.of());
}
@Override
public Optional<String> secret(String siteId, String key) {
return Optional.empty();
}
};
assertEquals(Optional.empty(), bare.savedApp("host"), "an implementation written before SPI 1.2.0");
}
} }
@@ -11,7 +11,7 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.web.servlet.FilterRegistrationBean; import org.springframework.boot.web.servlet.FilterRegistrationBean;
/** The protection floor and access log sit at their pinned slots, and the kernel default guard passes. */ /** The protection floor and the access log just inside it sit at their pinned slots; the default guard passes. */
@SpringBootTest @SpringBootTest
class EdgeProtectionConfigTest { class EdgeProtectionConfigTest {
@@ -30,9 +30,10 @@ class EdgeProtectionConfigTest {
} }
@Test @Test
void theAccessLogSitsInnermost() { void theAccessLogSitsJustInsideTheFloor() {
assertEquals(FilterOrder.CORE_ACCESS_LOG, accessLog.getOrder()); assertEquals(FilterOrder.CORE_ACCESS_LOG, accessLog.getOrder());
assertEquals(Integer.MAX_VALUE, accessLog.getOrder()); assertTrue(accessLog.getOrder() > edgeReject.getOrder(), "floor rejections stay out of the access log");
assertTrue(accessLog.getOrder() < FilterOrder.CORE_SITE_CONTEXT, "outer of every gate that answers alone");
} }
@Test @Test
@@ -12,8 +12,8 @@ import org.junit.jupiter.api.Test;
/** /**
* The recorder that closes the edge-rejection blind spot: a reject short-circuits at * The recorder that closes the edge-rejection blind spot: a reject short-circuits at
* {@code FilterOrder.CORE_PROTECTION} without calling the chain, so it never reaches the innermost access log * {@code FilterOrder.CORE_PROTECTION} without calling the chain, so it never reaches the access log (inside the
* and appeared in <b>no</b> log anywhere in the product. * floor) and appeared in <b>no</b> log anywhere in the product.
* *
* <p>The behaviour under test is mostly about what must remain true <em>under abuse</em>, since that is exactly * <p>The behaviour under test is mostly about what must remain true <em>under abuse</em>, since that is exactly
* when this code runs: the count must stay exact, the log must not become an amplifier, and the memory used to * when this code runs: the count must stay exact, the log must not become an amplifier, and the memory used to
@@ -0,0 +1,263 @@
package mx.quest.runway.web;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import ch.qos.logback.classic.Logger;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.read.ListAppender;
import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.function.BooleanSupplier;
import java.util.function.Supplier;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import mx.quest.runway.log.LogKind;
import mx.quest.runway.log.SiteLogService;
import mx.quest.runway.protect.EdgeGuard;
import mx.quest.runway.protect.EdgeVerdict;
import mx.quest.runway.site.Site;
import mx.quest.runway.site.SiteStatus;
import mx.quest.runway.site.SiteStore;
import mx.quest.runway.storage.StorageLayout;
import mx.quest.runway.storage.StorageProperties;
import mx.quest.runway.storage.YamlStore;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.TestConfiguration;
import org.springframework.boot.test.web.server.LocalServerPort;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Primary;
import org.springframework.test.context.DynamicPropertyRegistry;
import org.springframework.test.context.DynamicPropertySource;
/**
* Every request the abuse floor lets through is in the access log, however it is answered: in the platform's
* {@code runway.access} stream and in the answering site's own log. Until 1.1.2 the access log sat innermost, and
* each answer below except the plain page was given by a filter outside it, so none of them was logged: a login
* attempt, a CSRF refusal, a suspended or maintenance site, a refused slow body, an oversized form refused unread,
* an endpoint route. Floor rejections and the internal surfaces stay out.
*
* <p>Against a real Jetty and the real filter chain, over raw sockets, because the gap was the chain's shape.
*/
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
class AccessLogCoverageEndToEndTest {
private static final Pattern CSRF = Pattern.compile("name=\"_csrf\"[^>]*?value=\"([^\"]*)\"");
/** The test guard turns this path away at the floor. */
private static final String FLOOR_REJECTED = "/floor-rejected";
@DynamicPropertySource
static void config(DynamicPropertyRegistry registry) throws IOException {
Path external = Files.createTempDirectory("runway-access-log");
ConsoleHostEndToEndTest.seed(external, null);
StorageProperties props = new StorageProperties();
props.setExternal(external);
SiteStore sites = new SiteStore(StorageLayout.from(props), new YamlStore());
sites.save(new Site("sus", "Sus", List.of("sus.test"), Locale.ENGLISH, List.of(Locale.ENGLISH), null,
SiteStatus.SUSPENDED, false, null));
sites.save(new Site("mnt", "Mnt", List.of("mnt.test"), Locale.ENGLISH, List.of(Locale.ENGLISH), null,
SiteStatus.ACTIVE, true, "Back soon"));
registry.add("runway.storage.external", () -> external.toString());
registry.add("runway.security.app-master-id", () -> "app-master");
registry.add("runway.health.content-check", () -> "false");
registry.add("runway.http.min-request-data-rate", () -> "1024");
}
@TestConfiguration
static class Beans {
@Bean
@Primary
EdgeGuard floorRejectingOnePath() {
return request -> FLOOR_REJECTED.equals(request.path()) ? EdgeVerdict.reject(429) : EdgeVerdict.pass();
}
}
@LocalServerPort
private int port;
@Autowired
private SiteLogService siteLogs;
private Logger accessLogger;
private ListAppender<ILoggingEvent> platformLines;
@BeforeEach
void attach() {
accessLogger = (Logger) LoggerFactory.getLogger("runway.access");
platformLines = new ListAppender<>();
platformLines.start();
accessLogger.addAppender(platformLines);
}
@AfterEach
void detach() {
accessLogger.detachAppender(platformLines);
}
@Test
void aPageIsLogged() throws IOException {
String path = "/page-" + System.nanoTime();
assertEquals(404, get("main.test", path).status());
assertLogged("main", "GET", path, 404);
}
@Test
void aLoginPostWithoutItsFormTokenIsLogged() throws IOException {
assertEquals(403, RawHttp.send(port, "POST", "main.test:" + port, "/login",
"username=guess&password=guess").status());
assertLogged("main", "POST", "/login", 403);
}
@Test
void aFailedLoginAttemptIsLogged() throws IOException {
RawHttp.Response page = get("main.test", "/login");
assertEquals(200, page.status());
Matcher token = CSRF.matcher(page.body());
assertTrue(token.find(), "a form token on /login");
RawHttp.Response attempt = RawHttp.send(port, "POST", "main.test:" + port, "/login",
"username=nobody&password=wrong-guess&_csrf=" + URLEncoder.encode(token.group(1),
StandardCharsets.UTF_8), Map.of("Cookie", String.join("; ", page.cookies())));
assertEquals(302, attempt.status(), "Spring Security answers the attempt itself, with a redirect");
assertLogged("main", "POST", "/login", 302);
}
@Test
void aSuspendedSitesRefusalIsLogged() throws IOException {
String path = "/suspended-" + System.nanoTime();
assertEquals(503, get("sus.test", path).status());
assertLogged("sus", "GET", path, 503);
}
@Test
void aSiteInMaintenanceIsLogged() throws IOException {
String path = "/maintenance-" + System.nanoTime();
assertEquals(503, get("mnt.test", path).status());
assertLogged("mnt", "GET", path, 503);
}
@Test
void anEndpointRouteIsLogged() throws IOException {
int status = get("main.test", "/manifest.webmanifest").status();
assertLogged("main", "GET", "/manifest.webmanifest", status);
}
@Test
void anOversizedPutFormRefusedUnreadIsLogged() throws IOException {
// The form-content filter answers 413 from the declared length, without reading the body or calling the chain.
String path = "/put-form-" + System.nanoTime();
assertEquals(413, RawHttp.send(port, "PUT", "main.test:" + port, path, null, Map.of(
"Content-Type", "application/x-www-form-urlencoded", "Content-Length", "99999999")).status());
assertLogged("main", "PUT", path, 413);
}
@Test
void aRefusedSlowLoginBodyIsLogged() throws Exception {
try (Socket socket = new Socket("127.0.0.1", port)) {
OutputStream out = socket.getOutputStream();
out.write(("POST /login HTTP/1.1\r\nHost: main.test:" + port + "\r\nContent-Type: "
+ "application/x-www-form-urlencoded\r\nContent-Length: 1000\r\nConnection: close\r\n\r\n"
+ "username=").getBytes(StandardCharsets.US_ASCII));
out.flush();
try {
for (int i = 0; i < 20; i++) {
Thread.sleep(1000);
out.write('a');
out.flush();
}
} catch (IOException closedByServer) {
// expected: answered and closed while the client was still trickling
}
socket.setSoTimeout(40_000);
String response = new String(socket.getInputStream().readAllBytes(), StandardCharsets.US_ASCII);
assertTrue(response.startsWith("HTTP/1.1 408"), response.lines().findFirst().orElse(""));
}
assertLogged("main", "POST", "/login", 408);
}
@Test
void aFloorRejectionStaysOutOfTheAccessLog() throws IOException {
assertEquals(429, get("main.test", FLOOR_REJECTED).status());
String control = "/after-floor-" + System.nanoTime();
get("main.test", control);
awaitSiteLine("main", control);
assertFalse(platformText().contains(FLOOR_REJECTED), platformText());
assertFalse(siteText("main").contains(FLOOR_REJECTED), "reported by runway.protect, throttled, instead");
}
@Test
void theInternalSurfacesStayOut() throws IOException {
get("main.test", "/app/login");
get("127.0.0.1:" + port, "/app/login");
String control = "/after-internal-" + System.nanoTime();
get("main.test", control);
awaitSiteLine("main", control);
assertFalse(platformText().contains("/app/login"), platformText());
assertFalse(siteText("main").contains("/app/login"));
}
// ---------------------------------------------------------------------------------------------------------------
private RawHttp.Response get(String host, String path) throws IOException {
return RawHttp.send(port, "GET", host.contains(":") ? host : host + ":" + port, path);
}
/**
* Both sinks carry the request with its final status. Both are waited for: the line is written when the chain
* unwinds, which can be after the client has read a response the application already completed and closed.
*/
private void assertLogged(String siteId, String method, String path, int status) {
String platform = " " + method + " " + path + " -> " + status + " (";
await(() -> platformText().contains(platform), () -> "runway.access lacks [" + platform + "]: "
+ platformText());
awaitSiteLine(siteId, "\t" + method + "\t" + path + "\t" + status);
}
private String platformText() {
StringBuilder text = new StringBuilder();
for (ILoggingEvent event : List.copyOf(platformLines.list)) {
text.append(event.getFormattedMessage()).append('\n');
}
return text.toString();
}
private String siteText(String siteId) {
return String.join("\n", siteLogs.tail(siteId, LogKind.ACCESS, 1000));
}
/** Waits (up to 15 s) until the site's access log has a line containing {@code text}. */
private void awaitSiteLine(String siteId, String text) {
await(() -> siteText(siteId).contains(text),
() -> "no access line with [" + text + "] for " + siteId + ": " + siteText(siteId));
}
private static void await(BooleanSupplier condition, Supplier<String> failure) {
long deadline = System.nanoTime() + 15_000_000_000L;
while (System.nanoTime() < deadline) {
if (condition.getAsBoolean()) {
return;
}
try {
Thread.sleep(50);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
break;
}
}
throw new AssertionError(failure.get());
}
}
Loaded 100 of 119 files, more files were not shown because too many files have changed in this diff. Show more