Runway 1.2.0
This commit is contained in:
1 parent
5fa0c1ef9f
commit
037fba671a
90 files changed
+2737
-554
No files matched your search
@@ -2,6 +2,90 @@
|
||||
|
||||
All notable changes are recorded here. Versions follow [Semantic Versioning](https://semver.org/).
|
||||
|
||||
## [1.2.0] — 2026-10-30
|
||||
|
||||
_A minor release: a site's audit journal records its backups (saved, downloaded, deleted, restored), a restore no
|
||||
longer erases the site's logs, password settings are never filled in by the browser with your console login, and
|
||||
the plugin contract gains one method (SPI `1.2.0`: `PluginSettings.savedApp`) that the database plugins 2.0.0 use for
|
||||
their connection tests. Every plugin that runs on 1.1.2 loads unchanged._
|
||||
|
||||
### Upgrading — read this first
|
||||
|
||||
**From `1.1.2`: a kernel upgrade, no flag.** From `1.1.1`, `1.1.0`, `1.0.1` or `1.0.0`, read the *Upgrading*
|
||||
sections of the releases in between first, then install this release directly. Paths are the installer defaults
|
||||
(`/opt/runway`, `/opt/runway-data`).
|
||||
|
||||
**The database plugins.** `database`, `database-postgresql` and `database-mariadb` 1.0.0 keep running on this
|
||||
release unchanged. Their 2.0.0, released with it, needs it: the server's settings move from the `database` plugin to
|
||||
the provider plugin, and the connection tests move to the `database` plugin's settings page. Upgrade the kernel
|
||||
first, then those three plugins together, and move the settings **before** saving the `database` plugin's settings
|
||||
form (Administration §11.1, *Upgrading from database 1.x*; the plugins' own release notes).
|
||||
|
||||
**1. Back up.** Take each site's backup (**Backups**) and copy `/opt/runway-data/external/` somewhere **outside**
|
||||
`external/plugins/`.
|
||||
|
||||
**2. Upgrade the kernel:**
|
||||
|
||||
```bash
|
||||
chmod +x runway-1.2.0.bin
|
||||
sudo ./runway-1.2.0.bin -y
|
||||
```
|
||||
|
||||
The essential plugin moves with the kernel to `1.2.0` (its two settings pages mark the reCAPTCHA secret as a new
|
||||
password), so the installer refreshes it; expect these lines, once (a template you edited is backed up instead, and
|
||||
the line names the copy):
|
||||
|
||||
```
|
||||
refreshing bundled plugin 'protection' from this release (it moves with the kernel; files you edited are backed up)
|
||||
plugin 'protection': plugin.yml replaced (the previous one kept as plugin.yml.bak, for a rollback)
|
||||
plugin 'protection': runway-plugin-protection.jar replaced (the previous one kept as runway-plugin-protection.jar.bak, for a rollback)
|
||||
plugin 'protection': templates/admin-app.html updated (unchanged since it was installed — no backup needed)
|
||||
plugin 'protection': templates/site-protection.html updated (unchanged since it was installed — no backup needed)
|
||||
keeping the bundled plugins in the release: /opt/runway-1.2.0/seed/ (the repair copy — Administration §12)
|
||||
```
|
||||
|
||||
**3. Check.**
|
||||
- **About Runway** shows `1.2.0`.
|
||||
- On **Plugins**, every row is *Loaded* and none *Blocked*; protection shows `1.2.0`.
|
||||
- On a site's console, save a backup (**Backups**, *Save a backup on the server*): the site's **Logs** journal
|
||||
shows `backup.saved` with your name and the backup's.
|
||||
|
||||
**4. Rollback**, if needed: `sudo bash runway-1.1.2.bin -y` puts 1.1.2 back, its protection files included. Nothing
|
||||
this release saves is read differently by 1.1.2. Put the database plugins back to 1.0.0 first if you moved them to
|
||||
2.0.0 (with the server's settings back in `database.yml`): 2.0.0 needs SPI `1.2.0` and is refused by 1.1.2.
|
||||
|
||||
### Added
|
||||
|
||||
- **SPI 1.2.0: `PluginSettings.savedApp(key)`.** A plugin can read one of its own app-level settings as it is saved
|
||||
now, before the restart that applies it (a secret in clear), so it can check a change first. The database plugins
|
||||
2.0.0 use it for their connection test. Existing plugins load unchanged: the method only adds to the contract. See
|
||||
`docs/SPI-STABILITY.md`.
|
||||
- **The site's audit journal records backups.** On the site console, saving a backup on the server (`backup.saved`),
|
||||
downloading one (`backup.downloaded`: `full`, `transfer`, or `full` and a saved backup's name),
|
||||
deleting one (`backup.deleted`) and restoring the site (`site.restored`) are now journal lines, with who did it. A
|
||||
refused act writes nothing. On the application console, downloads join the platform's activity log, which already
|
||||
had saves, deletes and restores.
|
||||
- **Journal labels for every recorded action.** User changes (`user.updated`, `user.suspended`, `user.resumed`) and
|
||||
static-file changes (`static.uploaded`, `static.folder-created`, `static.deleted`) were recorded but shown only by
|
||||
their key; they now have English and Spanish labels like the others.
|
||||
|
||||
### Fixed
|
||||
|
||||
- **A restore erased the site's logs.** A restore replaced the whole site folder, and a backup never carries logs
|
||||
or stats, so the access log and the audit journal started again from nothing (the bandwidth history file too,
|
||||
until its next periodic save rewrote it from memory). A restore now keeps both folders; if it is interrupted, or
|
||||
the logs cannot be carried over at once, the next restore of the site or the next start finishes it. Logs or
|
||||
stats inside an archive are ignored: no backup writes them.
|
||||
- **A restore could lose the site it replaced.** If a log line was written in the instant between moving the site
|
||||
folder aside and moving the restored copy in, the site folder came back holding only logs: the restore failed, the
|
||||
rollback was skipped, and the next start deleted the previous copy. That folder is now set aside and the move
|
||||
retried, and a folder without a `site.yml` is never taken for the site.
|
||||
- **A browser could fill a plugin's password setting with your own console login.** On a plugin's settings page, a
|
||||
text box followed by a password box looks like a login form, and browsers fill it in with the saved console
|
||||
username and password, ignoring `autocomplete="off"`. A save would then store your console password as the
|
||||
plugin's credential. Password settings (plugin and widget settings, the protection plugin's CAPTCHA secret, a
|
||||
master administrator's password reset) are now marked as new passwords, which browsers do not fill in.
|
||||
|
||||
## [1.1.2] — 2026-10-29
|
||||
|
||||
_A patch release: the access log now records every public request that gets past the protection edge, including the
|
||||
|
||||
+128
-16
@@ -1950,14 +1950,80 @@ chosen in settings. Nothing uses them unless a plugin that needs a database is i
|
||||
|
||||
| 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-postgresql` | The PostgreSQL provider: bundles the pgjdbc driver. 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` | 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 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) 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),
|
||||
then restart. A plugin that needs the database declares it, so without `database` it shows as **Blocked** with the
|
||||
Install `database` and the provider for your server, then restart. With one provider installed, it is the one used;
|
||||
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.
|
||||
|
||||
**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`):
|
||||
|
||||
- `<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
|
||||
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
|
||||
-- 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 '…';
|
||||
@@ -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**
|
||||
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 |
|
||||
|---|---|
|
||||
| `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. |
|
||||
| `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. |
|
||||
| `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. |
|
||||
| `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. |
|
||||
| `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
|
||||
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
|
||||
provider*, or *Server not supported*; the provider, server version, driver, pool use and the number of sites with
|
||||
data;
|
||||
- **Test running connection** (the live pool) and **Test these settings** (typed values, one throwaway connection,
|
||||
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;
|
||||
- a link to the settings page and its **Connection tests** (above);
|
||||
- **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
|
||||
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.
|
||||
|
||||
**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
|
||||
deleted on one node has its schema dropped once, by that node. To change the server or the provider, stop **every**
|
||||
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
|
||||
*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
|
||||
(*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
|
||||
@@ -2543,7 +2655,7 @@ with:
|
||||
|
||||
- `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
|
||||
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
|
||||
(`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;
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
> 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
|
||||
> 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
|
||||
> [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
|
||||
@@ -104,7 +104,7 @@ boots.
|
||||
> **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
|
||||
> 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
|
||||
> 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 |
|
||||
|---|---|---|
|
||||
| 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 |
|
||||
| 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 |
|
||||
@@ -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 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` |
|
||||
| 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 |
|
||||
|
||||
**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 |
|
||||
|---|---|
|
||||
| `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. |
|
||||
| `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. |
|
||||
@@ -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
|
||||
`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
|
||||
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
|
||||
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
|
||||
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
|
||||
|
||||
@@ -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:
|
||||
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`,
|
||||
`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`,
|
||||
`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 —
|
||||
@@ -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
|
||||
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
|
||||
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
|
||||
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
|
||||
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
|
||||
|
||||
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
|
||||
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
|
||||
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
|
||||
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**
|
||||
(how visitors reach it) stay as the platform operator has set them now, whatever the backup says.
|
||||
**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; 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
|
||||
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) |
|
||||
| | Hostnames and base URL (replaced with a placeholder) |
|
||||
| | 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 |
|
||||
|
||||
The recipient restores it exactly like a backup. Their copy comes up with your content and appearance, no
|
||||
|
||||
+11
-1
@@ -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 |
|
||||
|---|---|---|---|
|
||||
| `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 |
|
||||
| `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 |
|
||||
@@ -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
|
||||
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 SPI is **binary API**. A plugin compiled against a released `runway-spi` keeps loading on any later version of
|
||||
|
||||
@@ -2,6 +2,22 @@
|
||||
|
||||
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
|
||||
|
||||
First public release of `database-mariadb`: the MariaDB 10.11+ provider for the `database` plugin, with MariaDB
|
||||
|
||||
@@ -2,13 +2,17 @@
|
||||
|
||||
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
|
||||
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/`
|
||||
- **Requires:** `database >= 1.0.0`, Runway SPI `1.1.0` or later
|
||||
- **Plugin id:** `database-mariadb` (v`2.0.0`) — install folder `external/plugins/database-mariadb/`
|
||||
- **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
|
||||
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`.
|
||||
|
||||
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).
|
||||
@@ -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
|
||||
`-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`.
|
||||
|
||||
## 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).
|
||||
@@ -5,16 +5,46 @@
|
||||
# published next to this plugin's release) and builds a configured
|
||||
# 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/.
|
||||
# =============================================================================
|
||||
id: database-mariadb
|
||||
name: Database — MariaDB
|
||||
version: 1.0.0
|
||||
version: 2.0.0
|
||||
|
||||
mainClass: mx.quest.database.mariadb.MariaDbProviderConfig
|
||||
|
||||
# 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 }
|
||||
@@ -17,7 +17,7 @@
|
||||
|
||||
<groupId>mx.quest</groupId>
|
||||
<artifactId>runway-plugin-database-mariadb</artifactId>
|
||||
<version>1.0.0</version>
|
||||
<version>2.0.0</version>
|
||||
<packaging>jar</packaging>
|
||||
<name>Runway Database — MariaDB</name>
|
||||
<licenses>
|
||||
@@ -38,11 +38,11 @@
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
<!-- Reproducible builds: pins every archive entry's timestamp. Bump at each release. -->
|
||||
<project.build.outputTimestamp>2026-10-29T00:00:00Z</project.build.outputTimestamp>
|
||||
<!-- The runway-spi this plugin compiles against: SPI 1.1.0 adds PluginSettings.appSecret. -->
|
||||
<runway.version>1.1.0</runway.version>
|
||||
<!-- The runway-spi this plugin compiles against: SPI 1.2.0 adds PluginSettings.savedApp. -->
|
||||
<runway.version>1.2.0</runway.version>
|
||||
<!-- The database plugin whose SPI this provider implements (provided: the shared plugin class loader
|
||||
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. -->
|
||||
<mariadb.version>3.5.8</mariadb.version>
|
||||
</properties>
|
||||
@@ -160,6 +160,9 @@
|
||||
<copy todir="${stage}/lib">
|
||||
<fileset dir="${project.build.directory}/staged-lib"/>
|
||||
</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). -->
|
||||
<fail message="no library in ${stage}/lib">
|
||||
<condition><resourcecount when="equal" count="0">
|
||||
|
||||
@@ -4,9 +4,12 @@ import java.sql.SQLException;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.Optional;
|
||||
import java.util.function.Supplier;
|
||||
import javax.sql.DataSource;
|
||||
import mx.quest.database.spi.ConnectionSettings;
|
||||
import mx.quest.database.spi.DatabaseProvider;
|
||||
import mx.quest.database.spi.ProviderSettings;
|
||||
import org.mariadb.jdbc.MariaDbDataSource;
|
||||
|
||||
/**
|
||||
@@ -27,6 +30,25 @@ public final class MariaDbProvider implements DatabaseProvider {
|
||||
|
||||
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
|
||||
public String id() {
|
||||
return "mariadb";
|
||||
@@ -95,4 +117,14 @@ public final class MariaDbProvider implements DatabaseProvider {
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Optional<ProviderSettings> runningSettings() {
|
||||
return Optional.ofNullable(running.get());
|
||||
}
|
||||
|
||||
@Override
|
||||
public Optional<ProviderSettings> savedSettings() {
|
||||
return Optional.ofNullable(saved.get());
|
||||
}
|
||||
}
|
||||
+22
-3
@@ -1,14 +1,33 @@
|
||||
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.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)
|
||||
public class MariaDbProviderConfig {
|
||||
|
||||
@Bean
|
||||
public MariaDbProvider databaseMariadbProvider() {
|
||||
return new MariaDbProvider();
|
||||
@ConfigurationProperties("runway.plugin.database-mariadb")
|
||||
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));
|
||||
}
|
||||
}
|
||||
+61
-3
@@ -20,14 +20,21 @@ import java.time.temporal.ChronoUnit;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Calendar;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.TimeZone;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
import java.util.stream.Stream;
|
||||
import mx.quest.database.spi.ConnectionSettings;
|
||||
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.springframework.boot.context.properties.EnableConfigurationProperties;
|
||||
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.core.env.MapPropertySource;
|
||||
|
||||
class MariaDbProviderTest {
|
||||
|
||||
@@ -114,15 +121,66 @@ class MariaDbProviderTest {
|
||||
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
|
||||
void theConfigurationRegistersOneProviderNamedForThePlugin() {
|
||||
try (AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(
|
||||
MariaDbProviderConfig.class)) {
|
||||
try (AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext()) {
|
||||
ctx.registerBean(PluginSettings.class, FakePluginSettings::new);
|
||||
ctx.register(Binding.class, MariaDbProviderConfig.class);
|
||||
ctx.refresh();
|
||||
assertThat(ctx.getBeanNamesForType(mx.quest.database.spi.DatabaseProvider.class))
|
||||
.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
|
||||
void theCompiledClassesLinkNoHostInternals() throws Exception {
|
||||
Path classes = Path.of("target", "classes");
|
||||
|
||||
@@ -2,6 +2,22 @@
|
||||
|
||||
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
|
||||
|
||||
First public release of `database-postgresql`: the PostgreSQL 14+ provider for the `database` plugin, with the
|
||||
|
||||
@@ -2,11 +2,15 @@
|
||||
|
||||
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
|
||||
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/`
|
||||
- **Requires:** `database >= 1.0.0`, Runway SPI `1.1.0` or later
|
||||
- **Plugin id:** `database-postgresql` (v`2.0.0`) — install folder `external/plugins/database-postgresql/`
|
||||
- **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`
|
||||
|
||||
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).
|
||||
@@ -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
|
||||
`-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`.
|
||||
|
||||
## 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.
|
||||
@@ -4,16 +4,44 @@
|
||||
# driver (BSD-2-Clause, in lib/) and builds a configured DataSource; every
|
||||
# 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/.
|
||||
# =============================================================================
|
||||
id: database-postgresql
|
||||
name: Database — PostgreSQL
|
||||
version: 1.0.0
|
||||
version: 2.0.0
|
||||
|
||||
mainClass: mx.quest.database.postgresql.PostgresProviderConfig
|
||||
|
||||
# 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 }
|
||||
@@ -17,7 +17,7 @@
|
||||
|
||||
<groupId>mx.quest</groupId>
|
||||
<artifactId>runway-plugin-database-postgresql</artifactId>
|
||||
<version>1.0.0</version>
|
||||
<version>2.0.0</version>
|
||||
<packaging>jar</packaging>
|
||||
<name>Runway Database — PostgreSQL</name>
|
||||
<licenses>
|
||||
@@ -38,11 +38,11 @@
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
<!-- Reproducible builds: pins every archive entry's timestamp. Bump at each release. -->
|
||||
<project.build.outputTimestamp>2026-10-29T00:00:00Z</project.build.outputTimestamp>
|
||||
<!-- The runway-spi this plugin compiles against: SPI 1.1.0 adds PluginSettings.appSecret. -->
|
||||
<runway.version>1.1.0</runway.version>
|
||||
<!-- The runway-spi this plugin compiles against: SPI 1.2.0 adds PluginSettings.savedApp. -->
|
||||
<runway.version>1.2.0</runway.version>
|
||||
<!-- The database plugin whose SPI this provider implements (provided: the shared plugin class loader
|
||||
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. -->
|
||||
<postgresql.version>42.7.10</postgresql.version>
|
||||
</properties>
|
||||
@@ -138,6 +138,9 @@
|
||||
<copy todir="${stage}/lib">
|
||||
<fileset dir="${project.build.directory}/staged-lib"/>
|
||||
</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). -->
|
||||
<fail message="no library in ${stage}/lib">
|
||||
<condition><resourcecount when="equal" count="0">
|
||||
|
||||
+38
@@ -1,9 +1,12 @@
|
||||
package mx.quest.database.postgresql;
|
||||
|
||||
import java.util.Objects;
|
||||
import java.util.Optional;
|
||||
import java.util.function.Supplier;
|
||||
import javax.sql.DataSource;
|
||||
import mx.quest.database.spi.ConnectionSettings;
|
||||
import mx.quest.database.spi.DatabaseProvider;
|
||||
import mx.quest.database.spi.ProviderSettings;
|
||||
import org.postgresql.ds.PGSimpleDataSource;
|
||||
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 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
|
||||
public String id() {
|
||||
return "postgresql";
|
||||
@@ -76,4 +98,20 @@ public final class PostgresProvider implements DatabaseProvider {
|
||||
private static int seconds(long 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);
|
||||
}
|
||||
}
|
||||
+22
-3
@@ -1,14 +1,33 @@
|
||||
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.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)
|
||||
public class PostgresProviderConfig {
|
||||
|
||||
@Bean
|
||||
public PostgresProvider databasePostgresqlProvider() {
|
||||
return new PostgresProvider();
|
||||
@ConfigurationProperties("runway.plugin.database-postgresql")
|
||||
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));
|
||||
}
|
||||
}
|
||||
+61
-3
@@ -12,14 +12,21 @@ import java.sql.Statement;
|
||||
import java.time.Duration;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
import java.util.stream.Stream;
|
||||
import mx.quest.database.spi.ConnectionSettings;
|
||||
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.postgresql.ds.PGSimpleDataSource;
|
||||
import org.springframework.boot.context.properties.EnableConfigurationProperties;
|
||||
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.core.env.MapPropertySource;
|
||||
|
||||
class PostgresProviderTest {
|
||||
|
||||
@@ -67,15 +74,66 @@ class PostgresProviderTest {
|
||||
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
|
||||
void theConfigurationRegistersOneProviderNamedForThePlugin() {
|
||||
try (AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(
|
||||
PostgresProviderConfig.class)) {
|
||||
try (AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext()) {
|
||||
ctx.registerBean(PluginSettings.class, FakePluginSettings::new);
|
||||
ctx.register(Binding.class, PostgresProviderConfig.class);
|
||||
ctx.refresh();
|
||||
assertThat(ctx.getBeanNamesForType(mx.quest.database.spi.DatabaseProvider.class))
|
||||
.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
|
||||
void theCompiledClassesLinkNoHostInternals() throws Exception {
|
||||
Path classes = Path.of("target", "classes");
|
||||
|
||||
@@ -2,6 +2,53 @@
|
||||
|
||||
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
|
||||
|
||||
First public release of `database`: plugins can keep their own data in PostgreSQL 14+ or MariaDB 10.11+, through a
|
||||
|
||||
@@ -11,23 +11,31 @@ settings — stays on files; this plugin is for plugins.
|
||||
resuming after a failure.
|
||||
- **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.
|
||||
- **A health screen** in the application console (**Settings → Database**) with connection tests and recovery
|
||||
actions; one line on each site's dashboard.
|
||||
- **A health screen** in the application console (**Settings → Database**) with recovery actions; **connection
|
||||
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.
|
||||
|
||||
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/`
|
||||
- **Requires:** Runway with SPI `1.1.0` or later (`requiresSpi: ">=1.1.0"`) and one provider plugin
|
||||
- **Plugin id:** `database` (v`2.0.0`) — install folder `external/plugins/database/`
|
||||
- **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`
|
||||
- **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
|
||||
|
||||
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
|
||||
|
||||
|
||||
@@ -24,7 +24,7 @@ reaches every schema.
|
||||
|
||||
| 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. |
|
||||
| Engines | `PostgresEngine`, `MariaDbEngine` | **All** the SQL Runway runs, per product. |
|
||||
| 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. |
|
||||
| Scopes | `ScopeImpl`, `PluginDatabaseImpl`, `DatabasesImpl` | What consumers call. |
|
||||
| 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
|
||||
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`,
|
||||
`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.
|
||||
- The password is bound (`secretBoundTo`) to everything that decides where it goes, and the connection test reuses it
|
||||
only for exactly the running target.
|
||||
- The password is bound (`secretBoundTo`, on the provider's page) to everything that decides where it goes. The
|
||||
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).
|
||||
- The health screen needs `CONFIGURE_PLATFORM`; its recovery actions are logged with the operator's name.
|
||||
|
||||
|
||||
@@ -1,25 +1,14 @@
|
||||
# Runway Database — English
|
||||
database.menu=Database
|
||||
|
||||
database.group.connection=Connection
|
||||
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=Database product
|
||||
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.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.help=The database product. Install its provider plugin too: database-postgresql or database-mariadb.
|
||||
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.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.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.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.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.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.pretitle=Application
|
||||
@@ -46,11 +33,9 @@ database.console.namespace=Namespace
|
||||
database.console.pool=Connections in use
|
||||
database.console.schemas=Sites with data
|
||||
database.console.lastError=Last error
|
||||
database.console.tests=Connection tests
|
||||
database.console.testRunning=Test running connection
|
||||
database.console.testNew=Test these settings
|
||||
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.settings=Settings and tests
|
||||
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.settings.link=Settings and connection tests
|
||||
database.console.issues=Plugin tables needing attention
|
||||
database.console.none=None.
|
||||
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.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.unreachable=The server could not be reached.
|
||||
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.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.has=This site keeps plugin data in the database.
|
||||
database.dashboard.none=This site keeps no data in the database.
|
||||
|
||||
@@ -1,25 +1,14 @@
|
||||
# Runway Database — español
|
||||
database.menu=Base de datos
|
||||
|
||||
database.group.connection=Conexión
|
||||
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=Producto de base de datos
|
||||
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.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.help=El producto de base de datos. Instale también su plugin proveedor: database-postgresql o database-mariadb.
|
||||
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.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.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.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.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.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.pretitle=Aplicación
|
||||
@@ -46,11 +33,9 @@ database.console.namespace=Espacio de nombres
|
||||
database.console.pool=Conexiones en uso
|
||||
database.console.schemas=Sitios con datos
|
||||
database.console.lastError=Último error
|
||||
database.console.tests=Pruebas de conexión
|
||||
database.console.testRunning=Probar la conexión en uso
|
||||
database.console.testNew=Probar estos ajustes
|
||||
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.settings=Ajustes y pruebas
|
||||
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.settings.link=Ajustes y pruebas de conexión
|
||||
database.console.issues=Tablas de plugins que requieren atención
|
||||
database.console.none=Ninguno.
|
||||
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.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.unreachable=No se pudo alcanzar el servidor.
|
||||
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.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.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.
|
||||
|
||||
+12
-26
@@ -9,18 +9,21 @@
|
||||
# read only from its own jar and checked for ownership.
|
||||
# - A site's database data travels in its full backups (not in transfer copies).
|
||||
# - 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/.
|
||||
# =============================================================================
|
||||
id: database
|
||||
name: Database
|
||||
version: 1.0.0
|
||||
version: 2.0.0
|
||||
|
||||
mainClass: mx.quest.database.DatabasePluginConfig
|
||||
|
||||
# SPI 1.1.0: PluginSettings.appSecret, which reads the Runway-wide password in clear.
|
||||
requiresSpi: ">=1.1.0"
|
||||
# SPI 1.2.0: PluginSettings.savedApp, which the providers use to hand over their saved settings for the
|
||||
# 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
|
||||
# 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/
|
||||
|
||||
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 }
|
||||
|
||||
# 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:
|
||||
- { 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 }
|
||||
- { key: host, type: string, group: connection, label: database.set.host, help: database.set.host.help }
|
||||
- { 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,
|
||||
- { key: namespace, type: string, default: rw, group: provider, advanced: true, label: database.set.namespace,
|
||||
help: database.set.namespace.help }
|
||||
- { key: poolMax, type: int, default: 10, range: "2..200", group: limits, label: database.set.poolMax,
|
||||
help: database.set.poolMax.help }
|
||||
@@ -63,8 +51,6 @@ settings:
|
||||
label: database.set.statementTimeoutSeconds, help: database.set.statementTimeoutSeconds.help }
|
||||
- { key: backupBudgetMiB, type: int, default: 128, range: "1..4096", group: limits,
|
||||
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.
|
||||
menu:
|
||||
|
||||
@@ -19,7 +19,7 @@
|
||||
|
||||
<groupId>mx.quest</groupId>
|
||||
<artifactId>runway-plugin-database</artifactId>
|
||||
<version>1.0.0</version>
|
||||
<version>2.0.0</version>
|
||||
<packaging>jar</packaging>
|
||||
<name>Runway Database</name>
|
||||
<licenses>
|
||||
@@ -42,8 +42,8 @@
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
<!-- Reproducible builds: pins every archive entry's timestamp. Bump at each release. -->
|
||||
<project.build.outputTimestamp>2026-10-29T00:00:00Z</project.build.outputTimestamp>
|
||||
<!-- The runway-spi this plugin compiles against: SPI 1.1.0 adds PluginSettings.appSecret. -->
|
||||
<runway.version>1.1.0</runway.version>
|
||||
<!-- The runway-spi this plugin compiles against: SPI 1.2.0 adds PluginSettings.savedApp. -->
|
||||
<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. -->
|
||||
<hikaricp.version>7.0.2</hikaricp.version>
|
||||
<!-- 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.
|
||||
#
|
||||
# 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;
|
||||
# - 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.
|
||||
#
|
||||
# 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
|
||||
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
|
||||
cat > "$EXT/plugin-settings/database.yml" <<EOF
|
||||
runway:
|
||||
@@ -112,6 +116,38 @@ runway:
|
||||
tls: disable
|
||||
EOF
|
||||
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) ..."
|
||||
boot "$LOG"
|
||||
@@ -128,7 +164,7 @@ ck "HikariCP and the drivers are in lib/" "ls '$EXT/plugins/database/lib/'Hikari
|
||||
|
||||
echo "== connection =="
|
||||
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 =="
|
||||
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"
|
||||
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'"
|
||||
ac -L "$BASE/__app/database/test-running" --data-urlencode "_csrf=$(token < "$SCRATCH/screen.html")" \
|
||||
> "$SCRATCH/tested.html"
|
||||
ck "Test running connection: connected" "grep -qE 'Connected: (PostgreSQL|MariaDB)' '$SCRATCH/tested.html'"
|
||||
ck "a POST without the CSRF token is refused" "[ \"\$(code -b '$SCRATCH/app.jar' -X POST '$BASE/__app/database/test-running')\" = 403 ]"
|
||||
ck "the screen points to the settings page" "grep -q '/__app/plugins/database/settings#db-tests' '$SCRATCH/screen.html'"
|
||||
ck "the screen has no test form any more" "! grep -qE 'test-new|type=\"password\"' '$SCRATCH/screen.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 ]"
|
||||
|
||||
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 =="
|
||||
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)"
|
||||
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 ]"
|
||||
# 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:'"
|
||||
|
||||
|
||||
@@ -11,7 +11,6 @@ import mx.quest.database.console.DatabaseConsoleController;
|
||||
import mx.quest.database.console.DatabaseScreens;
|
||||
import mx.quest.database.internal.ConnectionTester;
|
||||
import mx.quest.database.internal.DatabaseBackup;
|
||||
import mx.quest.database.internal.DatabaseConfig;
|
||||
import mx.quest.database.internal.DatabaseCore;
|
||||
import mx.quest.database.internal.DatabaseLifecycle;
|
||||
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.DatabasesImpl;
|
||||
import mx.quest.database.internal.Migrator;
|
||||
import mx.quest.database.internal.ProviderChoice;
|
||||
import mx.quest.database.internal.SiteSchemas;
|
||||
import mx.quest.database.spi.DatabaseConsumer;
|
||||
import mx.quest.database.spi.DatabaseProvider;
|
||||
import mx.quest.runway.spi.model.PluginInfo;
|
||||
import mx.quest.runway.spi.service.Messages;
|
||||
import mx.quest.runway.spi.service.PluginSettings;
|
||||
import mx.quest.runway.spi.service.PluginSiteFiles;
|
||||
import mx.quest.runway.spi.service.RequestContext;
|
||||
import mx.quest.runway.spi.service.Sites;
|
||||
@@ -64,12 +63,11 @@ public class DatabasePluginConfig {
|
||||
}
|
||||
|
||||
@Bean
|
||||
public DatabaseRuntime databaseRuntime(DatabaseProps databaseProps, PluginSettings settings,
|
||||
ObjectProvider<DatabaseProvider> providers, PluginInfo self,
|
||||
ScheduledExecutorService databaseExecutor) {
|
||||
public DatabaseRuntime databaseRuntime(DatabaseProps databaseProps, ObjectProvider<DatabaseProvider> providers,
|
||||
PluginInfo self, ScheduledExecutorService databaseExecutor) {
|
||||
Supplier<List<DatabaseProvider>> found = () -> providers.orderedStream().toList();
|
||||
return new DatabaseRuntime(() -> DatabaseConfig.from(databaseProps, settings.appSecret("password")), found,
|
||||
workDir(self), databaseExecutor);
|
||||
return new DatabaseRuntime(() -> ProviderChoice.running(databaseProps, found.get()), workDir(self),
|
||||
databaseExecutor);
|
||||
}
|
||||
|
||||
@Bean
|
||||
@@ -115,9 +113,10 @@ public class DatabasePluginConfig {
|
||||
}
|
||||
|
||||
@Bean
|
||||
public ConnectionTester databaseConnectionTester(DatabaseRuntime databaseRuntime,
|
||||
public ConnectionTester databaseConnectionTester(DatabaseRuntime databaseRuntime, DatabaseProps databaseProps,
|
||||
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
|
||||
|
||||
+20
-31
@@ -6,10 +6,10 @@ import java.util.Optional;
|
||||
import mx.quest.database.internal.ConnectionTester;
|
||||
import mx.quest.database.internal.Consumer;
|
||||
import mx.quest.database.internal.DatabaseCore;
|
||||
import mx.quest.database.internal.DatabaseProps;
|
||||
import mx.quest.database.internal.DatabaseRuntime;
|
||||
import mx.quest.database.internal.DatabasesImpl;
|
||||
import mx.quest.database.internal.Migrator;
|
||||
import mx.quest.database.internal.ProviderChoice;
|
||||
import mx.quest.database.internal.Registry;
|
||||
import mx.quest.database.spi.Scope;
|
||||
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;
|
||||
|
||||
/**
|
||||
* The database screen in the application console ({@code /__app/database}): health, the two connection tests and
|
||||
* the migration recovery actions. Every handler needs {@code CONFIGURE_PLATFORM}, which the master and wildcard
|
||||
* The database screen in the application console ({@code /__app/database}): health and the migration recovery
|
||||
* 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,
|
||||
* 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 FLASH = "databaseFlash";
|
||||
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);
|
||||
|
||||
@@ -77,35 +83,16 @@ public class DatabaseConsoleController {
|
||||
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)
|
||||
public String testNew(@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) {
|
||||
DatabaseProps props = new DatabaseProps();
|
||||
props.setProvider(provider);
|
||||
props.setNamespace(namespace.isBlank() ? null : namespace);
|
||||
props.setHost(host);
|
||||
props.setDatabase(database);
|
||||
props.setUsername(username);
|
||||
props.setTls(tls);
|
||||
props.setCaCertificate(caCertificate);
|
||||
if (!port.isBlank()) {
|
||||
try {
|
||||
props.setPort(Integer.parseInt(port.strip()));
|
||||
} catch (NumberFormatException e) {
|
||||
return back(flash, FLASH_ERROR, console("database.test.invalid", "The settings cannot be used: {0}",
|
||||
console("database.test.port", "the port is not a number")));
|
||||
}
|
||||
public String testSaved(@RequestParam(name = "provider", defaultValue = "") String provider,
|
||||
RedirectAttributes flash) {
|
||||
if (!tester.testable().contains(provider)) {
|
||||
return result(flash, new ConnectionTester.Result(ConnectionTester.Category.NO_PROVIDER,
|
||||
ProviderChoice.plugin(provider.isBlank() ? "?" : provider)));
|
||||
}
|
||||
return result(flash, tester.newSettings(props, password));
|
||||
return result(flash, tester.saved(provider));
|
||||
}
|
||||
|
||||
@PostMapping("/recover")
|
||||
@@ -164,7 +151,9 @@ public class DatabaseConsoleController {
|
||||
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.");
|
||||
};
|
||||
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() {
|
||||
|
||||
@@ -5,8 +5,6 @@ import java.sql.Connection;
|
||||
import java.sql.SQLException;
|
||||
import java.time.Duration;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
import java.util.Optional;
|
||||
import java.util.function.Supplier;
|
||||
import javax.sql.DataSource;
|
||||
import mx.quest.database.spi.ConnectionSettings;
|
||||
@@ -15,15 +13,15 @@ import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
/**
|
||||
* The console's two connection tests. Each answers with a fixed category (and, for success, the server version);
|
||||
* the driver's own message goes only to the server log, never with a credential.
|
||||
* The connection tests on the database plugin's settings page. Each answers with a fixed category (and, for success,
|
||||
* the server version); the driver's own message goes only to the server log, never with a credential.
|
||||
*
|
||||
* <ul>
|
||||
* <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.
|
||||
* A blank password reuses the running one only when every setting the password is bound to (provider, host,
|
||||
* port, database, username, TLS, CA certificate) matches the running value, so the test cannot send the saved
|
||||
* password to a server of the tester's choosing.</li>
|
||||
* <li><b>Saved</b>: opens one throwaway connection with short timeouts from the settings saved on one provider
|
||||
* plugin's page, which the next restart would apply, and changes nothing. The test takes no typed values: a
|
||||
* form with a username and a password box is one a browser fills in with the operator's own saved login,
|
||||
* which a test would then send to whatever server the form named (the 1.x test did exactly that).</li>
|
||||
* </ul>
|
||||
*/
|
||||
public final class ConnectionTester {
|
||||
@@ -44,15 +42,23 @@ public final class ConnectionTester {
|
||||
}
|
||||
|
||||
private final DatabaseRuntime runtime;
|
||||
private final DatabaseProps props;
|
||||
private final Supplier<List<DatabaseProvider>> providers;
|
||||
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.props = props;
|
||||
this.providers = providers;
|
||||
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. */
|
||||
public Result running() {
|
||||
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 password the typed password; blank to reuse the running one where the rule allows
|
||||
* @param product {@code postgresql} or {@code mariadb}
|
||||
*/
|
||||
public Result newSettings(DatabaseProps props, String password) {
|
||||
DatabaseConfig typed;
|
||||
try {
|
||||
typed = DatabaseConfig.from(props, Optional.empty());
|
||||
} catch (IllegalArgumentException e) {
|
||||
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();
|
||||
}
|
||||
public Result saved(String product) {
|
||||
List<DatabaseProvider> matching = ProviderChoice.supported(providers.get()).stream()
|
||||
.filter(p -> p.id().equals(product)).toList();
|
||||
if (matching.size() != 1) {
|
||||
return new Result(Category.NO_PROVIDER, ProviderChoice.plugin(String.valueOf(product)));
|
||||
}
|
||||
DatabaseConfig config;
|
||||
try {
|
||||
config = DatabaseConfig.from(props, Optional.of(secret));
|
||||
config = ProviderChoice.saved(props, matching.get(0)).config();
|
||||
} catch (IllegalArgumentException e) {
|
||||
return new Result(Category.INVALID_SETTINGS, e.getMessage());
|
||||
}
|
||||
List<DatabaseProvider> matching = providers.get().stream().filter(p -> config.provider().equals(p.id()))
|
||||
.toList();
|
||||
if (matching.size() != 1) {
|
||||
return new Result(Category.NO_PROVIDER, "database-" + config.provider());
|
||||
} catch (RuntimeException e) {
|
||||
// A provider whose saved settings cannot be read; its message is not trusted to be free of a secret.
|
||||
log.warn("database: the saved settings of {} could not be read ({})", ProviderChoice.plugin(product),
|
||||
e.getClass().getSimpleName());
|
||||
return new Result(Category.OTHER, "");
|
||||
}
|
||||
Engine engine = DatabaseRuntime.engineFor(config.provider());
|
||||
try {
|
||||
@@ -108,22 +105,15 @@ public final class ConnectionTester {
|
||||
return new Result(Category.OK, engine.inspectServer(c));
|
||||
}
|
||||
} 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()
|
||||
: "");
|
||||
} 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, "");
|
||||
}
|
||||
}
|
||||
|
||||
/** 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) {
|
||||
return switch (failure) {
|
||||
case UNREACHABLE -> Category.UNREACHABLE;
|
||||
|
||||
@@ -10,10 +10,12 @@ import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.regex.Pattern;
|
||||
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
|
||||
* 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
|
||||
* are clamped to a working range.
|
||||
*
|
||||
@@ -66,46 +68,45 @@ public record DatabaseConfig(String provider, String namespace, String host, int
|
||||
/**
|
||||
* Checks raw settings.
|
||||
*
|
||||
* @param props the bound settings
|
||||
* @param password the password in clear, or empty
|
||||
* @param props the database plugin's own settings: namespace and limits (its provider choice is resolved by
|
||||
* 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
|
||||
* @throws IllegalArgumentException naming the first setting that is missing or unusable; the message never
|
||||
* holds the password
|
||||
*/
|
||||
public static DatabaseConfig from(DatabaseProps props, Optional<String> password) {
|
||||
String provider = trimToNull(props.getProvider());
|
||||
if (provider == null) {
|
||||
public static DatabaseConfig from(DatabaseProps props, String provider, ProviderSettings server) {
|
||||
String product = trimToNull(provider);
|
||||
if (product == null) {
|
||||
throw new IllegalArgumentException("no provider is chosen");
|
||||
}
|
||||
provider = provider.toLowerCase(Locale.ROOT);
|
||||
if (!PROVIDERS.contains(provider)) {
|
||||
throw new IllegalArgumentException("unknown provider: " + provider);
|
||||
product = product.toLowerCase(Locale.ROOT);
|
||||
if (!PROVIDERS.contains(product)) {
|
||||
throw new IllegalArgumentException("unknown provider: " + product);
|
||||
}
|
||||
String namespace = Names.namespace(Optional.ofNullable(trimToNull(props.getNamespace())).orElse("rw"));
|
||||
String host = checkHost(props.getHost());
|
||||
int port = props.getPort() == null ? 0 : props.getPort();
|
||||
if (port < 0 || port > 65535) {
|
||||
throw new IllegalArgumentException("the port must be between 1 and 65535, or blank for the default");
|
||||
}
|
||||
String database = trimToNull(props.getDatabase());
|
||||
String host = checkHost(server.host());
|
||||
int port = port(server.port());
|
||||
String database = trimToNull(server.database());
|
||||
if (database == null || !DATABASE.matcher(database).matches()) {
|
||||
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)) {
|
||||
throw new IllegalArgumentException("the username must be 1 to " + USERNAME_MAX
|
||||
+ " characters, without control characters");
|
||||
}
|
||||
String secret = password.orElse("");
|
||||
String secret = server.password() == null ? "" : server.password();
|
||||
if (secret.length() > PASSWORD_MAX || hasControl(secret)) {
|
||||
throw new IllegalArgumentException("the password is too long or holds control characters");
|
||||
}
|
||||
Tls tls = tls(props.getTls());
|
||||
String ca = trimToNull(props.getCaCertificate());
|
||||
Tls tls = tls(server.tls());
|
||||
String ca = trimToNull(server.caCertificate());
|
||||
if (ca != null) {
|
||||
ca = checkPem(ca);
|
||||
}
|
||||
String collation = trimToNull(props.getCollation());
|
||||
String collation = trimToNull(server.collation());
|
||||
if (collation != null && !COLLATION.matcher(collation).matches()) {
|
||||
throw new IllegalArgumentException("the collation must be a MariaDB collation name such as "
|
||||
+ "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 timeout = clamp(props.getStatementTimeoutSeconds(), 10, TIMEOUT_MIN_S, TIMEOUT_MAX_S);
|
||||
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);
|
||||
}
|
||||
|
||||
/** 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). */
|
||||
static Tls tls(String value) {
|
||||
String v = trimToNull(value);
|
||||
|
||||
@@ -1,25 +1,54 @@
|
||||
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
|
||||
* ({@code external/plugin-settings/database.yml}). Raw values: {@link DatabaseConfig#from} checks them. The password
|
||||
* is not here: it is read in clear through {@code PluginSettings.appSecret("password")}.
|
||||
* ({@code external/plugin-settings/database.yml}): the provider choice, the namespace and the limits. Raw values:
|
||||
* {@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 {
|
||||
|
||||
private String provider;
|
||||
private String provider = "auto";
|
||||
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 statementTimeoutSeconds = 10;
|
||||
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;
|
||||
|
||||
/** 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() {
|
||||
return provider;
|
||||
}
|
||||
@@ -36,54 +65,6 @@ public class DatabaseProps {
|
||||
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() {
|
||||
return poolMax;
|
||||
}
|
||||
@@ -108,6 +89,62 @@ public class DatabaseProps {
|
||||
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() {
|
||||
return collation;
|
||||
}
|
||||
|
||||
@@ -54,7 +54,7 @@ public final class DatabaseRuntime {
|
||||
public enum Status {
|
||||
/** The settings are missing or unusable; fixed by saving the settings and restarting. */
|
||||
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,
|
||||
/** Trying to reach the server. */
|
||||
CONNECTING,
|
||||
@@ -79,8 +79,7 @@ public final class DatabaseRuntime {
|
||||
static final Duration UNSUPPORTED_RETRY = Duration.ofMinutes(5);
|
||||
private static final int LOCK_CONNECTIONS = 4;
|
||||
|
||||
private final Supplier<DatabaseConfig> configSource;
|
||||
private final Supplier<List<DatabaseProvider>> providers;
|
||||
private final Supplier<ProviderChoice.Chosen> source;
|
||||
private final Path workDir;
|
||||
private final ScheduledExecutorService executor;
|
||||
private final Semaphore lockConnections = new Semaphore(LOCK_CONNECTIONS, true);
|
||||
@@ -104,15 +103,13 @@ public final class DatabaseRuntime {
|
||||
private long backoffMillis = 1000;
|
||||
|
||||
/**
|
||||
* @param configSource builds the checked settings; throws {@link IllegalArgumentException} with a reason
|
||||
* @param providers the provider beans installed
|
||||
* @param workDir the plugin's own folder for the CA file
|
||||
* @param executor the plugin's executor
|
||||
* @param source chooses the provider and checks the settings ({@link ProviderChoice#running}); throws
|
||||
* {@link ProviderChoice.NoProviderException} or {@link IllegalArgumentException} with a reason
|
||||
* @param workDir the plugin's own folder for the CA file
|
||||
* @param executor the plugin's executor
|
||||
*/
|
||||
public DatabaseRuntime(Supplier<DatabaseConfig> configSource, Supplier<List<DatabaseProvider>> providers,
|
||||
Path workDir, ScheduledExecutorService executor) {
|
||||
this.configSource = Objects.requireNonNull(configSource, "configSource");
|
||||
this.providers = Objects.requireNonNull(providers, "providers");
|
||||
public DatabaseRuntime(Supplier<ProviderChoice.Chosen> source, Path workDir, ScheduledExecutorService executor) {
|
||||
this.source = Objects.requireNonNull(source, "source");
|
||||
this.workDir = Objects.requireNonNull(workDir, "workDir");
|
||||
this.executor = Objects.requireNonNull(executor, "executor");
|
||||
}
|
||||
@@ -221,27 +218,25 @@ public final class DatabaseRuntime {
|
||||
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() {
|
||||
DatabaseConfig c;
|
||||
DatabaseProvider provider;
|
||||
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) {
|
||||
status = Status.NOT_CONFIGURED;
|
||||
detail = e.getMessage();
|
||||
log.info("database: not configured: {}", e.getMessage());
|
||||
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());
|
||||
Path ca;
|
||||
try {
|
||||
|
||||
@@ -463,6 +463,11 @@ public final class PostgresEngine implements Engine {
|
||||
return ConnectFailure.TLS;
|
||||
}
|
||||
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.
|
||||
if (state.equals("28P01") || state.equals("28000") || state.equals("08004")) {
|
||||
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;
|
||||
|
||||
import java.util.Optional;
|
||||
import javax.sql.DataSource;
|
||||
|
||||
/**
|
||||
* 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 —
|
||||
* 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
|
||||
*/
|
||||
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>
|
||||
* 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()}
|
||||
* in the database plugin's settings.
|
||||
* driver in {@code lib/}. The provider declares its server's settings (the keys in
|
||||
* {@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>
|
||||
* 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.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.CountDownLatch;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
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.spi.ConnectionSettings;
|
||||
import mx.quest.database.spi.DatabaseProvider;
|
||||
import mx.quest.database.spi.ProviderSettings;
|
||||
import mx.quest.database.spi.Databases;
|
||||
import mx.quest.runway.spi.BackupParticipant;
|
||||
import mx.quest.runway.spi.model.PluginInfo;
|
||||
@@ -66,6 +68,11 @@ class DatabasePluginConfigTest {
|
||||
touched.set(true);
|
||||
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.refresh();
|
||||
@@ -107,10 +114,8 @@ class DatabasePluginConfigTest {
|
||||
String startThread = Thread.currentThread().getName();
|
||||
try (AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext()) {
|
||||
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.port", "1", "runway.plugin.database.database", "runway",
|
||||
"runway.plugin.database.username", "runway", "runway.plugin.database.tls", "disable")));
|
||||
ctx.registerBean(PluginSettings.class, () -> new FakePluginSettings().appSecret("password", "x"));
|
||||
"runway.plugin.database.provider", "postgresql")));
|
||||
ctx.registerBean(PluginSettings.class, FakePluginSettings::new);
|
||||
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(FakeSiteServices.class, FakeSiteServices::new);
|
||||
@@ -135,6 +140,12 @@ class DatabasePluginConfigTest {
|
||||
}
|
||||
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);
|
||||
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
|
||||
void theCompiledClassesLinkNoHostInternals() throws IOException {
|
||||
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.assertThatThrownBy;
|
||||
|
||||
import java.util.Optional;
|
||||
import mx.quest.database.spi.ConnectionSettings.Tls;
|
||||
import mx.quest.database.spi.ProviderSettings;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
class DatabaseConfigTest {
|
||||
|
||||
static DatabaseProps props() {
|
||||
DatabaseProps p = new DatabaseProps();
|
||||
p.setProvider("postgresql");
|
||||
p.setHost("db.example.com");
|
||||
p.setDatabase("runway");
|
||||
p.setUsername("runway");
|
||||
return p;
|
||||
static ProviderSettings server() {
|
||||
return server("db.example.com", null, null);
|
||||
}
|
||||
|
||||
static ProviderSettings server(String host, String port, String tls) {
|
||||
return new ProviderSettings(host, port, "runway", "runway", "s3cret", tls, null, null);
|
||||
}
|
||||
|
||||
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
|
||||
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.namespace()).isEqualTo("rw");
|
||||
assertThat(c.port()).isZero();
|
||||
assertThat(c.poolMax()).isEqualTo(10);
|
||||
assertThat(c.password()).isEqualTo("s3cret");
|
||||
assertThat(c.toString()).doesNotContain("s3cret");
|
||||
assertThat(server().toString()).doesNotContain("s3cret");
|
||||
}
|
||||
|
||||
@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",
|
||||
"h;x", "-h", "h-.com", "1.2.3.256", "999.1.1.1", "[::1]x", "fe80::1%eth0", "a..b", "h.",
|
||||
"::1::2"}) {
|
||||
DatabaseProps p = props();
|
||||
p.setHost(bad);
|
||||
assertThatThrownBy(() -> DatabaseConfig.from(p, Optional.empty())).as(bad)
|
||||
.isInstanceOf(IllegalArgumentException.class);
|
||||
assertThatThrownBy(() -> DatabaseConfig.from(new DatabaseProps(), "postgresql", server(bad, null, null)))
|
||||
.as(bad).isInstanceOf(IllegalArgumentException.class);
|
||||
}
|
||||
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"}) {
|
||||
DatabaseProps p = props();
|
||||
p.setHost(good);
|
||||
assertThat(DatabaseConfig.from(p, Optional.empty()).host()).as(good).doesNotContain("[");
|
||||
assertThat(DatabaseConfig.from(new DatabaseProps(), "postgresql", server(good, null, null)).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
|
||||
void theOtherFieldsAreCheckedToo() {
|
||||
DatabaseProps p = props();
|
||||
p.setDatabase("run way");
|
||||
assertThatThrownBy(() -> DatabaseConfig.from(p, Optional.empty())).hasMessageContaining("database name");
|
||||
DatabaseProps q = props();
|
||||
q.setTls("prefer");
|
||||
assertThatThrownBy(() -> DatabaseConfig.from(q, Optional.empty())).hasMessageContaining("tls");
|
||||
DatabaseProps r = props();
|
||||
r.setProvider("mysql");
|
||||
assertThatThrownBy(() -> DatabaseConfig.from(r, Optional.empty())).hasMessageContaining("unknown provider");
|
||||
DatabaseProps s = props();
|
||||
s.setCaCertificate("not a certificate");
|
||||
assertThatThrownBy(() -> DatabaseConfig.from(s, Optional.empty())).hasMessageContaining("PEM");
|
||||
DatabaseProps t = props();
|
||||
t.setCollation("utf8mb4; DROP");
|
||||
assertThatThrownBy(() -> DatabaseConfig.from(t, Optional.empty())).hasMessageContaining("collation");
|
||||
DatabaseProps u = props();
|
||||
DatabaseProps p = new DatabaseProps();
|
||||
assertThatThrownBy(() -> DatabaseConfig.from(p, "postgresql", with(server(), "run way", null, null)))
|
||||
.hasMessageContaining("database name");
|
||||
assertThatThrownBy(() -> DatabaseConfig.from(p, "postgresql", server("h", null, "prefer")))
|
||||
.hasMessageContaining("tls");
|
||||
assertThatThrownBy(() -> DatabaseConfig.from(p, "mysql", server())).hasMessageContaining("unknown provider");
|
||||
assertThatThrownBy(() -> DatabaseConfig.from(p, " ", server())).hasMessageContaining("no provider");
|
||||
assertThatThrownBy(() -> DatabaseConfig.from(p, "postgresql", with(server(), "runway", "not a certificate",
|
||||
null))).hasMessageContaining("PEM");
|
||||
assertThatThrownBy(() -> DatabaseConfig.from(p, "mariadb", with(server(), "runway", null, "utf8mb4; DROP")))
|
||||
.hasMessageContaining("collation");
|
||||
assertThatThrownBy(() -> DatabaseConfig.from(p, "postgresql", new ProviderSettings("h", null, "runway",
|
||||
null, null, null, null, null))).hasMessageContaining("username");
|
||||
DatabaseProps u = new DatabaseProps();
|
||||
u.setPoolMax(100000);
|
||||
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.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.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.function.Supplier;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.CopyOnWriteArrayList;
|
||||
import java.util.concurrent.Executors;
|
||||
@@ -26,6 +27,7 @@ import javax.sql.DataSource;
|
||||
import mx.quest.database.spi.ConnectionSettings;
|
||||
import mx.quest.database.spi.DatabaseConsumer;
|
||||
import mx.quest.database.spi.DatabaseProvider;
|
||||
import mx.quest.database.spi.ProviderSettings;
|
||||
import mx.quest.database.spi.PluginDatabase;
|
||||
import mx.quest.database.spi.Scope;
|
||||
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. */
|
||||
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() {
|
||||
@Override
|
||||
public Optional<ProviderSettings> runningSettings() {
|
||||
return Optional.ofNullable(running.get());
|
||||
}
|
||||
|
||||
@Override
|
||||
public Optional<ProviderSettings> savedSettings() {
|
||||
return Optional.ofNullable(saved.get());
|
||||
}
|
||||
|
||||
@Override
|
||||
public String id() {
|
||||
return engine;
|
||||
@@ -179,7 +197,13 @@ final class Harness implements AutoCloseable {
|
||||
final DatabaseCore core;
|
||||
final DatabasesImpl databases;
|
||||
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;
|
||||
/** 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 {
|
||||
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");
|
||||
props.setProvider(engine);
|
||||
props.setNamespace(namespace);
|
||||
props.setHost(endpoint.host());
|
||||
props.setPort(endpoint.port());
|
||||
props.setDatabase(DATABASE);
|
||||
props.setUsername(USER);
|
||||
props.setTls("disable");
|
||||
host = endpoint.host();
|
||||
port = String.valueOf(endpoint.port());
|
||||
username = USER;
|
||||
password = endpoint.password();
|
||||
providers.add(provider(engine));
|
||||
runtime = new DatabaseRuntime(() -> DatabaseConfig.from(props, Optional.ofNullable(password)),
|
||||
() -> List.copyOf(providers), work.resolve("run-" + System.nanoTime()), executor);
|
||||
providers.add(provider(engine, this::running, () -> saved != null ? saved : running()));
|
||||
runtime = new DatabaseRuntime(() -> ProviderChoice.running(props, List.copyOf(providers)),
|
||||
work.resolve("run-" + System.nanoTime()), executor);
|
||||
schemas = new SiteSchemas(runtime, files, sites);
|
||||
migrator = new Migrator(runtime);
|
||||
core = new DatabaseCore(runtime, schemas, migrator, sites, sites);
|
||||
@@ -219,6 +241,11 @@ final class Harness implements AutoCloseable {
|
||||
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 {
|
||||
runtime.start();
|
||||
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. */
|
||||
Connection raw() throws SQLException {
|
||||
return provider(engine).dataSource(DatabaseRuntime.settings(DatabaseConfig.from(props,
|
||||
Optional.of(endpoint.password())), null, Duration.ofSeconds(30))).getConnection();
|
||||
ProviderSettings test = new ProviderSettings(endpoint.host(), String.valueOf(endpoint.port()), DATABASE, USER,
|
||||
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 {
|
||||
|
||||
@@ -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.DatabaseUnavailableException;
|
||||
import mx.quest.database.spi.PluginDatabase;
|
||||
import mx.quest.database.spi.ProviderSettings;
|
||||
import mx.quest.database.spi.Scope;
|
||||
import mx.quest.database.spi.ScopeNotReadyException;
|
||||
import mx.quest.runway.spi.model.SiteLifecycleEvent;
|
||||
@@ -187,28 +188,27 @@ class RealServerTest {
|
||||
}
|
||||
assertThat(h.runtime.available()).isFalse();
|
||||
assertThat(h.runtime.status()).isEqualTo(DatabaseRuntime.Status.CONNECTING);
|
||||
DatabaseProps typed = new DatabaseProps();
|
||||
typed.setProvider(engine);
|
||||
typed.setHost(endpoint.host());
|
||||
typed.setPort(endpoint.port());
|
||||
typed.setDatabase(Harness.DATABASE);
|
||||
typed.setUsername(Harness.USER);
|
||||
typed.setTls("disable");
|
||||
ConnectionTester tester = new ConnectionTester(h.runtime, () -> h.providers, work);
|
||||
assertThat(tester.newSettings(typed, wrong).category()).isEqualTo(ConnectionTester.Category.AUTHENTICATION);
|
||||
assertThat(tester.newSettings(typed, endpoint.password()).category())
|
||||
.isEqualTo(ConnectionTester.Category.OK);
|
||||
typed.setDatabase("no_such_db_" + SEQ.incrementAndGet());
|
||||
assertThat(tester.newSettings(typed, endpoint.password()).category())
|
||||
.isEqualTo(ConnectionTester.Category.DATABASE_MISSING);
|
||||
typed.setDatabase(Harness.DATABASE);
|
||||
typed.setPort(1);
|
||||
assertThat(tester.newSettings(typed, endpoint.password()).category())
|
||||
.isEqualTo(ConnectionTester.Category.UNREACHABLE);
|
||||
// A blank password is not sent to a different target.
|
||||
typed.setPort(endpoint.port());
|
||||
typed.setUsername("someone_else");
|
||||
assertThat(tester.newSettings(typed, "").category()).isEqualTo(ConnectionTester.Category.AUTHENTICATION);
|
||||
// The saved-settings test reads what the provider's page holds now, never the running settings.
|
||||
ConnectionTester tester = new ConnectionTester(h.runtime, h.props, () -> h.providers, work);
|
||||
assertThat(tester.testable()).containsExactly(engine);
|
||||
h.saved = saved(endpoint, Harness.DATABASE, endpoint.port(), Harness.USER, wrong);
|
||||
assertThat(tester.saved(engine).category()).isEqualTo(ConnectionTester.Category.AUTHENTICATION);
|
||||
h.saved = saved(endpoint, Harness.DATABASE, endpoint.port(), Harness.USER, endpoint.password());
|
||||
ConnectionTester.Result ok = tester.saved(engine);
|
||||
assertThat(ok.category()).isEqualTo(ConnectionTester.Category.OK);
|
||||
assertThat(ok.detail()).containsIgnoringCase(engine.equals("postgresql") ? "PostgreSQL" : "MariaDB");
|
||||
h.saved = saved(endpoint, "no_such_db_" + SEQ.incrementAndGet(), endpoint.port(), Harness.USER,
|
||||
endpoint.password());
|
||||
assertThat(tester.saved(engine).category()).isEqualTo(ConnectionTester.Category.DATABASE_MISSING);
|
||||
h.saved = saved(endpoint, Harness.DATABASE, 1, Harness.USER, endpoint.password());
|
||||
assertThat(tester.saved(engine).category()).isEqualTo(ConnectionTester.Category.UNREACHABLE);
|
||||
h.saved = saved(endpoint, Harness.DATABASE, 99999, Harness.USER, endpoint.password());
|
||||
assertThat(tester.saved(engine)).isEqualTo(new ConnectionTester.Result(
|
||||
ConnectionTester.Category.INVALID_SETTINGS, "database-" + engine + " settings: the port must be "
|
||||
+ "between 1 and 65535, or blank for the default"));
|
||||
String other = engine.equals("postgresql") ? "mariadb" : "postgresql";
|
||||
assertThat(tester.saved(other).category()).isEqualTo(ConnectionTester.Category.NO_PROVIDER);
|
||||
assertThat(h.runtime.status()).as("a test changes nothing").isEqualTo(DatabaseRuntime.Status.CONNECTING);
|
||||
} finally {
|
||||
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
|
||||
void withoutSettingsOrProviderNothingConnects() throws Exception {
|
||||
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)");
|
||||
Harness h = new Harness("postgresql", namespace("postgresql"), endpoint, work.resolve("nc"));
|
||||
open.add(h);
|
||||
h.props.setHost(null);
|
||||
h.host = null;
|
||||
h.username = null;
|
||||
h.start();
|
||||
assertThat(h.runtime.status()).isEqualTo(DatabaseRuntime.Status.NOT_CONFIGURED);
|
||||
Harness p = new Harness("postgresql", namespace("postgresql"), endpoint, work.resolve("np"));
|
||||
|
||||
@@ -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>
|
||||
@@ -71,66 +71,16 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Connection tests -->
|
||||
<!-- Where the settings and the connection tests are (since 2.0.0) -->
|
||||
<div class="col-lg-6">
|
||||
<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">
|
||||
<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 running
|
||||
connection</button>
|
||||
</form>
|
||||
<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>
|
||||
<p class="text-secondary" id="db-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.</p>
|
||||
<a class="btn btn-outline-primary" href="/__app/plugins/database/settings#db-tests"
|
||||
id="db-settings-link">Settings and connection tests</a>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -43,20 +43,10 @@
|
||||
<attr sel="#db-last-error-text" th:text="${db.runtime().lastError()}"/>
|
||||
<attr sel="#db-problem" th:if="${db.problem() != null}" th:text="${db.problem()}"/>
|
||||
|
||||
<!-- Connection tests -->
|
||||
<attr sel="#db-test-title" th:text="#{database.console.tests}"/>
|
||||
<attr sel="#db-test-running" th:text="#{database.console.testRunning}"/>
|
||||
<attr sel="#db-test-new-help" th:text="#{database.console.testNew.help}"/>
|
||||
<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}"/>
|
||||
<!-- Where the settings and the connection tests are -->
|
||||
<attr sel="#db-settings-title" th:text="#{database.console.settings}"/>
|
||||
<attr sel="#db-settings-text" th:text="#{database.console.settings.text}"/>
|
||||
<attr sel="#db-settings-link" th:text="#{database.console.settings.link}"/>
|
||||
|
||||
<!-- Migration problems -->
|
||||
<attr sel="#db-issues-title" th:text="#{database.console.issues}"/>
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
> **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
|
||||
> 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
|
||||
> 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.
|
||||
@@ -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/
|
||||
# PluginLifecycle; ">=0.5.0" PluginSiteFiles, Sites, RequestContext, AccessCheck, Messages, SitePages, anonymous
|
||||
# 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
|
||||
# blocked as "built for the pre-1.0 plugin contract" (a code-less library plugin is exempt).
|
||||
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
|
||||
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:` 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-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 |
|
||||
|---|---|
|
||||
| `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 |
|
||||
| `FakeSiteServices` | `Sites`, `RequestContext` (`.current(id)`), `AccessCheck` (`.grant(key)`), `Messages` (`.message(…)`), `SitePages` (`.page(…)`, `.nextInstall(outcome)`, `.installs()`) |
|
||||
| `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 "$HERE/target/runway-demo-database" "$EXT/plugins/runway-demo-database"
|
||||
boot() { ( cd "$SCRATCH" && exec "$JAVA" -jar "$JAR" --server.port="$PORT" --runway.storage.external="$EXT" ) >"$1" 2>&1 & PID=$!; }
|
||||
settings() { # port
|
||||
settings() { # port. Since database 2.0.0 the server is the provider plugin's setting; the namespace stays.
|
||||
umask 077
|
||||
printf 'runway:\n plugin:\n database:\n provider: %s\n namespace: %s\n host: "%s"\n port: %s\n database: "%s"\n username: "%s"\n password: "%s"\n tls: disable\n' \
|
||||
"$PROVIDER" "$NS" "$DB_HOST" "$1" "$DB_NAME" "$DB_USER" "$DB_PASSWORD" > "$EXT/plugin-settings/database.yml"
|
||||
printf 'runway:\n plugin:\n database:\n namespace: %s\n' "$NS" > "$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
|
||||
}
|
||||
|
||||
|
||||
@@ -13,7 +13,7 @@
|
||||
|
||||
<groupId>mx.quest</groupId>
|
||||
<artifactId>runway</artifactId>
|
||||
<version>1.1.2</version>
|
||||
<version>1.2.0</version>
|
||||
<packaging>pom</packaging>
|
||||
|
||||
<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
|
||||
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. -->
|
||||
<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>
|
||||
<!-- 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'
|
||||
|
||||
+1
-1
@@ -7,7 +7,7 @@
|
||||
<parent>
|
||||
<groupId>mx.quest</groupId>
|
||||
<artifactId>runway</artifactId>
|
||||
<version>1.1.2</version>
|
||||
<version>1.2.0</version>
|
||||
</parent>
|
||||
|
||||
<artifactId>runway-app</artifactId>
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package mx.quest.runway.backup;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.UncheckedIOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
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
|
||||
* 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
|
||||
* 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) {
|
||||
String siteId = workDir.getFileName().toString();
|
||||
Path old = workDir.resolve("old");
|
||||
Path siteDir = layout.siteDir(siteId);
|
||||
if (Files.exists(old) && !Files.exists(siteDir)) {
|
||||
try {
|
||||
Files.move(old, siteDir);
|
||||
try {
|
||||
if (BackupService.settle(siteDir, workDir)) {
|
||||
log.warn("recovered site '{}' from an interrupted restore", siteId);
|
||||
} catch (IOException e) {
|
||||
// Recovery failed — DO NOT delete this work dir; `old` is the only copy of the site.
|
||||
log.error("could not recover site '{}' automatically — its content is preserved at {}",
|
||||
siteId, old, e);
|
||||
continue;
|
||||
}
|
||||
} catch (IOException | UncheckedIOException e) {
|
||||
// Recovery failed — DO NOT delete this work dir: it may hold the only copy of the site, or its logs.
|
||||
log.error("could not recover site '{}' automatically — its content is preserved at {}",
|
||||
siteId, workDir, e);
|
||||
continue;
|
||||
}
|
||||
BackupService.deleteRecursively(workDir); // recovered or not needed — the leftovers are safe to drop
|
||||
BackupService.deleteRecursively(workDir); // settled — the leftovers (a staging copy) are safe to drop
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -9,6 +9,7 @@ import java.io.InputStream;
|
||||
import java.io.OutputStream;
|
||||
import java.io.UncheckedIOException;
|
||||
import java.nio.file.AtomicMoveNotSupportedException;
|
||||
import java.nio.file.FileAlreadyExistsException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.LinkOption;
|
||||
import java.nio.file.Path;
|
||||
@@ -296,7 +297,7 @@ public class BackupService {
|
||||
|
||||
private void doRestore(String siteId, InputStream in, boolean keepRouting) throws IOException {
|
||||
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) {
|
||||
keepRouting(siteId, live);
|
||||
} else {
|
||||
@@ -307,7 +308,9 @@ public class BackupService {
|
||||
sites.evict(siteId);
|
||||
events.publishEvent(new SiteChangedEvent(siteId, SiteChangedEvent.Kind.RESTORED));
|
||||
importParticipants(siteId, staged.pluginData());
|
||||
deleteRecursively(staged.work());
|
||||
if (staged.settled()) {
|
||||
deleteRecursively(staged.work());
|
||||
} // else: the site's previous logs wait in it for the next restore or start (swapIntoPlace)
|
||||
log.info("restored site '{}' from backup", siteId);
|
||||
}
|
||||
|
||||
@@ -384,7 +387,7 @@ public class BackupService {
|
||||
if (sites.exists(newId)) {
|
||||
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 {
|
||||
// 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"));
|
||||
@@ -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. */
|
||||
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.
|
||||
* 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 work = workDir(siteId);
|
||||
Path staging = work.resolve("staging");
|
||||
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);
|
||||
Files.createDirectories(staging);
|
||||
// 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)");
|
||||
}
|
||||
warnParticipantDrift(siteId, manifest, pluginData);
|
||||
swapIntoPlace(siteDir, staging, old);
|
||||
return new Staged(manifest, pluginData, work);
|
||||
boolean settled = swapIntoPlace(siteDir, staging, old, keepTransient);
|
||||
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. */
|
||||
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) {
|
||||
@@ -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 {
|
||||
if (Files.exists(siteDir)) {
|
||||
move(siteDir, old);
|
||||
}
|
||||
move(staging, siteDir);
|
||||
try {
|
||||
move(staging, siteDir);
|
||||
} catch (IOException recreated) {
|
||||
if (!setAsideIfNotASite(siteDir, late)) {
|
||||
throw recreated;
|
||||
}
|
||||
move(staging, siteDir);
|
||||
}
|
||||
} catch (IOException swapFailed) {
|
||||
if (Files.exists(old) && !Files.exists(siteDir)) {
|
||||
if (Files.exists(old)) {
|
||||
try {
|
||||
move(old, siteDir); // roll back
|
||||
} catch (IOException rollbackFailed) {
|
||||
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
|
||||
// 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);
|
||||
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);
|
||||
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. */
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
package mx.quest.runway.console;
|
||||
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
@@ -98,8 +99,8 @@ public class AppBackupsController {
|
||||
|
||||
/** Stream a fresh backup of any site. */
|
||||
@GetMapping("/__app/backups/{siteId}/download")
|
||||
public void download(@PathVariable String siteId, Authentication authentication, HttpServletResponse response)
|
||||
throws IOException {
|
||||
public void download(@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");
|
||||
@@ -107,13 +108,17 @@ public class AppBackupsController {
|
||||
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,
|
||||
HttpServletResponse response) throws IOException {
|
||||
HttpServletRequest request, HttpServletResponse response) throws IOException {
|
||||
platformAuthority.require(authentication);
|
||||
if (!sites.exists(siteId)) {
|
||||
throw new ResponseStatusException(HttpStatus.NOT_FOUND, "no such site");
|
||||
@@ -121,7 +126,11 @@ public class AppBackupsController {
|
||||
response.setContentType("application/zip");
|
||||
response.setHeader(HttpHeaders.CONTENT_DISPOSITION,
|
||||
"attachment; filename=\"" + siteId + "-transfer-" + LocalDate.now() + ".zip\"");
|
||||
if (TenantBackupsController.isHead(request)) {
|
||||
return;
|
||||
}
|
||||
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. */
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
package mx.quest.runway.console;
|
||||
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
@@ -7,6 +8,7 @@ import java.nio.file.Path;
|
||||
import java.time.LocalDate;
|
||||
import mx.quest.runway.backup.BackupService;
|
||||
import mx.quest.runway.backup.UnsupportedBackupFormatException;
|
||||
import mx.quest.runway.log.SiteLogService;
|
||||
import mx.quest.runway.site.Site;
|
||||
import mx.quest.runway.site.SiteResolver;
|
||||
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
|
||||
* {@code /__app/backups}) to download or restore. Bound-tenancy only — a tenant can only ever back up or restore its
|
||||
* 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
|
||||
public class TenantBackupsController {
|
||||
@@ -62,11 +72,13 @@ public class TenantBackupsController {
|
||||
private final MessageSource messages;
|
||||
private final mx.quest.runway.backup.BackupProperties policy;
|
||||
private final mx.quest.runway.platform.PlatformSettingsStore platform;
|
||||
private final SiteLogService siteLog;
|
||||
|
||||
public TenantBackupsController(SiteResolver siteResolver, BackupService backups, TenantAuthority tenantAuthority,
|
||||
@Qualifier("operatorAwareMessageSource") MessageSource messages,
|
||||
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.policy = policy;
|
||||
this.siteResolver = siteResolver;
|
||||
@@ -120,10 +132,11 @@ public class TenantBackupsController {
|
||||
/** Save a new backup on the server. */
|
||||
@PostMapping("/__admin/backups/create")
|
||||
@PreAuthorize("@authz.may('MANAGE_BACKUPS')")
|
||||
public String create(RedirectAttributes redirect) {
|
||||
public String create(Authentication authentication, RedirectAttributes redirect) {
|
||||
Site site = boundTenancy();
|
||||
try {
|
||||
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);
|
||||
} catch (IOException e) {
|
||||
log.warn("backup create failed for {}", site.id(), e);
|
||||
@@ -138,13 +151,18 @@ public class TenantBackupsController {
|
||||
*/
|
||||
@GetMapping("/__admin/backups/download")
|
||||
@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();
|
||||
tenantAuthority.require(authentication, site.id());
|
||||
response.setContentType("application/zip");
|
||||
response.setHeader(HttpHeaders.CONTENT_DISPOSITION,
|
||||
"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());
|
||||
siteLog.audit(site.id(), actor(authentication), "backup.downloaded", "full");
|
||||
}
|
||||
|
||||
|
||||
@@ -158,12 +176,17 @@ public class TenantBackupsController {
|
||||
*/
|
||||
@GetMapping("/__admin/backups/download-transfer")
|
||||
@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();
|
||||
response.setContentType("application/zip");
|
||||
response.setHeader(HttpHeaders.CONTENT_DISPOSITION,
|
||||
"attachment; filename=\"" + site.id() + "-transfer-" + LocalDate.now() + ".zip\"");
|
||||
if (isHead(request)) {
|
||||
return;
|
||||
}
|
||||
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")
|
||||
@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();
|
||||
tenantAuthority.require(authentication, site.id());
|
||||
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
|
||||
// attacker-controlled input (CRLF / quotes) even though the store already rejects it as an unsafe id.
|
||||
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()
|
||||
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + filename + "\"")
|
||||
.contentType(MediaType.parseMediaType("application/zip"))
|
||||
@@ -190,9 +220,11 @@ public class TenantBackupsController {
|
||||
/** Delete a stored backup. */
|
||||
@PostMapping("/__admin/backups/{name}/delete")
|
||||
@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();
|
||||
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."));
|
||||
return "redirect:/__admin/backups";
|
||||
}
|
||||
@@ -204,6 +236,7 @@ public class TenantBackupsController {
|
||||
tenantAuthority.require(authentication, site.id());
|
||||
try {
|
||||
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(AppBackupsController.REVIEW_HOSTS, Boolean.TRUE);
|
||||
} catch (UnsupportedBackupFormatException e) {
|
||||
@@ -227,6 +260,7 @@ public class TenantBackupsController {
|
||||
}
|
||||
try (InputStream in = file.getInputStream()) {
|
||||
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(AppBackupsController.REVIEW_HOSTS, Boolean.TRUE);
|
||||
} catch (UnsupportedBackupFormatException e) {
|
||||
@@ -238,6 +272,20 @@ public class TenantBackupsController {
|
||||
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) {
|
||||
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.PluginSiteFiles;
|
||||
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.ObjectProvider;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
@@ -49,6 +51,8 @@ import org.springframework.core.env.Environment;
|
||||
@Configuration(proxyBeanMethods = false)
|
||||
public class PluginScopedServices {
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(PluginScopedServices.class);
|
||||
|
||||
private final PluginOwnership ownership;
|
||||
private final SitePluginConfigService siteConfig;
|
||||
private final SecretCipher cipher;
|
||||
@@ -99,7 +103,26 @@ public class PluginScopedServices {
|
||||
"kernel code reads per-site plugin settings through SitePluginConfigService");
|
||||
return settings.computeIfAbsent(plugin.id(), id -> new PluginSettingsImpl(id,
|
||||
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>/}. */
|
||||
|
||||
@@ -174,8 +174,20 @@ public class PluginSettingsService {
|
||||
// ---- 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). */
|
||||
@SuppressWarnings("unchecked")
|
||||
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
|
||||
if (!Files.isRegularFile(file)) {
|
||||
return Map.of();
|
||||
|
||||
@@ -41,6 +41,7 @@ public final class PluginSettingsImpl implements PluginSettings {
|
||||
private final Map<String, PluginSettingDef> schema;
|
||||
private final Map<String, PluginSettingDef> appSchema;
|
||||
private final Function<String, String> appValues;
|
||||
private final Function<String, String> savedAppValues;
|
||||
private final SitePluginConfigService config;
|
||||
private final SecretCipher cipher;
|
||||
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,
|
||||
Function<String, String> appValues, SitePluginConfigService config,
|
||||
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.schema = byKey(siteSettings);
|
||||
this.appSchema = byKey(appSettings);
|
||||
@@ -166,6 +185,29 @@ public final class PluginSettingsImpl implements PluginSettings {
|
||||
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. */
|
||||
private Optional<String> reveal(String value, String scope, String warnKey, String key) {
|
||||
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.backup.saved=Backup saved
|
||||
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.imported=Site template imported
|
||||
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.password-reset=User password reset
|
||||
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.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.backup.saved=Copia de seguridad guardada
|
||||
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.imported=Plantilla de sitio importada
|
||||
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.password-reset=Contraseña de usuario restablecida
|
||||
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.site-config.changed=Ajustes del sitio modificados
|
||||
|
||||
|
||||
@@ -44,7 +44,7 @@
|
||||
<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="">
|
||||
<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">
|
||||
<label class="form-check">
|
||||
<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">
|
||||
<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-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>
|
||||
</form>
|
||||
</div>
|
||||
|
||||
@@ -3,13 +3,15 @@
|
||||
<head><meta charset="utf-8"><title>setting row</title></head>
|
||||
<body>
|
||||
<!-- 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">
|
||||
<label class="form-label sr-label" for="sr-input">key</label>
|
||||
|
||||
<input class="form-control sr-text" type="text" name="key" value="">
|
||||
<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">
|
||||
<select class="form-select sr-select" name="key">
|
||||
<option class="sr-opt" value="">value</option>
|
||||
|
||||
@@ -71,6 +71,67 @@ class BackupRestoreRecoveryTest {
|
||||
"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
|
||||
void noWorkDirIsANoOp() {
|
||||
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.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.junit.jupiter.api.Assumptions.assumeFalse;
|
||||
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.ByteArrayOutputStream;
|
||||
@@ -492,6 +493,113 @@ class BackupServiceTest {
|
||||
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 ------------------------------------
|
||||
|
||||
/**
|
||||
|
||||
@@ -103,7 +103,9 @@ class AuditViewTest {
|
||||
"permissions.role-inherit-removed", "page.saved", "page.deleted", "page.published",
|
||||
"page.unpublished", "user.created", "user.password-reset", "user.deleted",
|
||||
"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")) {
|
||||
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.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.SecurityMockMvcRequestPostProcessors.csrf;
|
||||
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.head;
|
||||
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.result.MockMvcResultMatchers.content;
|
||||
@@ -23,6 +30,7 @@ import java.util.Set;
|
||||
import mx.quest.runway.authz.GrantFile;
|
||||
import mx.quest.runway.authz.GrantStore;
|
||||
import mx.quest.runway.backup.BackupService;
|
||||
import mx.quest.runway.log.SiteLogService;
|
||||
import mx.quest.runway.security.PasswordEncoders;
|
||||
import mx.quest.runway.security.PasswordStrength;
|
||||
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.test.context.DynamicPropertyRegistry;
|
||||
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.MvcResult;
|
||||
import org.springframework.test.web.servlet.request.RequestPostProcessor;
|
||||
@@ -104,6 +113,8 @@ class TenantBackupsScreenTest {
|
||||
private SiteResolver siteResolver;
|
||||
@Autowired
|
||||
private BackupService backups;
|
||||
@MockitoSpyBean
|
||||
private SiteLogService siteLog;
|
||||
private MockMvc mvc;
|
||||
|
||||
@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. */
|
||||
@Test
|
||||
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");
|
||||
}
|
||||
|
||||
@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
|
||||
void anInjectionPointInAPluginsOwnJarBindsToThatPlugin() throws Exception {
|
||||
assumeTrue(PluginFixture.compilerAvailable());
|
||||
|
||||
@@ -273,4 +273,90 @@ class PluginSettingsImplTest {
|
||||
assertEquals(Optional.empty(), bare.appSecret("password"),
|
||||
"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
@@ -7,7 +7,7 @@
|
||||
<parent>
|
||||
<groupId>mx.quest</groupId>
|
||||
<artifactId>runway</artifactId>
|
||||
<version>1.1.2</version>
|
||||
<version>1.2.0</version>
|
||||
</parent>
|
||||
|
||||
<artifactId>runway-dist</artifactId>
|
||||
|
||||
@@ -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 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.
|
||||
version: 1.1.2
|
||||
version: 1.2.0
|
||||
essential: true
|
||||
# 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
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
<parent>
|
||||
<groupId>mx.quest</groupId>
|
||||
<artifactId>runway</artifactId>
|
||||
<version>1.1.2</version>
|
||||
<version>1.2.0</version>
|
||||
</parent>
|
||||
|
||||
<artifactId>runway-plugin-protection</artifactId>
|
||||
|
||||
+1
-1
@@ -35,7 +35,7 @@ class ProtectionDescriptorK4Test {
|
||||
PluginDescriptor descriptor = shipped();
|
||||
assertEquals("protection", descriptor.id());
|
||||
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(RunwaySpi.VERSION).major(), descriptor.spiFloor().major(),
|
||||
"the floor names the kernel's own SPI major line");
|
||||
|
||||
@@ -60,7 +60,7 @@
|
||||
</div>
|
||||
<div class="mb-3">
|
||||
<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
|
||||
keep the current secret.</small>
|
||||
</div>
|
||||
|
||||
@@ -57,7 +57,7 @@
|
||||
</div>
|
||||
<div class="mb-3">
|
||||
<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 keep the current secret.</small>
|
||||
</div>
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
<parent>
|
||||
<groupId>mx.quest</groupId>
|
||||
<artifactId>runway</artifactId>
|
||||
<version>1.1.2</version>
|
||||
<version>1.2.0</version>
|
||||
</parent>
|
||||
|
||||
<artifactId>runway-spi-testkit</artifactId>
|
||||
|
||||
+18
-1
@@ -18,7 +18,8 @@ import mx.quest.runway.spi.service.PluginSettings;
|
||||
* .defaults(Map.of("enabled", true, "limit", 20))
|
||||
* .site("acme", Map.of("limit", 50))
|
||||
* .secret("acme", "smtpPassword", "s3cret")
|
||||
* .appSecret("password", "app-s3cret");
|
||||
* .appSecret("password", "app-s3cret")
|
||||
* .savedApp("host", "db.example.com");
|
||||
* MyWidget widget = new MyWidget(settings);
|
||||
* }</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, String> secrets = 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). */
|
||||
public FakePluginSettings defaults(Map<String, ?> declaredDefaults) {
|
||||
@@ -59,6 +61,15 @@ public final class FakePluginSettings implements PluginSettings {
|
||||
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
|
||||
public SettingsView site(String siteId) {
|
||||
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);
|
||||
}
|
||||
|
||||
@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) {
|
||||
if (siteId == null || siteId.equals(".") || siteId.equals("..") || !SAFE_ID.matcher(siteId).matches()) {
|
||||
throw new IllegalArgumentException("unsafe site id: " + siteId);
|
||||
|
||||
+10
@@ -56,4 +56,14 @@ class FakePluginSettingsTest {
|
||||
assertEquals(Optional.empty(), settings.appSecret("other"));
|
||||
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
@@ -7,7 +7,7 @@
|
||||
<parent>
|
||||
<groupId>mx.quest</groupId>
|
||||
<artifactId>runway</artifactId>
|
||||
<version>1.1.2</version>
|
||||
<version>1.2.0</version>
|
||||
</parent>
|
||||
|
||||
<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
|
||||
* 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>
|
||||
* <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>
|
||||
*
|
||||
* <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
|
||||
* 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
|
||||
|
||||
@@ -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
|
||||
* {@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
|
||||
* {@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
|
||||
*/
|
||||
@@ -76,4 +78,25 @@ public interface PluginSettings {
|
||||
default Optional<String> appSecret(String key) {
|
||||
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
|
||||
void theSpiIsAtOneZero() {
|
||||
assertEquals("1.1.0", RunwaySpi.VERSION);
|
||||
assertEquals("1.2.0", RunwaySpi.VERSION);
|
||||
}
|
||||
|
||||
// --- LocalizedUrl ----------------------------------------------------------------------------------------
|
||||
|
||||
Reference in new issue
Block a user