From 9144c206be736d1a95b22e0ecbad1f25d7617d88 Mon Sep 17 00:00:00 2001 From: Runway Date: Fri, 30 Oct 2026 11:24:46 -0600 Subject: [PATCH] Runway 1.2.0 --- CHANGELOG.md | 84 +++++++ docs/ADMINISTRATION.md | 144 ++++++++++-- docs/PLUGIN-DEVELOPMENT.md | 17 +- docs/SITE-MANAGER-GUIDE.md | 38 +++- docs/SPI-STABILITY.md | 12 +- plugins/database-mariadb/CHANGELOG.md | 16 ++ plugins/database-mariadb/README.md | 12 +- .../docs/DATABASE-MARIADB-PLUGIN.md | 12 + .../database-mariadb/i18n/messages.properties | 17 ++ .../i18n/messages_es.properties | 17 ++ plugins/database-mariadb/plugin.yml | 38 +++- plugins/database-mariadb/pom.xml | 11 +- .../database/mariadb/MariaDbProvider.java | 32 +++ .../mariadb/MariaDbProviderConfig.java | 25 ++- .../database/mariadb/MariaDbProviderTest.java | 64 +++++- plugins/database-postgresql/CHANGELOG.md | 16 ++ plugins/database-postgresql/README.md | 12 +- .../docs/DATABASE-POSTGRESQL-PLUGIN.md | 14 ++ .../i18n/messages.properties | 15 ++ .../i18n/messages_es.properties | 15 ++ plugins/database-postgresql/plugin.yml | 36 ++- plugins/database-postgresql/pom.xml | 11 +- .../database/postgresql/PostgresProvider.java | 38 ++++ .../postgresql/PostgresProviderConfig.java | 25 ++- .../postgresql/PostgresProviderTest.java | 64 +++++- plugins/database/CHANGELOG.md | 47 ++++ plugins/database/README.md | 22 +- plugins/database/docs/DATABASE-PLUGIN.md | 10 +- plugins/database/i18n/messages.properties | 41 ++-- plugins/database/i18n/messages_es.properties | 41 ++-- plugins/database/plugin.yml | 38 +--- plugins/database/pom.xml | 6 +- .../database/scripts/verify-against-host.sh | 82 ++++++- .../quest/database/DatabasePluginConfig.java | 17 +- .../console/DatabaseConsoleController.java | 51 ++--- .../database/internal/ConnectionTester.java | 70 +++--- .../database/internal/DatabaseConfig.java | 60 +++-- .../database/internal/DatabaseProps.java | 153 ++++++++----- .../database/internal/DatabaseRuntime.java | 41 ++-- .../database/internal/PostgresEngine.java | 5 + .../database/internal/ProviderChoice.java | 128 +++++++++++ .../quest/database/spi/DatabaseProvider.java | 36 ++- .../quest/database/spi/ProviderSettings.java | 71 ++++++ .../database/spi/ProviderSettingsProps.java | 99 ++++++++ .../mx/quest/database/spi/package-info.java | 7 +- .../database/DatabasePluginConfigTest.java | 71 +++++- .../database/internal/DatabaseConfigTest.java | 80 ++++--- .../mx/quest/database/internal/Harness.java | 49 +++- .../database/internal/PostgresEngineTest.java | 32 +++ .../database/internal/ProviderChoiceTest.java | 146 ++++++++++++ .../database/internal/RealServerTest.java | 53 +++-- plugins/database/templates/admin-app.html | 37 +++ plugins/database/templates/admin-app.th.xml | 38 ++++ plugins/database/templates/health.html | 64 +----- plugins/database/templates/health.th.xml | 18 +- plugins/docs/PLUGIN-AUTHORING-GUIDE.md | 10 +- .../scripts/verify-against-host.sh | 7 +- pom.xml | 4 +- runway-app/pom.xml | 2 +- .../runway/backup/BackupRestoreRecovery.java | 23 +- .../mx/quest/runway/backup/BackupService.java | 212 ++++++++++++++++-- .../runway/console/AppBackupsController.java | 15 +- .../console/TenantBackupsController.java | 62 ++++- .../runway/plugin/PluginScopedServices.java | 25 ++- .../runway/plugin/PluginSettingsService.java | 14 +- .../runway/plugin/spi/PluginSettingsImpl.java | 42 ++++ .../i18n/operator-messages.properties | 7 + .../i18n/operator-messages_es.properties | 7 + .../operator/admin/widget-instances.html | 2 +- .../templates/operator/app/masters.html | 2 +- .../templates/operator/setting-row.html | 6 +- .../backup/BackupRestoreRecoveryTest.java | 61 +++++ .../runway/backup/BackupServiceTest.java | 108 +++++++++ .../quest/runway/console/AuditViewTest.java | 4 +- .../console/TenantBackupsScreenTest.java | 80 +++++++ .../plugin/PluginContributionPolicyTest.java | 35 +++ .../plugin/spi/PluginSettingsImplTest.java | 86 +++++++ runway-dist/pom.xml | 2 +- runway-plugin-protection/plugin.yml | 2 +- runway-plugin-protection/pom.xml | 2 +- .../ProtectionDescriptorK4Test.java | 2 +- .../templates/admin-app.html | 2 +- .../templates/site-protection.html | 2 +- runway-spi-testkit/pom.xml | 2 +- .../spi/testkit/FakePluginSettings.java | 19 +- .../spi/testkit/FakePluginSettingsTest.java | 10 + runway-spi/pom.xml | 2 +- .../java/mx/quest/runway/spi/RunwaySpi.java | 7 +- .../runway/spi/service/PluginSettings.java | 25 ++- .../quest/runway/spi/model/K3RecordsTest.java | 2 +- 90 files changed, 2737 insertions(+), 554 deletions(-) create mode 100644 plugins/database-mariadb/i18n/messages.properties create mode 100644 plugins/database-mariadb/i18n/messages_es.properties create mode 100644 plugins/database-postgresql/i18n/messages.properties create mode 100644 plugins/database-postgresql/i18n/messages_es.properties create mode 100644 plugins/database/src/main/java/mx/quest/database/internal/ProviderChoice.java create mode 100644 plugins/database/src/main/java/mx/quest/database/spi/ProviderSettings.java create mode 100644 plugins/database/src/main/java/mx/quest/database/spi/ProviderSettingsProps.java create mode 100644 plugins/database/src/test/java/mx/quest/database/internal/PostgresEngineTest.java create mode 100644 plugins/database/src/test/java/mx/quest/database/internal/ProviderChoiceTest.java create mode 100644 plugins/database/templates/admin-app.html create mode 100644 plugins/database/templates/admin-app.th.xml diff --git a/CHANGELOG.md b/CHANGELOG.md index 7eabcc4..f5e7758 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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 diff --git a/docs/ADMINISTRATION.md b/docs/ADMINISTRATION.md index 0c376bb..ae687ce 100644 --- a/docs/ADMINISTRATION.md +++ b/docs/ADMINISTRATION.md @@ -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-.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 `
` on a page of a + site, sign the guestbook as a visitor, and the site's schema appears on the server (`rw_s__`); 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.` 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`): - `_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//templates/.pending//`. 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; diff --git a/docs/PLUGIN-DEVELOPMENT.md b/docs/PLUGIN-DEVELOPMENT.md index eaf7c9d..4f60209 100644 --- a/docs/PLUGIN-DEVELOPMENT.md +++ b/docs/PLUGIN-DEVELOPMENT.md @@ -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:` (`provided`) and `mx.quest:runway-spi | You need | Use | Never | |---|---|---| -| your per-site settings and secrets (app-level ones: `@ConfigurationProperties("runway.plugin.")`; 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.")`; 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:` (`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/` or `/__app/` | 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//plugins/.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//plugins/.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` 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 diff --git a/docs/SITE-MANAGER-GUIDE.md b/docs/SITE-MANAGER-GUIDE.md index d5da12f..a73aa46 100644 --- a/docs/SITE-MANAGER-GUIDE.md +++ b/docs/SITE-MANAGER-GUIDE.md @@ -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 `
` 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 diff --git a/docs/SPI-STABILITY.md b/docs/SPI-STABILITY.md index 7058328..2fe3f36 100644 --- a/docs/SPI-STABILITY.md +++ b/docs/SPI-STABILITY.md @@ -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.")`; 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.")`; 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//plugins//`: 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 diff --git a/plugins/database-mariadb/CHANGELOG.md b/plugins/database-mariadb/CHANGELOG.md index 528feba..7c84963 100644 --- a/plugins/database-mariadb/CHANGELOG.md +++ b/plugins/database-mariadb/CHANGELOG.md @@ -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 diff --git a/plugins/database-mariadb/README.md b/plugins/database-mariadb/README.md index af1ce79..d527201 100644 --- a/plugins/database-mariadb/README.md +++ b/plugins/database-mariadb/README.md @@ -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). diff --git a/plugins/database-mariadb/docs/DATABASE-MARIADB-PLUGIN.md b/plugins/database-mariadb/docs/DATABASE-MARIADB-PLUGIN.md index 0b1ca52..635dfa6 100644 --- a/plugins/database-mariadb/docs/DATABASE-MARIADB-PLUGIN.md +++ b/plugins/database-mariadb/docs/DATABASE-MARIADB-PLUGIN.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. diff --git a/plugins/database-mariadb/i18n/messages.properties b/plugins/database-mariadb/i18n/messages.properties new file mode 100644 index 0000000..4ec87fd --- /dev/null +++ b/plugins/database-mariadb/i18n/messages.properties @@ -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). diff --git a/plugins/database-mariadb/i18n/messages_es.properties b/plugins/database-mariadb/i18n/messages_es.properties new file mode 100644 index 0000000..127e26a --- /dev/null +++ b/plugins/database-mariadb/i18n/messages_es.properties @@ -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). diff --git a/plugins/database-mariadb/plugin.yml b/plugins/database-mariadb/plugin.yml index 3bd2556..5830d96 100644 --- a/plugins/database-mariadb/plugin.yml +++ b/plugins/database-mariadb/plugin.yml @@ -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 } diff --git a/plugins/database-mariadb/pom.xml b/plugins/database-mariadb/pom.xml index 3d4c9e6..dfbca20 100644 --- a/plugins/database-mariadb/pom.xml +++ b/plugins/database-mariadb/pom.xml @@ -17,7 +17,7 @@ mx.quest runway-plugin-database-mariadb - 1.0.0 + 2.0.0 jar Runway Database — MariaDB @@ -38,11 +38,11 @@ UTF-8 2026-10-29T00:00:00Z - - 1.1.0 + + 1.2.0 - 1.0.0 + 2.0.0 3.5.8 @@ -160,6 +160,9 @@ + + + diff --git a/plugins/database-mariadb/src/main/java/mx/quest/database/mariadb/MariaDbProvider.java b/plugins/database-mariadb/src/main/java/mx/quest/database/mariadb/MariaDbProvider.java index 19ea2d3..7c27f52 100644 --- a/plugins/database-mariadb/src/main/java/mx/quest/database/mariadb/MariaDbProvider.java +++ b/plugins/database-mariadb/src/main/java/mx/quest/database/mariadb/MariaDbProvider.java @@ -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 running; + private final Supplier 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 running, Supplier 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 runningSettings() { + return Optional.ofNullable(running.get()); + } + + @Override + public Optional savedSettings() { + return Optional.ofNullable(saved.get()); + } } diff --git a/plugins/database-mariadb/src/main/java/mx/quest/database/mariadb/MariaDbProviderConfig.java b/plugins/database-mariadb/src/main/java/mx/quest/database/mariadb/MariaDbProviderConfig.java index baeefd5..85f2cc6 100644 --- a/plugins/database-mariadb/src/main/java/mx/quest/database/mariadb/MariaDbProviderConfig.java +++ b/plugins/database-mariadb/src/main/java/mx/quest/database/mariadb/MariaDbProviderConfig.java @@ -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)); } } diff --git a/plugins/database-mariadb/src/test/java/mx/quest/database/mariadb/MariaDbProviderTest.java b/plugins/database-mariadb/src/test/java/mx/quest/database/mariadb/MariaDbProviderTest.java index 2481091..230b4fe 100644 --- a/plugins/database-mariadb/src/test/java/mx/quest/database/mariadb/MariaDbProviderTest.java +++ b/plugins/database-mariadb/src/test/java/mx/quest/database/mariadb/MariaDbProviderTest.java @@ -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"); diff --git a/plugins/database-postgresql/CHANGELOG.md b/plugins/database-postgresql/CHANGELOG.md index 6290ba2..81e01e2 100644 --- a/plugins/database-postgresql/CHANGELOG.md +++ b/plugins/database-postgresql/CHANGELOG.md @@ -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 diff --git a/plugins/database-postgresql/README.md b/plugins/database-postgresql/README.md index 8ab572a..8da344f 100644 --- a/plugins/database-postgresql/README.md +++ b/plugins/database-postgresql/README.md @@ -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). diff --git a/plugins/database-postgresql/docs/DATABASE-POSTGRESQL-PLUGIN.md b/plugins/database-postgresql/docs/DATABASE-POSTGRESQL-PLUGIN.md index d75edf9..305c2a7 100644 --- a/plugins/database-postgresql/docs/DATABASE-POSTGRESQL-PLUGIN.md +++ b/plugins/database-postgresql/docs/DATABASE-POSTGRESQL-PLUGIN.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. diff --git a/plugins/database-postgresql/i18n/messages.properties b/plugins/database-postgresql/i18n/messages.properties new file mode 100644 index 0000000..4365643 --- /dev/null +++ b/plugins/database-postgresql/i18n/messages.properties @@ -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. diff --git a/plugins/database-postgresql/i18n/messages_es.properties b/plugins/database-postgresql/i18n/messages_es.properties new file mode 100644 index 0000000..a293b69 --- /dev/null +++ b/plugins/database-postgresql/i18n/messages_es.properties @@ -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. diff --git a/plugins/database-postgresql/plugin.yml b/plugins/database-postgresql/plugin.yml index 9511129..1cbd247 100644 --- a/plugins/database-postgresql/plugin.yml +++ b/plugins/database-postgresql/plugin.yml @@ -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 } diff --git a/plugins/database-postgresql/pom.xml b/plugins/database-postgresql/pom.xml index 2579b3f..e5c62f4 100644 --- a/plugins/database-postgresql/pom.xml +++ b/plugins/database-postgresql/pom.xml @@ -17,7 +17,7 @@ mx.quest runway-plugin-database-postgresql - 1.0.0 + 2.0.0 jar Runway Database — PostgreSQL @@ -38,11 +38,11 @@ UTF-8 2026-10-29T00:00:00Z - - 1.1.0 + + 1.2.0 - 1.0.0 + 2.0.0 42.7.10 @@ -138,6 +138,9 @@ + + + diff --git a/plugins/database-postgresql/src/main/java/mx/quest/database/postgresql/PostgresProvider.java b/plugins/database-postgresql/src/main/java/mx/quest/database/postgresql/PostgresProvider.java index 76fe8c9..e01a72e 100644 --- a/plugins/database-postgresql/src/main/java/mx/quest/database/postgresql/PostgresProvider.java +++ b/plugins/database-postgresql/src/main/java/mx/quest/database/postgresql/PostgresProvider.java @@ -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 running; + private final Supplier 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 running, Supplier 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 runningSettings() { + return Optional.ofNullable(withoutCollation(running.get())); + } + + @Override + public Optional 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); + } } diff --git a/plugins/database-postgresql/src/main/java/mx/quest/database/postgresql/PostgresProviderConfig.java b/plugins/database-postgresql/src/main/java/mx/quest/database/postgresql/PostgresProviderConfig.java index ff0abe7..7cfb75a 100644 --- a/plugins/database-postgresql/src/main/java/mx/quest/database/postgresql/PostgresProviderConfig.java +++ b/plugins/database-postgresql/src/main/java/mx/quest/database/postgresql/PostgresProviderConfig.java @@ -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)); } } diff --git a/plugins/database-postgresql/src/test/java/mx/quest/database/postgresql/PostgresProviderTest.java b/plugins/database-postgresql/src/test/java/mx/quest/database/postgresql/PostgresProviderTest.java index f1c0a26..d0b4f55 100644 --- a/plugins/database-postgresql/src/test/java/mx/quest/database/postgresql/PostgresProviderTest.java +++ b/plugins/database-postgresql/src/test/java/mx/quest/database/postgresql/PostgresProviderTest.java @@ -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"); diff --git a/plugins/database/CHANGELOG.md b/plugins/database/CHANGELOG.md index 85da997..b087cb9 100644 --- a/plugins/database/CHANGELOG.md +++ b/plugins/database/CHANGELOG.md @@ -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 diff --git a/plugins/database/README.md b/plugins/database/README.md index f165328..703e5be 100644 --- a/plugins/database/README.md +++ b/plugins/database/README.md @@ -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 diff --git a/plugins/database/docs/DATABASE-PLUGIN.md b/plugins/database/docs/DATABASE-PLUGIN.md index 1a1f3f1..a0ff397 100644 --- a/plugins/database/docs/DATABASE-PLUGIN.md +++ b/plugins/database/docs/DATABASE-PLUGIN.md @@ -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 `_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. diff --git a/plugins/database/i18n/messages.properties b/plugins/database/i18n/messages.properties index 4d7231f..23701ef 100644 --- a/plugins/database/i18n/messages.properties +++ b/plugins/database/i18n/messages.properties @@ -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. diff --git a/plugins/database/i18n/messages_es.properties b/plugins/database/i18n/messages_es.properties index fa6d635..000940d 100644 --- a/plugins/database/i18n/messages_es.properties +++ b/plugins/database/i18n/messages_es.properties @@ -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. diff --git a/plugins/database/plugin.yml b/plugins/database/plugin.yml index 6ea7138..45aacac 100644 --- a/plugins/database/plugin.yml +++ b/plugins/database/plugin.yml @@ -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//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: diff --git a/plugins/database/pom.xml b/plugins/database/pom.xml index bef2898..ddd1986 100644 --- a/plugins/database/pom.xml +++ b/plugins/database/pom.xml @@ -19,7 +19,7 @@ mx.quest runway-plugin-database - 1.0.0 + 2.0.0 jar Runway Database @@ -42,8 +42,8 @@ UTF-8 2026-10-29T00:00:00Z - - 1.1.0 + + 1.2.0 7.0.2 diff --git a/plugins/database/scripts/verify-against-host.sh b/plugins/database/scripts/verify-against-host.sh index 10fc46a..41e64b7 100755 --- a/plugins/database/scripts/verify-against-host.sh +++ b/plugins/database/scripts/verify-against-host.sh @@ -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" < "$EXT/plugin-settings/database.yml" < "$EXT/plugin-settings/database-$PROVIDER.yml" < "$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:'" diff --git a/plugins/database/src/main/java/mx/quest/database/DatabasePluginConfig.java b/plugins/database/src/main/java/mx/quest/database/DatabasePluginConfig.java index adaa877..d75d065 100644 --- a/plugins/database/src/main/java/mx/quest/database/DatabasePluginConfig.java +++ b/plugins/database/src/main/java/mx/quest/database/DatabasePluginConfig.java @@ -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 providers, PluginInfo self, - ScheduledExecutorService databaseExecutor) { + public DatabaseRuntime databaseRuntime(DatabaseProps databaseProps, ObjectProvider providers, + PluginInfo self, ScheduledExecutorService databaseExecutor) { Supplier> 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 providers, PluginInfo self) { - return new ConnectionTester(databaseRuntime, () -> providers.orderedStream().toList(), workDir(self)); + return new ConnectionTester(databaseRuntime, databaseProps, () -> providers.orderedStream().toList(), + workDir(self)); } @Bean diff --git a/plugins/database/src/main/java/mx/quest/database/console/DatabaseConsoleController.java b/plugins/database/src/main/java/mx/quest/database/console/DatabaseConsoleController.java index 6065fef..096732f 100644 --- a/plugins/database/src/main/java/mx/quest/database/console/DatabaseConsoleController.java +++ b/plugins/database/src/main/java/mx/quest/database/console/DatabaseConsoleController.java @@ -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() { diff --git a/plugins/database/src/main/java/mx/quest/database/internal/ConnectionTester.java b/plugins/database/src/main/java/mx/quest/database/internal/ConnectionTester.java index c50da07..2dc4de9 100644 --- a/plugins/database/src/main/java/mx/quest/database/internal/ConnectionTester.java +++ b/plugins/database/src/main/java/mx/quest/database/internal/ConnectionTester.java @@ -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. * *
    *
  • Running: borrows from the live pool and asks the server what it is.
  • - *
  • New settings: 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.
  • + *
  • Saved: 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).
  • *
*/ public final class ConnectionTester { @@ -44,15 +42,23 @@ public final class ConnectionTester { } private final DatabaseRuntime runtime; + private final DatabaseProps props; private final Supplier> providers; private final Path workDir; - public ConnectionTester(DatabaseRuntime runtime, Supplier> providers, Path workDir) { + public ConnectionTester(DatabaseRuntime runtime, DatabaseProps props, Supplier> 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 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 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 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; diff --git a/plugins/database/src/main/java/mx/quest/database/internal/DatabaseConfig.java b/plugins/database/src/main/java/mx/quest/database/internal/DatabaseConfig.java index 62f763c..57ad6b1 100644 --- a/plugins/database/src/main/java/mx/quest/database/internal/DatabaseConfig.java +++ b/plugins/database/src/main/java/mx/quest/database/internal/DatabaseConfig.java @@ -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 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); diff --git a/plugins/database/src/main/java/mx/quest/database/internal/DatabaseProps.java b/plugins/database/src/main/java/mx/quest/database/internal/DatabaseProps.java index a64397e..ad5c8e4 100644 --- a/plugins/database/src/main/java/mx/quest/database/internal/DatabaseProps.java +++ b/plugins/database/src/main/java/mx/quest/database/internal/DatabaseProps.java @@ -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}). + * + *

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 legacyKeys() { + List 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 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; } diff --git a/plugins/database/src/main/java/mx/quest/database/internal/DatabaseRuntime.java b/plugins/database/src/main/java/mx/quest/database/internal/DatabaseRuntime.java index c829b4c..443758c 100644 --- a/plugins/database/src/main/java/mx/quest/database/internal/DatabaseRuntime.java +++ b/plugins/database/src/main/java/mx/quest/database/internal/DatabaseRuntime.java @@ -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 configSource; - private final Supplier> providers; + private final Supplier 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 configSource, Supplier> providers, - Path workDir, ScheduledExecutorService executor) { - this.configSource = Objects.requireNonNull(configSource, "configSource"); - this.providers = Objects.requireNonNull(providers, "providers"); + public DatabaseRuntime(Supplier 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 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 { diff --git a/plugins/database/src/main/java/mx/quest/database/internal/PostgresEngine.java b/plugins/database/src/main/java/mx/quest/database/internal/PostgresEngine.java index 93b962a..4785eab 100644 --- a/plugins/database/src/main/java/mx/quest/database/internal/PostgresEngine.java +++ b/plugins/database/src/main/java/mx/quest/database/internal/PostgresEngine.java @@ -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; diff --git a/plugins/database/src/main/java/mx/quest/database/internal/ProviderChoice.java b/plugins/database/src/main/java/mx/quest/database/internal/ProviderChoice.java new file mode 100644 index 0000000..32a4fa0 --- /dev/null +++ b/plugins/database/src/main/java/mx/quest/database/internal/ProviderChoice.java @@ -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). + * + *

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 installed) { + DatabaseProvider provider = pick(props.getProvider(), installed); + String plugin = plugin(provider.id()); + ProviderSettings server = provider.runningSettings().orElseThrow(() -> tooOld(plugin)); + if (server.isEmpty()) { + List 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 supported(List 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 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 candidates = supported(installed); + if (choice.equals(AUTO)) { + Set 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 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"); + } +} diff --git a/plugins/database/src/main/java/mx/quest/database/spi/DatabaseProvider.java b/plugins/database/src/main/java/mx/quest/database/spi/DatabaseProvider.java index 6695451..9747f55 100644 --- a/plugins/database/src/main/java/mx/quest/database/spi/DatabaseProvider.java +++ b/plugins/database/src/main/java/mx/quest/database/spi/DatabaseProvider.java @@ -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. + * + *

The provider holds its server's settings (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. * *

A provider brings the driver, not the SQL. 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 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 savedSettings() { + return Optional.empty(); + } } diff --git a/plugins/database/src/main/java/mx/quest/database/spi/ProviderSettings.java b/plugins/database/src/main/java/mx/quest/database/spi/ProviderSettings.java new file mode 100644 index 0000000..e6c5da4 --- /dev/null +++ b/plugins/database/src/main/java/mx/quest/database/spi/ProviderSettings.java @@ -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. + * + *

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> 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> setting, String key) { + Optional 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(); + } +} diff --git a/plugins/database/src/main/java/mx/quest/database/spi/ProviderSettingsProps.java b/plugins/database/src/main/java/mx/quest/database/spi/ProviderSettingsProps.java new file mode 100644 index 0000000..38b68df --- /dev/null +++ b/plugins/database/src/main/java/mx/quest/database/spi/ProviderSettingsProps.java @@ -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.")} 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 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; + } +} diff --git a/plugins/database/src/main/java/mx/quest/database/spi/package-info.java b/plugins/database/src/main/java/mx/quest/database/spi/package-info.java index dc79b57..d641a00 100644 --- a/plugins/database/src/main/java/mx/quest/database/spi/package-info.java +++ b/plugins/database/src/main/java/mx/quest/database/spi/package-info.java @@ -18,8 +18,11 @@ * *

For a provider

* 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. * *

Stability

* This package evolves additively within a major version of the database plugin: interfaces gain {@code default} diff --git a/plugins/database/src/test/java/mx/quest/database/DatabasePluginConfigTest.java b/plugins/database/src/test/java/mx/quest/database/DatabasePluginConfigTest.java index 494b728..ed6a960 100644 --- a/plugins/database/src/test/java/mx/quest/database/DatabasePluginConfigTest.java +++ b/plugins/database/src/test/java/mx/quest/database/DatabasePluginConfigTest.java @@ -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 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 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 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"); diff --git a/plugins/database/src/test/java/mx/quest/database/internal/DatabaseConfigTest.java b/plugins/database/src/test/java/mx/quest/database/internal/DatabaseConfigTest.java index 3957015..458edca 100644 --- a/plugins/database/src/test/java/mx/quest/database/internal/DatabaseConfigTest.java +++ b/plugins/database/src/test/java/mx/quest/database/internal/DatabaseConfigTest.java @@ -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"); } } diff --git a/plugins/database/src/test/java/mx/quest/database/internal/Harness.java b/plugins/database/src/test/java/mx/quest/database/internal/Harness.java index 63b0482..c07986c 100644 --- a/plugins/database/src/test/java/mx/quest/database/internal/Harness.java +++ b/plugins/database/src/test/java/mx/quest/database/internal/Harness.java @@ -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 running, + Supplier saved) { return new DatabaseProvider() { + @Override + public Optional runningSettings() { + return Optional.ofNullable(running.get()); + } + + @Override + public Optional 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 schemasInNamespace() throws SQLException { diff --git a/plugins/database/src/test/java/mx/quest/database/internal/PostgresEngineTest.java b/plugins/database/src/test/java/mx/quest/database/internal/PostgresEngineTest.java new file mode 100644 index 0000000..b2b613e --- /dev/null +++ b/plugins/database/src/test/java/mx/quest/database/internal/PostgresEngineTest.java @@ -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); + } +} diff --git a/plugins/database/src/test/java/mx/quest/database/internal/ProviderChoiceTest.java b/plugins/database/src/test/java/mx/quest/database/internal/ProviderChoiceTest.java new file mode 100644 index 0000000..5cecd65 --- /dev/null +++ b/plugins/database/src/test/java/mx/quest/database/internal/ProviderChoiceTest.java @@ -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 runningSettings() { + return Optional.ofNullable(running); + } + + @Override + public Optional 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"); + } +} diff --git a/plugins/database/src/test/java/mx/quest/database/internal/RealServerTest.java b/plugins/database/src/test/java/mx/quest/database/internal/RealServerTest.java index 9c89dda..c3d7aaa 100644 --- a/plugins/database/src/test/java/mx/quest/database/internal/RealServerTest.java +++ b/plugins/database/src/test/java/mx/quest/database/internal/RealServerTest.java @@ -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")); diff --git a/plugins/database/templates/admin-app.html b/plugins/database/templates/admin-app.html new file mode 100644 index 0000000..e17dc2f --- /dev/null +++ b/plugins/database/templates/admin-app.html @@ -0,0 +1,37 @@ + +
+

