Runway 1.2.0

This commit is contained in:
Runway committed 2026-10-30 11:24:46 -06:00
1 parent 5fa0c1ef9f
commit 037fba671a
90 files changed
+2744 -561

No files matched your search

+84
View File
@@ -2,6 +2,90 @@
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 ## [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 _A patch release: the access log now records every public request that gets past the protection edge, including the
+128 -16
View File
@@ -1950,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;
@@ -1981,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 '…';
@@ -1992,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
@@ -2018,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.
@@ -2043,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.
@@ -2508,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
@@ -2543,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;
+12 -5
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. |
@@ -928,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.
@@ -1001,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
+33 -5
View File
@@ -235,7 +235,12 @@ site refused, such as a `503` while it is in maintenance) and its **audit journa
(`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 —
@@ -257,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
@@ -836,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
@@ -1316,12 +1336,20 @@ 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
@@ -1361,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,14 +121,65 @@ 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 {
+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,14 +74,65 @@ 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 {
+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,
@RequestParam(name = "host", defaultValue = "") String host,
@RequestParam(name = "port", defaultValue = "") String port,
@RequestParam(name = "database", defaultValue = "") String database,
@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) { RedirectAttributes flash) {
DatabaseProps props = new DatabaseProps(); if (!tester.testable().contains(provider)) {
props.setProvider(provider); return result(flash, new ConnectionTester.Result(ConnectionTester.Category.NO_PROVIDER,
props.setNamespace(namespace.isBlank() ? null : namespace); ProviderChoice.plugin(provider.isBlank() ? "?" : provider)));
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.saved(provider));
return result(flash, tester.newSettings(props, password));
} }
@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.2</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-29T18:30: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.2</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 {
Files.move(old, siteDir); if (BackupService.settle(siteDir, workDir)) {
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. } 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 {}", log.error("could not recover site '{}' automatically — its content is preserved at {}",
siteId, old, e); siteId, workDir, e);
continue; continue;
} }
} BackupService.deleteRecursively(workDir); // settled — the leftovers (a staging copy) are safe to drop
BackupService.deleteRecursively(workDir); // recovered or not needed — the leftovers 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());
if (staged.settled()) {
deleteRecursively(staged.work()); 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);
} catch (IOException swapFailed) {
if (Files.exists(old) && !Files.exists(siteDir)) {
try { try {
move(old, siteDir); // roll back move(staging, siteDir);
} catch (IOException rollbackFailed) { } catch (IOException recreated) {
if (!setAsideIfNotASite(siteDir, late)) {
throw recreated;
}
move(staging, siteDir);
}
} catch (IOException swapFailed) {
if (Files.exists(old)) {
try {
settle(siteDir, work); // rolls the original back, with any lines written meanwhile
} catch (IOException | UncheckedIOException rollbackFailed) {
// Leave `old` in place as the recovery copy — the startup sweep rolls it forward. Do NOT // 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;
@@ -98,30 +99,38 @@ 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 {
platformAuthority.require(authentication);
if (!sites.exists(siteId)) {
throw new ResponseStatusException(HttpStatus.NOT_FOUND, "no such site");
}
response.setContentType("application/zip");
response.setHeader(HttpHeaders.CONTENT_DISPOSITION,
"attachment; filename=\"" + siteId + "-backup-" + LocalDate.now() + ".zip\"");
backups.backup(siteId, response.getOutputStream());
}
/** Stream a <b>transfer</b> archive of any site — no credentials, accounts or origin hostnames. */
@GetMapping("/__app/backups/{siteId}/download-transfer")
public void downloadForTransfer(@PathVariable String siteId, Authentication authentication,
HttpServletResponse response) throws IOException { 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");
} }
response.setContentType("application/zip"); response.setContentType("application/zip");
response.setHeader(HttpHeaders.CONTENT_DISPOSITION,
"attachment; filename=\"" + siteId + "-backup-" + LocalDate.now() + ".zip\"");
if (TenantBackupsController.isHead(request)) {
return; // the headers only: no archive is built, and nothing is downloaded
}
backups.backup(siteId, response.getOutputStream());
activity.record(authentication.getName(), "backup.downloaded", siteId + " (full)");
}
/** Stream a <b>transfer</b> archive of any site — no credentials, accounts or origin hostnames. */
@GetMapping("/__app/backups/{siteId}/download-transfer")
public void downloadForTransfer(@PathVariable String siteId, Authentication authentication,
HttpServletRequest request, HttpServletResponse response) throws IOException {
platformAuthority.require(authentication);
if (!sites.exists(siteId)) {
throw new ResponseStatusException(HttpStatus.NOT_FOUND, "no such site");
}
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. */
@@ -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 {
@@ -62,11 +72,13 @@ public class TenantBackupsController {
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 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) { mx.quest.runway.platform.PlatformSettingsStore platform, SiteLogService siteLog) {
this.siteLog = siteLog;
this.platform = platform; this.platform = platform;
this.policy = policy; this.policy = policy;
this.siteResolver = siteResolver; this.siteResolver = siteResolver;
@@ -120,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);
@@ -138,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");
} }
@@ -158,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");
} }
/** /**
@@ -173,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)
@@ -181,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"))
@@ -190,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";
} }
@@ -204,6 +236,7 @@ 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); redirect.addFlashAttribute(AppBackupsController.REVIEW_HOSTS, Boolean.TRUE);
} catch (UnsupportedBackupFormatException e) { } catch (UnsupportedBackupFormatException e) {
@@ -227,6 +260,7 @@ 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); redirect.addFlashAttribute(AppBackupsController.REVIEW_HOSTS, Boolean.TRUE);
} catch (UnsupportedBackupFormatException e) { } catch (UnsupportedBackupFormatException e) {
@@ -238,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());
} }
@@ -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()) {
@@ -1194,6 +1194,7 @@ op.audit.action.site.created-from-backup=Site created from backup
op.audit.action.demo.installed=Demo site installed op.audit.action.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
@@ -1225,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
@@ -1195,6 +1195,7 @@ op.audit.action.site.created-from-backup=Sitio creado desde una copia de segurid
op.audit.action.demo.installed=Sitio de demostración instalado op.audit.action.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
@@ -1226,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
@@ -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">
@@ -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 ------------------------------------
/** /**
@@ -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 {
@@ -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");
}
} }
+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.2</version> <version>1.2.0</version>
</parent> </parent>
<artifactId>runway-dist</artifactId> <artifactId>runway-dist</artifactId>
+1 -1
View File
@@ -6,7 +6,7 @@ name: Essential Protection
# The essential plugin ships with the kernel, in the same release, on the kernel's version line (docs/SPI-STABILITY.md, # The essential plugin ships with the kernel, in the same release, on the kernel's version line (docs/SPI-STABILITY.md,
# "The essential-plugin exception"): its version is the kernel's plain MAJOR.MINOR.PATCH. Seeding compares SHA-256 # "The essential-plugin exception"): its version is the kernel's plain MAJOR.MINOR.PATCH. Seeding compares SHA-256
# hashes, not versions, and no plugin may `requires:` an essential plugin, so nothing keys on it. # hashes, not versions, and no plugin may `requires:` an essential plugin, so nothing keys on it.
version: 1.1.2 version: 1.2.0
essential: true essential: true
# The mandatory floor (SPI 1.0.0): every plugin with a mainClass declares one; the kernel's own plugin declares the # The mandatory floor (SPI 1.0.0): every plugin with a mainClass declares one; the kernel's own plugin declares the
# SPI major's floor (>=1.0.0, met by every 1.x kernel; raised only when it uses a newer SPI member), so the floor rule # SPI major's floor (>=1.0.0, met by every 1.x kernel; raised only when it uses a newer SPI member), so the floor rule
+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.2</version> <version>1.2.0</version>
</parent> </parent>
<artifactId>runway-plugin-protection</artifactId> <artifactId>runway-plugin-protection</artifactId>
@@ -35,7 +35,7 @@ class ProtectionDescriptorK4Test {
PluginDescriptor descriptor = shipped(); PluginDescriptor descriptor = shipped();
assertEquals("protection", descriptor.id()); assertEquals("protection", descriptor.id());
assertTrue(descriptor.isEssential()); assertTrue(descriptor.isEssential());
assertEquals("1.1.2", descriptor.version(), "versioned on the kernel's line"); assertEquals("1.2.0", descriptor.version(), "versioned on the kernel's line");
assertEquals(PluginVersion.parse("1.0.0"), descriptor.spiFloor()); assertEquals(PluginVersion.parse("1.0.0"), descriptor.spiFloor());
assertEquals(PluginVersion.parse(RunwaySpi.VERSION).major(), descriptor.spiFloor().major(), assertEquals(PluginVersion.parse(RunwaySpi.VERSION).major(), descriptor.spiFloor().major(),
"the floor names the kernel's own SPI major line"); "the floor names the kernel's own SPI major line");
@@ -60,7 +60,7 @@
</div> </div>
<div class="mb-3"> <div class="mb-3">
<label class="form-label" id="pr-l-secretKey" for="pr-secretKey">Secret key</label> <label class="form-label" id="pr-l-secretKey" for="pr-secretKey">Secret key</label>
<input class="form-control" id="pr-secretKey" name="secretKey" type="password" value="" autocomplete="off"> <input class="form-control" id="pr-secretKey" name="secretKey" type="password" value="" autocomplete="new-password">
<small class="form-hint" id="pr-h-secretKey">Verified server-side, stored encrypted. Leave blank to <small class="form-hint" id="pr-h-secretKey">Verified server-side, stored encrypted. Leave blank to
keep the current secret.</small> keep the current secret.</small>
</div> </div>
@@ -57,7 +57,7 @@
</div> </div>
<div class="mb-3"> <div class="mb-3">
<label class="form-label" id="pr-l-secretKey" for="pr-secretKey">Secret key</label> <label class="form-label" id="pr-l-secretKey" for="pr-secretKey">Secret key</label>
<input class="form-control" id="pr-secretKey" name="secretKey" type="password" value="" autocomplete="off"> <input class="form-control" id="pr-secretKey" name="secretKey" type="password" value="" autocomplete="new-password">
<small class="form-hint" id="pr-h-secretKey">Verified server-side, stored encrypted. Leave blank <small class="form-hint" id="pr-h-secretKey">Verified server-side, stored encrypted. Leave blank
to keep the current secret.</small> to keep the current secret.</small>
</div> </div>
+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.2</version> <version>1.2.0</version>
</parent> </parent>
<artifactId>runway-spi-testkit</artifactId> <artifactId>runway-spi-testkit</artifactId>
@@ -18,7 +18,8 @@ import mx.quest.runway.spi.service.PluginSettings;
* .defaults(Map.of("enabled", true, "limit", 20)) * .defaults(Map.of("enabled", true, "limit", 20))
* .site("acme", Map.of("limit", 50)) * .site("acme", Map.of("limit", 50))
* .secret("acme", "smtpPassword", "s3cret") * .secret("acme", "smtpPassword", "s3cret")
* .appSecret("password", "app-s3cret"); * .appSecret("password", "app-s3cret")
* .savedApp("host", "db.example.com");
* MyWidget widget = new MyWidget(settings); * MyWidget widget = new MyWidget(settings);
* }</pre> * }</pre>
* *
@@ -34,6 +35,7 @@ public final class FakePluginSettings implements PluginSettings {
private final Map<String, Map<String, Object>> sites = new ConcurrentHashMap<>(); private final Map<String, Map<String, Object>> sites = new ConcurrentHashMap<>();
private final Map<String, String> secrets = new ConcurrentHashMap<>(); private final Map<String, String> secrets = new ConcurrentHashMap<>();
private final Map<String, String> appSecrets = new ConcurrentHashMap<>(); private final Map<String, String> appSecrets = new ConcurrentHashMap<>();
private final Map<String, String> savedApp = new ConcurrentHashMap<>();
/** The declared {@code siteSettings:} defaults (replaces any set before). */ /** The declared {@code siteSettings:} defaults (replaces any set before). */
public FakePluginSettings defaults(Map<String, ?> declaredDefaults) { public FakePluginSettings defaults(Map<String, ?> declaredDefaults) {
@@ -59,6 +61,15 @@ public final class FakePluginSettings implements PluginSettings {
return this; return this;
} }
/**
* An app-level value as {@link #savedApp(String)} answers it: what the operator saved and a restart would apply
* (a secret in clear). Pass the declared default yourself if the test needs one.
*/
public FakePluginSettings savedApp(String key, String value) {
savedApp.put(key, value);
return this;
}
@Override @Override
public SettingsView site(String siteId) { public SettingsView site(String siteId) {
Map<String, Object> values = new LinkedHashMap<>(defaults); Map<String, Object> values = new LinkedHashMap<>(defaults);
@@ -83,6 +94,12 @@ public final class FakePluginSettings implements PluginSettings {
return value == null || value.isBlank() ? Optional.empty() : Optional.of(value); return value == null || value.isBlank() ? Optional.empty() : Optional.of(value);
} }
@Override
public Optional<String> savedApp(String key) {
String value = key == null ? null : savedApp.get(key);
return value == null || value.isBlank() ? Optional.empty() : Optional.of(value);
}
private static String requireSafe(String siteId) { private static String requireSafe(String siteId) {
if (siteId == null || siteId.equals(".") || siteId.equals("..") || !SAFE_ID.matcher(siteId).matches()) { if (siteId == null || siteId.equals(".") || siteId.equals("..") || !SAFE_ID.matcher(siteId).matches()) {
throw new IllegalArgumentException("unsafe site id: " + siteId); throw new IllegalArgumentException("unsafe site id: " + siteId);
@@ -56,4 +56,14 @@ class FakePluginSettingsTest {
assertEquals(Optional.empty(), settings.appSecret("other")); assertEquals(Optional.empty(), settings.appSecret("other"));
assertEquals(Optional.empty(), settings.appSecret(null)); assertEquals(Optional.empty(), settings.appSecret(null));
} }
@Test
void savedAppValuesAreReturnedAndBlankOrUnsetOnesAreAbsent() {
FakePluginSettings settings = new FakePluginSettings().savedApp("host", "db.example").savedApp("blank", " ")
.appSecret("password", "running");
assertEquals(Optional.of("db.example"), settings.savedApp("host"));
assertEquals(Optional.empty(), settings.savedApp("blank"));
assertEquals(Optional.empty(), settings.savedApp("password"), "independent of the running secrets");
assertEquals(Optional.empty(), settings.savedApp(null));
}
} }
+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.2</version> <version>1.2.0</version>
</parent> </parent>
<artifactId>runway-spi</artifactId> <artifactId>runway-spi</artifactId>
@@ -77,6 +77,11 @@ public final class RunwaySpi {
* empty), the calling plugin's own {@code secret}-typed <b>app-level</b> setting in clear. Before, such a * empty), the calling plugin's own {@code secret}-typed <b>app-level</b> setting in clear. Before, such a
* setting reached the plugin only in its stored {@code ENC(...)} form, which a plugin cannot decrypt. A * setting reached the plugin only in its stored {@code ENC(...)} form, which a plugin cannot decrypt. A
* plugin that calls it declares {@code requiresSpi: ">=1.1.0"}.</li> * plugin that calls it declares {@code requiresSpi: ">=1.1.0"}.</li>
* <li><b>1.2.0</b> — one addition:
* {@link mx.quest.runway.spi.service.PluginSettings#savedApp(String)} (a {@code default} method answering
* empty), the calling plugin's own app-level setting as saved now rather than as the running application
* started with it, so a plugin can check settings before the restart that applies them. A plugin that
* calls it declares {@code requiresSpi: ">=1.2.0"}.</li>
* </ul> * </ul>
* *
* <p>Before 0.4.0: 0.3.4 added {@link HeadContributor#headInputs(String)} (a {@code default} method returning an empty list: * <p>Before 0.4.0: 0.3.4 added {@link HeadContributor#headInputs(String)} (a {@code default} method returning an empty list:
@@ -104,7 +109,7 @@ public final class RunwaySpi {
* {@link mx.quest.runway.spi.model.WidgetView} (with the old-arity constructor kept). All additive and * {@link mx.quest.runway.spi.model.WidgetView} (with the old-arity constructor kept). All additive and
* binary-compatible (no existing member changed). * binary-compatible (no existing member changed).
*/ */
public static final String VERSION = "1.1.0"; public static final String VERSION = "1.2.0";
/** /**
* The SPI version of the <b>running</b> kernel — unlike {@link #VERSION}, which the compiler inlines into the * The SPI version of the <b>running</b> kernel — unlike {@link #VERSION}, which the compiler inlines into the
@@ -28,7 +28,9 @@ import mx.quest.runway.spi.model.SettingsView;
* <p>App-level (platform-wide) plugin settings ({@code settings:} in {@code plugin.yml}) bind through Spring * <p>App-level (platform-wide) plugin settings ({@code settings:} in {@code plugin.yml}) bind through Spring
* {@code @ConfigurationProperties} under {@code runway.plugin.<id>.*}, which is descriptor contract. The one * {@code @ConfigurationProperties} under {@code runway.plugin.<id>.*}, which is descriptor contract. The one
* exception is a {@code secret}-typed app-level setting: it binds there only in its stored {@code ENC(...)} form, so * exception is a {@code secret}-typed app-level setting: it binds there only in its stored {@code ENC(...)} form, so
* {@link #appSecret(String)} hands it out in clear (since SPI 1.1.0). * {@link #appSecret(String)} hands it out in clear (since SPI 1.1.0). Those bindings are the values the running
* application started with; {@link #savedApp(String)} reads what is saved now, which a restart will apply (since SPI
* 1.2.0).
* *
* @since SPI 0.4.0 * @since SPI 0.4.0
*/ */
@@ -76,4 +78,25 @@ public interface PluginSettings {
default Optional<String> appSecret(String key) { default Optional<String> appSecret(String key) {
return Optional.empty(); return Optional.empty();
} }
/**
* An <b>app-level</b> setting of the calling plugin as it is <b>saved now</b>, which may differ from the running
* value until the restart that applies it. It lets a plugin check settings before that restart, for example by
* testing a connection with them.
*
* <p>The answer is the value stored in the plugin's app-level settings file when it is not blank (a {@code secret}
* in clear, decrypted as {@link #appSecret(String)} does), otherwise the declared default of a non-secret
* setting, otherwise empty. It is read from the file on each call, so call it when needed rather than in a loop.
*
* <p>Empty when the key is not declared in the plugin's own {@code settings:} (a key declared only in
* {@code siteSettings:} does not count, and no plugin can name another's), and for an encrypted secret that
* cannot be decrypted (logged once per key, never with the value).
*
* @param key the setting key as declared in {@code settings:}
* @return the saved value, or empty
* @since SPI 1.2.0
*/
default Optional<String> savedApp(String key) {
return Optional.empty();
}
} }
@@ -28,7 +28,7 @@ class K3RecordsTest {
@Test @Test
void theSpiIsAtOneZero() { void theSpiIsAtOneZero() {
assertEquals("1.1.0", RunwaySpi.VERSION); assertEquals("1.2.0", RunwaySpi.VERSION);
} }
// --- LocalizedUrl ---------------------------------------------------------------------------------------- // --- LocalizedUrl ----------------------------------------------------------------------------------------