Connection tests

+
+

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.

+ +
ok
+ + +
+ Running now: + Available + detail +
+ +
+ + +
+ +

No provider plugin is installed: install database-postgresql or + database-mariadb.

+
+
+ + + +
+ Edit them +
+
+
diff --git a/plugins/database/templates/admin-app.th.xml b/plugins/database/templates/admin-app.th.xml new file mode 100644 index 0000000..395f914 --- /dev/null +++ b/plugins/database/templates/admin-app.th.xml @@ -0,0 +1,38 @@ + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/plugins/database/templates/health.html b/plugins/database/templates/health.html index 66ca3a0..aa0de8e 100644 --- a/plugins/database/templates/health.html +++ b/plugins/database/templates/health.html @@ -71,66 +71,16 @@ - +
-

Connection tests

+

Settings and tests

-
- - -
-

Try other settings without saving them.

-
- -
-
- - -
-
- - -
-
- - -
-
- - -
-
- - -
-
- - -
-
- - -
-
- - -
-
-

A blank password reuses the - saved one only for the same server, database, account and TLS settings.

- -
+

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.

+ Settings and connection tests
diff --git a/plugins/database/templates/health.th.xml b/plugins/database/templates/health.th.xml index 4926451..ddff30b 100644 --- a/plugins/database/templates/health.th.xml +++ b/plugins/database/templates/health.th.xml @@ -43,20 +43,10 @@ - - - - - - - - - - - - - - + + + + diff --git a/plugins/docs/PLUGIN-AUTHORING-GUIDE.md b/plugins/docs/PLUGIN-AUTHORING-GUIDE.md index 19c40a8..d621b3a 100644 --- a/plugins/docs/PLUGIN-AUTHORING-GUIDE.md +++ b/plugins/docs/PLUGIN-AUTHORING-GUIDE.md @@ -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..*`, 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()` | diff --git a/plugins/runway-demo-database/scripts/verify-against-host.sh b/plugins/runway-demo-database/scripts/verify-against-host.sh index 7d83b3f..7c95893 100755 --- a/plugins/runway-demo-database/scripts/verify-against-host.sh +++ b/plugins/runway-demo-database/scripts/verify-against-host.sh @@ -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 } diff --git a/pom.xml b/pom.xml index 41f244d..8ba8291 100644 --- a/pom.xml +++ b/pom.xml @@ -13,7 +13,7 @@ mx.quest runway - 1.1.2 + 1.2.0 pom Runway @@ -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. --> - 2026-10-29T18:30:00Z + 2026-10-30T17:20:00Z UTF-8 + 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. -->
- + Verified server-side, stored encrypted. Leave blank to keep the current secret.
diff --git a/runway-plugin-protection/templates/site-protection.html b/runway-plugin-protection/templates/site-protection.html index e7c69d9..cea4aa4 100644 --- a/runway-plugin-protection/templates/site-protection.html +++ b/runway-plugin-protection/templates/site-protection.html @@ -57,7 +57,7 @@
- + Verified server-side, stored encrypted. Leave blank to keep the current secret.
diff --git a/runway-spi-testkit/pom.xml b/runway-spi-testkit/pom.xml index b184bb5..72e7381 100644 --- a/runway-spi-testkit/pom.xml +++ b/runway-spi-testkit/pom.xml @@ -7,7 +7,7 @@ mx.quest runway - 1.1.2 + 1.2.0 runway-spi-testkit diff --git a/runway-spi-testkit/src/main/java/mx/quest/runway/spi/testkit/FakePluginSettings.java b/runway-spi-testkit/src/main/java/mx/quest/runway/spi/testkit/FakePluginSettings.java index 595cb19..0d7baf5 100644 --- a/runway-spi-testkit/src/main/java/mx/quest/runway/spi/testkit/FakePluginSettings.java +++ b/runway-spi-testkit/src/main/java/mx/quest/runway/spi/testkit/FakePluginSettings.java @@ -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); * } * @@ -34,6 +35,7 @@ public final class FakePluginSettings implements PluginSettings { private final Map> sites = new ConcurrentHashMap<>(); private final Map secrets = new ConcurrentHashMap<>(); private final Map appSecrets = new ConcurrentHashMap<>(); + private final Map savedApp = new ConcurrentHashMap<>(); /** The declared {@code siteSettings:} defaults (replaces any set before). */ public FakePluginSettings defaults(Map 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 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 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); diff --git a/runway-spi-testkit/src/test/java/mx/quest/runway/spi/testkit/FakePluginSettingsTest.java b/runway-spi-testkit/src/test/java/mx/quest/runway/spi/testkit/FakePluginSettingsTest.java index 507bbc7..488640c 100644 --- a/runway-spi-testkit/src/test/java/mx/quest/runway/spi/testkit/FakePluginSettingsTest.java +++ b/runway-spi-testkit/src/test/java/mx/quest/runway/spi/testkit/FakePluginSettingsTest.java @@ -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)); + } } diff --git a/runway-spi/pom.xml b/runway-spi/pom.xml index cd2924b..8164011 100644 --- a/runway-spi/pom.xml +++ b/runway-spi/pom.xml @@ -7,7 +7,7 @@ mx.quest runway - 1.1.2 + 1.2.0 runway-spi diff --git a/runway-spi/src/main/java/mx/quest/runway/spi/RunwaySpi.java b/runway-spi/src/main/java/mx/quest/runway/spi/RunwaySpi.java index b9ca3d1..26a6ea8 100644 --- a/runway-spi/src/main/java/mx/quest/runway/spi/RunwaySpi.java +++ b/runway-spi/src/main/java/mx/quest/runway/spi/RunwaySpi.java @@ -77,6 +77,11 @@ public final class RunwaySpi { * empty), the calling plugin's own {@code secret}-typed app-level 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"}. + *
  • 1.2.0 — 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"}.
  • * * *

    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 running kernel — unlike {@link #VERSION}, which the compiler inlines into the diff --git a/runway-spi/src/main/java/mx/quest/runway/spi/service/PluginSettings.java b/runway-spi/src/main/java/mx/quest/runway/spi/service/PluginSettings.java index 929104b..b40956f 100644 --- a/runway-spi/src/main/java/mx/quest/runway/spi/service/PluginSettings.java +++ b/runway-spi/src/main/java/mx/quest/runway/spi/service/PluginSettings.java @@ -28,7 +28,9 @@ import mx.quest.runway.spi.model.SettingsView; *

    App-level (platform-wide) plugin settings ({@code settings:} in {@code plugin.yml}) bind through Spring * {@code @ConfigurationProperties} under {@code runway.plugin..*}, 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 appSecret(String key) { return Optional.empty(); } + + /** + * An app-level setting of the calling plugin as it is saved now, 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. + * + *

    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. + * + *

    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 savedApp(String key) { + return Optional.empty(); + } } diff --git a/runway-spi/src/test/java/mx/quest/runway/spi/model/K3RecordsTest.java b/runway-spi/src/test/java/mx/quest/runway/spi/model/K3RecordsTest.java index 513383b..3a7298c 100644 --- a/runway-spi/src/test/java/mx/quest/runway/spi/model/K3RecordsTest.java +++ b/runway-spi/src/test/java/mx/quest/runway/spi/model/K3RecordsTest.java @@ -28,7 +28,7 @@ class K3RecordsTest { @Test void theSpiIsAtOneZero() { - assertEquals("1.1.0", RunwaySpi.VERSION); + assertEquals("1.2.0", RunwaySpi.VERSION); } // --- LocalizedUrl ----------------------------------------------------------------------------------------