diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 808d8bab7..88a8ad83a 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -62,7 +62,9 @@ jobs: with: shared-key: rust-sqlpage-proj-test save-if: ${{ github.ref == 'refs/heads/main' }} + - run: sudo apt-get update && sudo apt-get install -y unixodbc-dev - run: cargo fmt --all -- --check + - run: cargo test --locked --features config-schema --test mod configuration_docs - run: cargo clippy --all-targets --all-features -- -D warnings - name: Prepare official website run: npm run site:build diff --git a/AGENTS.md b/AGENTS.md index a2cc6a4bd..7e8cbfb28 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -42,7 +42,8 @@ Update the existing page or documentation migration for changed behavior. Add a migration only for new documentation content. Build and preview the official site with the commands in its [README](./examples/official-site/README.md). -Update `configuration.md` for configuration changes. +Document server options on `AppConfig` where the site build reads them. Keep +setup examples in `configuration.md`. Add a concise CHANGELOG.md entry only for user-visible changes, and never edit an already tagged release. diff --git a/CHANGELOG.md b/CHANGELOG.md index 62ce81fd5..e75fbaf8e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,7 @@ ## unreleased +- The [configuration reference](https://sql-page.com/configuration) now lists server settings and their defaults directly from SQLPage. Search for a setting by name or link to it with a URL such as `/configuration#listen_on`. - The first-website tutorial now lets you choose an installation target, copy a command, or download an archive for macOS, Windows, Linux, or AWS Lambda. - Missing component pages on the official site return HTTP 404 and link to the catalog. Action buttons in colored alerts stay readable. - The `shell` sidebar now uses `navbar_title` and preserves the colors of the supplied logo in dark mode. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index e55e268c6..5eeb7616f 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -107,5 +107,6 @@ Deployment recreates the website's database from the site's SQL migrations. Run `npm run site` to preview changes using the same site build as deployment. -Update [configuration.md](./configuration.md) for configuration changes and +Document server options on the Rust fields of [`AppConfig`](./src/app_config.rs). +Keep setup examples in [configuration.md](./configuration.md). Update [CHANGELOG.md](./CHANGELOG.md) for user-visible changes in an unreleased version. diff --git a/Cargo.lock b/Cargo.lock index 565cc9428..15c5167d8 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4210,10 +4210,23 @@ checksum = "ab508826f74a77ca9d5aba6ff19b522583ee3eaf28a19384ff3d0e5835fadf6e" dependencies = [ "dyn-clone", "ref-cast", + "schemars_derive", "serde", "serde_json", ] +[[package]] +name = "schemars_derive" +version = "1.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e1c3a92094fa7d61aa124645844facb6b554dfc797136d0f5fd1f890e2bffc69" +dependencies = [ + "proc-macro2", + "quote", + "serde_derive_internals", + "syn 3.0.10", +] + [[package]] name = "scopeguard" version = "1.2.0" @@ -4315,6 +4328,17 @@ dependencies = [ "syn 3.0.10", ] +[[package]] +name = "serde_derive_internals" +version = "0.30.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f852137cce035d6a4df67ccce505ff6b3e9fd3a10e3e52b24dc71e650bb1a9bd" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + [[package]] name = "serde_json" version = "1.0.154" @@ -4630,6 +4654,7 @@ dependencies = [ "rustls", "rustls-acme", "rustls-native-certs", + "schemars 1.2.3", "serde", "serde_json", "sha2 0.11.1", diff --git a/Cargo.toml b/Cargo.toml index d5c3b4fa8..91b8fc65d 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -62,6 +62,7 @@ tokio = { version = "1.24.1", features = ["macros", "rt", "process", "sync"] } tokio-stream = "0.1.9" anyhow = "1" serde = "1" +schemars = { version = "1", optional = true } serde_json = { version = "1.0.82", features = [ "preserve_order", "raw_value", @@ -137,6 +138,7 @@ opentelemetry-semantic-conventions = { version = "0.33", features = ["semconv_ex [features] default = [] +config-schema = ["dep:schemars"] odbc-static = ["odbc-sys", "odbc-sys/vendored-unix-odbc"] lambda-web = [ "dep:actix-http", @@ -151,3 +153,9 @@ actix-http = "3" tempfile = "3" tokio = { version = "1", features = ["rt", "time", "test-util"] } +[[example]] +name = "export_config_schema" +# The Docker build omits this source, so Cargo cannot infer the path. +path = "examples/export_config_schema.rs" +required-features = ["config-schema"] + diff --git a/README.md b/README.md index 6bed71d75..650716c9d 100644 --- a/README.md +++ b/README.md @@ -124,7 +124,7 @@ select ## Supported databases -- [SQLite](https://www.sqlite.org/index.html), including the ability to [load extensions](./configuration.md) such as *Spatialite*. +- [SQLite](https://www.sqlite.org/index.html), including the ability to [load extensions](https://sql-page.com/configuration#sqlite_extensions) such as *Spatialite*. - [PostgreSQL](https://www.postgresql.org/), and other compatible databases such as *YugabyteDB*, *CockroachDB* and *Aurora*. - [MySQL](https://www.mysql.com/), and other compatible databases such as *MariaDB* and *TiDB*. - [Microsoft SQL Server](https://www.microsoft.com/en-us/sql-server), and all compatible databases and providers such as *Azure SQL* and *Amazon RDS*. @@ -218,7 +218,7 @@ You still need to install or provide the database-specific ODBC driver for the d - Find your [connection string](https://www.connectionstrings.com/). - It will look like this: `Driver=/opt/snowflake_odbc/lib/libSnowflake.so;Server=xyz.snowflakecomputing.com;Database=MY_DB;Schema=PUBLIC;UID=my_user;PWD=my_password` - It must reference the path to the database driver you installed earlier, plus any connection parameter required by the driver itself. Follow the instructions from the driver's own documentation. - - Use it in the [DATABASE_URL configuration option](./configuration.md) + - Use it in the [DATABASE_URL configuration option](https://sql-page.com/configuration#database_url) ## How it works diff --git a/configuration.md b/configuration.md index 9b4e504c8..790ace096 100644 --- a/configuration.md +++ b/configuration.md @@ -3,67 +3,20 @@ SQLPage can be configured through either [environment variables](https://en.wikipedia.org/wiki/Environment_variable) or a [JSON](https://en.wikipedia.org/wiki/JSON) file placed in `sqlpage/sqlpage.json`. -You can find an example configuration file in [`sqlpage/sqlpage.json`](./sqlpage/sqlpage.json). -Here are the available configuration options and their default values: - -| variable | default | description | -| --------------------------------------------- | ----------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | -| `listen_on` | 0.0.0.0:8080 | Interface and port on which the web server should listen | -| `database_url` | `sqlite://sqlpage.db?mode=rwc` in the `configuration_directory` | Database connection URL, either `dbengine://user:password@host:port/dbname` or an ODBC connection string. Special characters should be [percent-encoded](https://developer.mozilla.org/en-US/docs/Glossary/percent-encoding). See [Database connection strings](#database-connection-strings) for details and examples. When left unset, SQLPage looks for an existing db or creates `sqlpage.db` in the `configuration_directory`, with a fallback to in-memory if unwritable.| -| `database_password` | | Database password. If set, this will override any password specified in the `database_url`. This allows you to keep the password separate from the connection string for better security. | -| `port` | 8080 | Like listen_on, but specifies only the port. | -| `unix_socket` | | Path to a UNIX socket to listen on instead of the TCP port. If specified, SQLPage will accept HTTP connections only on this socket and not on any TCP port. This option is mutually exclusive with `listen_on` and `port`. -| `host` | | The web address where your application is accessible (e.g., "myapp.example.com"). Used for login redirects with OIDC. | -| `max_database_pool_connections` | PostgreSQL: 50
MySql: 75
SQLite: 16, or 128 in memory
MSSQL: 100
ODBC: 50 | How many simultaneous database connections to open at most | -| `database_connection_idle_timeout_seconds` | SQLite: None
All other: 30 minutes | Automatically close database connections after this period of inactivity. Set to 0 to disable. | -| `database_connection_max_lifetime_seconds` | SQLite: None
All other: 60 minutes | Always close database connections after this amount of time. Set to 0 to disable. | -| `database_connection_retries` | 6 | Database connection attempts before giving up. Retries will happen every 5 seconds. | -| `database_connection_acquire_timeout_seconds` | 10 | How long to wait when acquiring a database connection from the pool before giving up and returning an error. | -| `sqlite_extensions` | | An array of SQLite extensions to load, such as `mod_spatialite`. When set through an environment variable, use a space-separated list. | -| `web_root` | `.` | The root directory of the web server, where the `index.sql` file is located. Static file serving follows symlinks, so do not place symlinks under `web_root` that point to private paths (such as the `sqlpage/` config directory) or to files outside `web_root`, as their targets would become publicly reachable (see [`SECURITY.md`](./SECURITY.md)). | -| `site_prefix` | `/` | Base path of the site. If you want to host SQLPage at `https://example.com/sqlpage/`, set this to `/sqlpage/`. When using a reverse proxy, this allows hosting SQLPage together with other applications on the same subdomain. | -| `configuration_directory` | `./sqlpage/` | The directory where the `sqlpage.json` file is located. This is used to find the path to [`templates/`](https://sql-page.com/custom_components.sql), [`migrations/`](https://sql-page.com/your-first-sql-website/migrations.sql), and `on_connect.sql`. Obviously, this configuration parameter can be set only through environment variables, not through the `sqlpage.json` file itself in order to find the `sqlpage.json` file. Be careful not to use a path that is accessible from the public WEB_ROOT | -| `allow_exec` | false | Allow usage of the `sqlpage.exec` function. Do this only if all users with write access to sqlpage query files and to the optional `sqlpage_files` table on the database are trusted. | -| `max_uploaded_file_size` | 5242880 | Maximum size of forms and uploaded files in bytes. Defaults to 5 MiB. | -| `oidc_protected_paths` | `["/"]` | A list of URL prefixes that should be protected by OIDC authentication. By default, all paths are protected (`["/"]`). If you want to make some pages public, you can restrict authentication to a sub-path, for instance `["/admin", "/users/settings"]`. Decoded dot and repeated-separator aliases are normalized before matching, and protected prefixes also match ASCII case aliases on case-insensitive storage. All paths must start with a "/" and will be prepended by `site_prefix` if defined. When set through an environment variable, use a space-separated list, such as `/admin /users/settings`.| -| `oidc_public_paths` | `[]` | A list of URL prefixes that should be publicly available. By default, no paths are publicly accessible (`[]`). If you want to make some pages public, you can bypass authentication for a sub-path, for instance `["/public/", "/assets/"]`. Keep in mind that without the closing backslashes, that any directory or file starting with `public` or `assets` will be publicly available. This will also overwrite any protected path restriction. If you have a private path `/private` and you define the public path `/private/public/` everything in `/private/public/` will be publicly accessible, while everything else in private will still need authentication. All paths must start with a "/" and will be prepended by `site_prefix` if defined. When set through an environment variable, use a space-separated list, such as `/public/ /assets/`. -| `oidc_issuer_url` | | The base URL of the [OpenID Connect provider](#openid-connect-oidc-authentication). Required for enabling Single Sign-On. | -| `oidc_client_id` | sqlpage | The ID that identifies your SQLPage application to the OIDC provider. You get this when registering your app with the provider. | -| `oidc_client_secret` | | The secret key for your SQLPage application. Keep this confidential as it allows your app to authenticate with the OIDC provider. | -| `oidc_scopes` | openid email profile | Space-separated list of [scopes](https://openid.net/specs/openid-connect-core-1_0.html#ScopeClaims) your app requests from the OIDC provider. | -| `oidc_additional_trusted_audiences` | unset | A list of additional audiences that are allowed in JWT tokens, beyond the client ID. When empty or unset, any additional audience is accepted. For increased security, set to an empty list `[]` in the configuration file to only allow the client ID as audience. When set through an environment variable, use a space-separated list, such as `audience-one audience-two`. | -| `max_pending_rows` | 256 | Maximum number of rendered rows that can be queued up in memory when a client is slow to receive them. | -| `compress_responses` | false | When the client supports it, compress the http response body. This can save bandwidth and speed up page loading on slow connections, but can also increase CPU usage and cause rendering delays on pages that take time to render (because streaming responses are buffered for longer than necessary). | -| `https_domain` | | Domain name to request a certificate for. Setting this parameter will automatically make SQLPage listen on port 443 and request an SSL certificate. The server will take a little bit longer to start the first time it has to request a certificate. HTTPS is always served on port 443; if `listen_on` or `port` names a different port, SQLPage also serves plain HTTP there. | -| `https_certificate_email` | contact@ | The email address to use when requesting a certificate. | -| `https_certificate_cache_dir` | ./sqlpage/https | A writeable directory where to cache the certificates, so that SQLPage can serve https traffic immediately when it restarts. The default ignores `web_root` and `configuration_directory`. | -| `https_acme_directory_url` | https://acme-v02.api.letsencrypt.org/directory | The URL of the ACME directory to use when requesting a certificate. | -| `environment` | development | The environment in which SQLPage is running. Can be either `development` or `production`. In `production` mode, SQLPage will hide error messages and stack traces from the user, and will cache sql files in memory to avoid reloading them from disk. | -| `cache_stale_duration_ms` | 1000 (prod), 0 (dev) | The duration in milliseconds that a file can be cached before its freshness is checked against the filesystem. Defaults to 1000ms (1 second) in production and 0ms in development. | -| `content_security_policy` | `script-src 'self' 'nonce-{NONCE}'` | The [Content Security Policy](https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP) to set in the HTTP headers. If you get CSP errors in the browser console, you can set this to the empty string to disable CSP. If you want a custom CSP that contains a nonce, include the `'nonce-{NONCE}'` directive in your configuration string and it will be populated with a random value per request. | -| `smtp_host` | | SMTP server host used by the `sqlpage.send_mail` function. Set with `SMTP_HOST` in the environment. | -| `smtp_port` | 25 (`none`), 465 (`tls`), or 587 (`starttls`) | SMTP server port. The default depends on `smtp_tls_mode`. Set this explicitly for relays using a nonstandard port. | -| `smtp_username` | | Optional SMTP user name for `sqlpage.send_mail`. When set, SQLPage authenticates to `SMTP_HOST` using this user name and `smtp_password`. Credentials require `smtp_tls_mode` to be `starttls` or `tls`. | -| `smtp_password` | | Optional SMTP password for `sqlpage.send_mail`. `smtp_username` and `smtp_password` must be configured together. | -| `smtp_from` | | Default sender address for `sqlpage.send_mail`, optionally including a display name. Individual messages can override it with their `from` property. | -| `smtp_tls_mode` | `starttls` | Encryption mode for `sqlpage.send_mail`: `starttls` requires a STARTTLS upgrade, `tls` uses TLS from connection start, and `none` permits plaintext only without credentials for trusted local SMTP servers. | -| `max_email_attachment_size` | 10485760 | Maximum combined decoded size, in bytes, of all attachments in one email. Defaults to 10 MiB. This is independent of `max_uploaded_file_size` because attachments may come from sources other than form uploads. | -| `system_root_ca_certificates` | true when `SSL_CERT_FILE` or `SSL_CERT_DIR` is set, false otherwise | Whether to use the system root CA certificates to validate SSL certificates when making http requests with `sqlpage.fetch`. If set to false, SQLPage will use its own set of root CA certificates. The `SSL_CERT_FILE` and `SSL_CERT_DIR` environment variables define what the system store contains, so setting either of them also turns this option on by default. | -| `max_recursion_depth` | 10 | Maximum depth of recursion allowed in the `run_sql` function. Values above 255 stop the server from starting. | -| `markdown_allow_dangerous_html` | false | Whether to allow raw HTML in markdown content. Only enable this if the markdown content is fully trusted (not user generated). | -| `markdown_allow_dangerous_protocol` | false | Whether to allow dangerous protocols (like javascript:) in markdown links. Only enable this if the markdown content is fully trusted (not user generated). | +You can find an example configuration file in [`sqlpage/sqlpage.json`](https://github.com/sqlpage/SQLPage/blob/main/sqlpage/sqlpage.json). +See the [configuration reference](https://sql-page.com/configuration) for every option, its accepted values, and its default. Multiple configuration file formats are supported: you can use a [`.json5`](https://json5.org/) file, a [`.toml`](https://toml.io/) file, or a [`.yaml`](https://en.wikipedia.org/wiki/YAML#Syntax) file. ## Environment variables -All the parameters above can be set through environment variables. +Configuration options can also be set through environment variables. The name of the environment variable is the same as the name of the configuration variable, but in uppercase. -The environment variable name can optionally be prefixed with `SQLPAGE_`. +For settings read from the configuration file, the environment variable overrides the file, and a variable prefixed with `SQLPAGE_` takes precedence over its unprefixed form. Additionnally, when troubleshooting, you can set the [`LOG_LEVEL`](https://docs.rs/tracing-subscriber/latest/tracing_subscriber/filter/struct.EnvFilter.html) @@ -121,7 +74,7 @@ DATABASE_URL="Driver={SnowflakeDSIIDriver};Server=account.snowflakecomputing.com ODBC drivers must be installed and configured on your system. On Linux, the `unixODBC` driver manager is statically linked into the SQLPage binary, so you usually only need to install and configure the database-specific ODBC driver for your target database (for example Snowflake, Oracle, DuckDB...). -The `-duckdb` [docker image variants](./README.md#install-your-odbc-database-driver) ships with `DATABASE_URL` set to `DSN=DuckDB`so that the container uses a DuckDB file instead of SQLite. +The [DuckDB image variant](https://github.com/sqlpage/SQLPage#install-your-odbc-database-driver) includes the DuckDB ODBC driver and defaults to a DuckDB database file. If the `database_password` configuration parameter is set, it will override any password specified in the `database_url`. It does not need to be percent-encoded. diff --git a/examples/export_config_schema.rs b/examples/export_config_schema.rs new file mode 100644 index 000000000..3101475b3 --- /dev/null +++ b/examples/export_config_schema.rs @@ -0,0 +1,15 @@ +use schemars::generate::SchemaSettings; +use sqlpage::app_config::AppConfig; +use std::io::{self, Write}; + +fn main() -> anyhow::Result<()> { + let settings = + SchemaSettings::draft2020_12().with(|settings| settings.inline_subschemas = true); + let schema = settings + .into_generator() + .into_root_schema_for::(); + let mut stdout = io::stdout().lock(); + serde_json::to_writer_pretty(&mut stdout, &schema)?; + writeln!(stdout)?; + Ok(()) +} diff --git a/examples/official-site/configuration.sql b/examples/official-site/configuration.sql new file mode 100644 index 000000000..3dea998a3 --- /dev/null +++ b/examples/official-site/configuration.sql @@ -0,0 +1,14 @@ +select 'shell-docs' as component, 'Configuration | SQLPage' as title, 'Configuration' as section; + +select 'docs-reference-heading' as component, 'configuration' as id, 'Documentation' as section, + '/documentation.sql' as link, 'settings' as icon, 'Configuration' as title, + 'Server settings, accepted values, and defaults.' as description; + +select 'text' as component, + 'Set options in your configuration file or use their uppercase names as environment variables. The [configuration guide](https://github.com/sqlpage/SQLPage/blob/main/configuration.md) covers file formats, connection strings, and setup examples.' as contents_md; + +select 'docs-parameters' as component; +select 'options' as id, 'Options' as title, json_group_array(json_object( + 'name', name, 'anchor', name, 'type', type, 'description_md', description_md, + 'default_md', coalesce(default_md, 'Unset') +) order by name) as parameters from config_option; diff --git a/examples/official-site/documentation.sql b/examples/official-site/documentation.sql index 58a8074a4..92017596d 100644 --- a/examples/official-site/documentation.sql +++ b/examples/official-site/documentation.sql @@ -29,6 +29,8 @@ select case kind when 'component' then 'Components' else 'Functions' end as titl (kind = 'function' and name in ('fetch', 'link', 'run_sql', 'variables')) ) as links from reference_entry group by kind order by kind; +select 'Configuration' as title, 'settings' as icon, '/configuration' as link, + 'Look up server settings, accepted values, and defaults.' as description; select 'title' as component, 'Anatomy of a SQL page' as contents, 2 as level, 'how-it-works' as id; select 'text' as component, 'Each SQL file is a page. Its first SELECT names a component and sets its top-level parameters. The rows returned by the next SELECT supply the row-level parameters. This list uses both.' as contents; diff --git a/examples/official-site/llms.txt.sql b/examples/official-site/llms.txt.sql index 106080336..a88439718 100644 --- a/examples/official-site/llms.txt.sql +++ b/examples/official-site/llms.txt.sql @@ -51,7 +51,7 @@ Key features: - [Components reference](/components.sql): List of all ' || (select count(*) from component) || ' built-in UI components with parameters and examples - [Functions reference](/functions.sql): SQLPage built-in functions for handling requests, encoding data, and more -- [Configuration guide](https://github.com/sqlpage/SQLPage/blob/main/configuration.md): Complete list of configuration options in sqlpage.json +- [Configuration reference](/configuration): Accepted values and defaults for SQLPage server settings ## Components diff --git a/examples/official-site/safety.sql b/examples/official-site/safety.sql index 2ba06a7fc..8522ed1cb 100644 --- a/examples/official-site/safety.sql +++ b/examples/official-site/safety.sql @@ -144,7 +144,7 @@ For more information, see the [this discussion](https://github.com/sqlpage/SQLPa ## Database connections SQLPage uses a fixed pool of database connections, and will never open more connections than the ones you -[configured](https://github.com/sqlpage/SQLPage/blob/main/configuration.md). So even under heavy load, your database +[configured](/configuration#max_database_pool_connections). So even under heavy load, your database connection limit will never be saturated by SQLPage. And SQLPage will accept any restriction you put on the database user you use to connect to your database, so you can diff --git a/examples/official-site/search.sql b/examples/official-site/search.sql index eede7173a..a367e5891 100644 --- a/examples/official-site/search.sql +++ b/examples/official-site/search.sql @@ -7,6 +7,9 @@ where name = lower($search) or (kind = 'function' and lower($search) in ( )) order by kind limit 1; +select 'redirect' as component, '/configuration#' || name as link +from config_option where name = lower($search); + select 'shell-docs' as component, 'Search' as section, coalesce($search || ' | ', '') || 'SQLPage documentation search' as title; @@ -17,7 +20,10 @@ set escaped_search = '"' || replace(coalesce($search, ''), '"', '""') || '"'; with matches as ( select title, trim(description, char(13) || char(10) || ' ') as summary, page, parameters, fragment, rank, - row_number() over (partition by page, parameters order by rank, rowid) as position + row_number() over ( + partition by page, parameters, case when page = '/configuration' then fragment end + order by rank, rowid + ) as position from documentation_fts where documentation_fts match $escaped_search ) diff --git a/examples/official-site/sqlpage/templates/docs-parameters.handlebars b/examples/official-site/sqlpage/templates/docs-parameters.handlebars index 4642c7f1f..bf5c9f0c2 100644 --- a/examples/official-site/sqlpage/templates/docs-parameters.handlebars +++ b/examples/official-site/sqlpage/templates/docs-parameters.handlebars @@ -14,7 +14,7 @@ {{#if required}}Required{{/if}} -
{{{markdown description_md}}}
+
{{{markdown description_md}}}{{#if default_md}}

Default

{{{markdown default_md}}}{{/if}}
{{/each}} diff --git a/examples/official-site/sqlpage/templates/shell-docs.handlebars b/examples/official-site/sqlpage/templates/shell-docs.handlebars index 30dfc4a1f..2bddb6408 100644 --- a/examples/official-site/sqlpage/templates/shell-docs.handlebars +++ b/examples/official-site/sqlpage/templates/shell-docs.handlebars @@ -101,7 +101,7 @@ Blog Performance Security - Configuration + Configuration Community {{icon_img "arrow-up" 16}} Back to top diff --git a/examples/official-site/test.hurl b/examples/official-site/test.hurl index 99061a770..c50a035e8 100644 --- a/examples/official-site/test.hurl +++ b/examples/official-site/test.hurl @@ -19,6 +19,19 @@ xpath "string(//main//a[normalize-space()='Components']/@href)" == "/components. xpath "string(//main//a[normalize-space()='Functions']/@href)" == "/functions.sql" body not contains "An error occurred" +GET http://localhost:8080/configuration +HTTP 200 +[Asserts] +xpath "//*[@id='listen_on']//a[@href='#listen_on']" count == 1 +xpath "normalize-space(//*[@id='listen_on']/dd)" contains "443" +xpath "//*[@id='database_connection_idle_timeout_seconds']" count == 1 +body not contains "An error occurred" + +GET http://localhost:8080/search.sql?search=LISTEN_ON +HTTP 302 +[Asserts] +header "Location" == "/configuration#listen_on" + GET http://localhost:8080/components.sql HTTP 200 [Asserts] diff --git a/examples/official-site/your-first-sql-website/nginx.md b/examples/official-site/your-first-sql-website/nginx.md index 59235958b..1586f2cb4 100644 --- a/examples/official-site/your-first-sql-website/nginx.md +++ b/examples/official-site/your-first-sql-website/nginx.md @@ -78,7 +78,7 @@ but will increase the load on your SQLPage server, and reduce the amount of user Refer to the official documentation for [proxy buffering](https://nginx.org/en/docs/http/ngx_http_proxy_module.html#proxy_buffering), [gzip](https://nginx.org/en/docs/http/ngx_http_gzip_module.html), and [chunked transfer](https://nginx.org/en/docs/http/ngx_http_core_module.html#chunked_transfer_encoding) when tuning these values. -When SQLPage sits behind a reverse proxy, set `compress_responses` to `false` [in `sqlpage.json`](https://github.com/sqlpage/SQLPage/blob/main/configuration.md) so that NGINX compresses once at the edge. +When SQLPage sits behind a reverse proxy, set `compress_responses` to `false` [in `sqlpage.json`](/configuration#compress_responses) so that NGINX compresses once at the edge. ### URL Rewriting diff --git a/examples/official-site/your-first-sql-website/tutorial.md b/examples/official-site/your-first-sql-website/tutorial.md index 7ef99a11e..497ca7ea7 100644 --- a/examples/official-site/your-first-sql-website/tutorial.md +++ b/examples/official-site/your-first-sql-website/tutorial.md @@ -87,7 +87,7 @@ Later, when you want to deploy your website online, you can switch back to a per > For instance, a SQL Server database named `db` running on `localhost` port `1433` with the username `funny:user` and the password `p@ssw0rd` would be represented as > `mssql://funny%3Auser:p%40ssw0rd@localhost:1433/db`. -For more information about the properties that can be set in sqlpage.json, see [SQLPage's configuration documentation](https://github.com/sqlpage/SQLPage/blob/main/configuration.md#configuring-sqlpage) +For more information about the properties that can be set in sqlpage.json, see [SQLPage's configuration reference](/configuration). ![screenshot for the full sql website folder organisation](full-website.png) @@ -180,7 +180,7 @@ If you prefer to host your website yourself, you can use a cloud provider or a V - [Setup docker](https://github.com/sqlpage/SQLPage?tab=readme-ov-file#with-docker) or another process manager such as [systemd](https://github.com/sqlpage/SQLPage/blob/main/sqlpage.service) to start SQLPage automatically when your server boots and to keep it running - Optionally, [setup a reverse proxy](nginx.sql) to avoid exposing SQLPage directly to the internet - Optionally, setup a TLS certificate to enable HTTPS -- Configure connection to a cloud database or a database running on your server in [`sqlpage.json`](https://github.com/sqlpage/SQLPage/blob/main/configuration.md#configuring-sqlpage) +- Configure connection to a cloud database or a database running on your server in [`database_url`](/configuration#database_url) ## Go further diff --git a/package.json b/package.json index 62cae9e5d..91daa2a26 100644 --- a/package.json +++ b/package.json @@ -8,7 +8,7 @@ "typecheck": "tsc && tsc -p tests/js && tsc -p tests/end-to-end", "format": "biome format --write .", "fix": "biome check --fix --unsafe .", - "site:build": "node scripts/site-build.mjs", + "site:build": "cargo run --locked --quiet --features config-schema --example export_config_schema | node scripts/site-build.mjs", "site": "npm run build && npm run site:build && cd target/official-site && cargo run --locked --manifest-path ../../Cargo.toml" }, "repository": { diff --git a/scripts/site-build.mjs b/scripts/site-build.mjs index 96a3d5c90..03c31af1d 100644 --- a/scripts/site-build.mjs +++ b/scripts/site-build.mjs @@ -4,10 +4,13 @@ import { existsSync, mkdirSync, mkdtempSync, + readFileSync, renameSync, rmSync, + writeFileSync, } from "node:fs"; import { dirname, join, relative, resolve } from "node:path"; +import { buildConfigurationMigration } from "./site-configuration.mjs"; const repository = resolve(import.meta.dirname, ".."); const siteDirectory = join(repository, "target", "official-site"); @@ -21,7 +24,7 @@ const excluded = new Set([ join("sqlpage", "https"), ]); -function buildSite() { +function buildSite(configurationSchema) { const parent = dirname(siteDirectory); mkdirSync(parent, { recursive: true }); const temporary = mkdtempSync(join(parent, ".official-site-")); @@ -36,6 +39,10 @@ function buildSite() { join(repository, "configuration.md"), join(next, "configuration.md"), ); + writeFileSync( + join(next, "sqlpage", "migrations", "1000_configuration_reference.sql"), + buildConfigurationMigration(configurationSchema), + ); // Stage the complete site before exchanging the previous preview. try { renameSync(siteDirectory, previous); @@ -56,4 +63,4 @@ function buildSite() { } } -buildSite(); +buildSite(JSON.parse(readFileSync(0, "utf8"))); diff --git a/scripts/site-configuration.mjs b/scripts/site-configuration.mjs new file mode 100644 index 000000000..d6b2d984c --- /dev/null +++ b/scripts/site-configuration.mjs @@ -0,0 +1,58 @@ +function schemaType(schema) { + if (schema.enum) + return schema.enum.map((value) => JSON.stringify(value)).join(" | "); + if (schema.anyOf) return schema.anyOf.map(schemaType).join(" or "); + const types = Array.isArray(schema.type) ? schema.type : [schema.type]; + return types + .map((type) => { + if (type === "array") return `${schemaType(schema.items)}[]`; + if (type === "integer" || type === "number") { + if (schema.minimum !== undefined && schema.maximum !== undefined) + return `${type} (${schema.minimum} to ${schema.maximum})`; + if (schema.minimum !== undefined) + return `${type} (≥ ${schema.minimum})`; + if (schema.maximum !== undefined) + return `${type} (≤ ${schema.maximum})`; + } + if (typeof type !== "string") + throw new Error("Missing configuration option type"); + return type; + }) + .join(" or "); +} + +function configDefault(schema) { + if (schema["x-default-description"]) return schema["x-default-description"]; + if (!Object.hasOwn(schema, "default")) return null; + const value = JSON.stringify(schema.default); + const longestTick = Math.max( + 0, + ...(value.match(/`+/g) ?? []).map((s) => s.length), + ); + const delimiter = "`".repeat(longestTick + 1); + return `${delimiter}${value}${delimiter}`; +} + +export function buildConfigurationMigration(schema) { + const options = Object.entries(schema.properties).map(([name, option]) => ({ + name, + type: schemaType(option), + default_md: configDefault(option) ?? null, + description_md: option.description, + })); + + return `CREATE TABLE config_option ( + name TEXT PRIMARY KEY, + type TEXT NOT NULL, + default_md TEXT, + description_md TEXT NOT NULL +); + +INSERT INTO config_option +SELECT value ->> 'name', value ->> 'type', value ->> 'default_md', value ->> 'description_md' +FROM json_each('${JSON.stringify(options).replaceAll("'", "''")}'); + +INSERT INTO documentation_fts(title, description, page, fragment) +SELECT name, description_md, '/configuration', name FROM config_option; +`; +} diff --git a/src/app_config.rs b/src/app_config.rs index 6e9166457..e899139f2 100644 --- a/src/app_config.rs +++ b/src/app_config.rs @@ -14,9 +14,16 @@ use std::path::{Path, PathBuf}; use std::str::FromStr; use std::time::Duration; -#[cfg(not(feature = "lambda-web"))] +#[cfg(any(not(feature = "lambda-web"), feature = "config-schema"))] const DEFAULT_DATABASE_FILE: &str = "sqlpage.db"; +const DEFAULT_IDLE_TIMEOUT: Duration = Duration::from_mins(30); +const DEFAULT_MAX_LIFETIME: Duration = Duration::from_hours(1); +const CERTIFICATE_CACHE_DIRECTORY: &str = "sqlpage/https"; + +#[cfg(feature = "config-schema")] +mod schema; + impl AppConfig { pub fn from_cli(cli: &Cli) -> anyhow::Result { let mut config = if let Some(config_file) = &cli.config_file { @@ -92,19 +99,11 @@ impl AppConfig { let is_sqlite = self.database_url.starts_with("sqlite:"); self.database_connection_idle_timeout = resolve_timeout( self.database_connection_idle_timeout, - if is_sqlite { - None - } else { - Some(Duration::from_mins(30)) - }, + (!is_sqlite).then_some(DEFAULT_IDLE_TIMEOUT), ); self.database_connection_max_lifetime = resolve_timeout( self.database_connection_max_lifetime, - if is_sqlite { - None - } else { - Some(Duration::from_hours(1)) - }, + (!is_sqlite).then_some(DEFAULT_MAX_LIFETIME), ); } @@ -207,210 +206,252 @@ pub fn load_from_env() -> anyhow::Result { .with_context(|| format!("Unable to load configuration from {}", config_dir.display())) } +/// Settings accepted in a server configuration file. #[derive(Debug, Deserialize, PartialEq, Clone)] +#[cfg_attr(feature = "config-schema", derive(schemars::JsonSchema))] +#[cfg_attr(feature = "config-schema", schemars(transform = schema::remove_unset_defaults))] #[allow(clippy::struct_excessive_bools)] pub struct AppConfig { + /// Database connection URL or ODBC connection string. Percent-encode special + /// characters in URL usernames and passwords. See [Database connection strings](https://github.com/sqlpage/SQLPage/blob/main/configuration.md#database-connection-strings). + /// The server also recognizes an existing `sqlpage.db` in the working directory for compatibility. #[serde(default = "default_database_url")] + #[cfg_attr(feature = "config-schema", schemars(default, extend("x-default-description" = format!( + "SQLite file `{DEFAULT_DATABASE_FILE}` in the configuration directory, or in-memory SQLite on Lambda or when the directory is unwritable." + ))))] pub database_url: String, - /// A separate field for the database password. If set, this will override any password specified in the `database_url`. + + /// Overrides the password in `database_url`. This value does not require percent encoding. #[serde(default)] pub database_password: Option, + + /// Maximum number of simultaneous database connections. Must be greater than zero. + #[cfg_attr(feature = "config-schema", schemars(extend("x-default-description" = schema::pool_sizes())))] pub max_database_pool_connections: Option, + + /// Close a database connection after this many idle seconds. Set to zero to disable. #[serde( default, deserialize_with = "deserialize_duration_seconds", rename = "database_connection_idle_timeout_seconds" )] + #[cfg_attr(feature = "config-schema", schemars(with = "Option", extend( + "x-default-description" = schema::timeout(DEFAULT_IDLE_TIMEOUT) + )))] pub database_connection_idle_timeout: Option, + + /// Maximum age in seconds of a connection in the pool. Set to zero to disable. #[serde( default, deserialize_with = "deserialize_duration_seconds", rename = "database_connection_max_lifetime_seconds" )] + #[cfg_attr(feature = "config-schema", schemars(with = "Option", extend( + "x-default-description" = schema::timeout(DEFAULT_MAX_LIFETIME) + )))] pub database_connection_max_lifetime: Option, + /// SQLite extensions to load, such as `mod_spatialite`. Use a space-separated list in environment variables. #[serde(default)] pub sqlite_extensions: Vec, + /// Host and port on which to listen, for example `127.0.0.1:8080` or `localhost:8080`. #[serde(default, deserialize_with = "deserialize_socket_addr")] + #[cfg_attr(feature = "config-schema", schemars(with = "Option", extend( + "x-default-description" = format!("`{}` with `https_domain`, otherwise `{}`.", + default_listen_on(true), default_listen_on(false) + ) + )))] pub listen_on: Option, + + /// Overrides the port in `listen_on`. A Kubernetes service URI in this setting is ignored. #[serde(default, deserialize_with = "deserialize_port")] + #[cfg_attr(feature = "config-schema", schemars(with = "Option", extend("x-default-description" = "The port in `listen_on`.")))] pub port: Option, + + /// Unix socket path. On Unix this serves HTTP exclusively on the socket and overrides TCP listener settings. pub unix_socket: Option, - /// Number of times to retry connecting to the database after a failure when the server starts - /// up. Retries will happen every 5 seconds. The default is 6 retries, which means the server - /// will wait up to 30 seconds for the database to become available. + /// Number of times to retry a failed database connection at startup, with five seconds between attempts. #[serde(default = "default_database_connection_retries")] pub database_connection_retries: u32, - /// Maximum number of seconds to wait before giving up when acquiring a database connection from the - /// pool. The default is 10 seconds. + /// Maximum time in seconds to wait for a connection from the database pool. Must be positive. #[serde(default = "default_database_connection_acquire_timeout_seconds")] pub database_connection_acquire_timeout_seconds: f64, - /// The directory where the .sql files are located. Defaults to the current directory. + /// Root directory for SQL pages and static files. Static serving follows symlinks. + /// A symlink under the web root exposes its target, including files outside the web root. + /// Keep links to private files and directories outside the web root. See the [security guide](https://github.com/sqlpage/SQLPage/blob/main/SECURITY.md). #[serde(default = "default_web_root")] + #[cfg_attr( + feature = "config-schema", + schemars(default = "schema::working_directory") + )] pub web_root: PathBuf, - /// The directory where the sqlpage configuration file is located. Defaults to `./sqlpage`. + /// Directory containing the configuration file, templates, migrations, and connection management scripts. + /// Keep this directory private. To select it before the server looks for the configuration file, + /// pass `--config-dir` or set `CONFIGURATION_DIRECTORY` or `SQLPAGE_CONFIGURATION_DIRECTORY`. #[serde(default = "configuration_directory")] + #[cfg_attr( + feature = "config-schema", + schemars(default = "default_configuration_directory") + )] pub configuration_directory: PathBuf, - /// Set to true to allow the `sqlpage.exec` function to be used in SQL queries. - /// This should be enabled only if you trust the users writing SQL queries, since it gives - /// them the ability to execute arbitrary shell commands on the server. + /// Allow `sqlpage.exec` to execute server-side commands. Enable only if everyone who can write SQL pages, + /// including through the `sqlpage_files` database table, is trusted to run arbitrary commands. #[serde(default)] pub allow_exec: bool, - /// SMTP server host used by the `sqlpage.send_mail` function. + /// SMTP server hostname or IP address used by `sqlpage.send_mail`. Required when configuring a port, credentials, or sender. pub smtp_host: Option, - /// SMTP server port. Defaults to 25 for plaintext, 465 for implicit TLS, and 587 for STARTTLS. + /// Port used to connect to the SMTP server. Valid ports range from 1 to 65535. + #[cfg_attr(feature = "config-schema", schemars(extend("x-default-description" = format!( + "{} for `none`, {} for `tls`, {} for `starttls`.", + SmtpTlsMode::None.default_port(), SmtpTlsMode::Tls.default_port(), SmtpTlsMode::Starttls.default_port() + ))))] pub smtp_port: Option, - /// Optional SMTP user name used by the `sqlpage.send_mail` function. - /// If set, `SQLPage` authenticates to `SMTP_HOST` with this user name and `smtp_password`. + /// SMTP username. Set it together with `smtp_password` and use `starttls` or `tls`. pub smtp_username: Option, - /// Optional SMTP password used by the `sqlpage.send_mail` function when `smtp_username` is set. + /// SMTP password. Set it together with `smtp_username`. pub smtp_password: Option, - /// Default sender used by the `sqlpage.send_mail` function when the message has no `from` property. + /// Default sender address for `sqlpage.send_mail`, optionally including a display name. + /// The message's `from` property overrides this setting. pub smtp_from: Option, - /// Encryption mode used to connect to `SMTP_HOST`. + /// SMTP transport security. Use `starttls` to require a STARTTLS upgrade or `tls` to use TLS from connection start. + /// Use `none` only with a trusted relay that does not require credentials. #[serde(default)] pub smtp_tls_mode: SmtpTlsMode, - /// Maximum combined decoded size of attachments in one email. + /// Maximum combined size in bytes of decoded attachments in one email, independent of the upload limit. #[serde(default = "default_max_email_attachment_size")] pub max_email_attachment_size: usize, - /// Maximum size of uploaded files in bytes. The default is 5MiB (5 * 1024 * 1024 bytes) + /// Maximum size in bytes of submitted forms and uploaded files. #[serde(default = "default_max_file_size")] pub max_uploaded_file_size: usize, - /// The base URL of the `OpenID` Connect provider. - /// Required when enabling Single Sign-On through an OIDC provider. + /// Issuer URL of the [OpenID Connect provider](https://github.com/sqlpage/SQLPage/blob/main/configuration.md#openid-connect-oidc-authentication). Required for single sign-on. + #[cfg_attr(feature = "config-schema", schemars(with = "Option", url))] pub oidc_issuer_url: Option, - /// The client ID assigned to `SQLPage` when registering with the OIDC provider. - /// Defaults to `sqlpage`. + + /// Client ID assigned by the OIDC provider. #[serde(default = "default_oidc_client_id")] pub oidc_client_id: String, - /// The client secret for authenticating `SQLPage` to the OIDC provider. - /// Required when enabling Single Sign-On through an OIDC provider. + + /// Client secret required to authenticate with the OIDC provider. Keep this value private. pub oidc_client_secret: Option, - /// Space-separated list of [scopes](https://openid.net/specs/openid-connect-core-1_0.html#ScopeClaims) to request during OIDC authentication. - /// Defaults to "openid email profile" + + /// Space-separated [scopes](https://openid.net/specs/openid-connect-core-1_0.html#ScopeClaims) to request during login. #[serde(default = "default_oidc_scopes")] pub oidc_scopes: String, - /// Defines a list of path prefixes that should be protected by OIDC authentication. - /// By default, all paths are protected. - /// If you specify a list of prefixes, only requests whose path starts with one of the prefixes will require authentication. - /// For example, if you set this to `["/private"]`, then requests to `/private/some_page.sql` will require authentication, - /// but requests to `/index.sql` will not. - /// NOTE: `OIDC_PUBLIC_PATHS` takes precedence over `OIDC_PROTECTED_PATHS`. - /// For example, if you have `["/private"]` on the `protected_paths` like before, but also `["/private/public"]` on the `public_paths`, then `/private` requires authentication, but `/private/public` requires not authentication. - /// You cannot make a path inside a public path private again. So expanding the previous example, if you now add `/private/public/private_again`, then this path will still be accessible. + /// Path prefixes that require OIDC authentication, relative to `site_prefix`. + /// For example, use `["/admin", "/users/settings"]` to require login for both prefixes. + /// All prefixes must begin with `/`. The server normalizes decoded dot segments and repeated separators + /// and recognizes ASCII case aliases on case-insensitive storage. Public prefixes take precedence. + /// Use a space-separated list for environment variables. #[serde(default = "default_oidc_protected_paths")] pub oidc_protected_paths: Vec, - /// Defines path prefixes to exclude from OIDC authentication. - /// By default, no paths are excluded. - /// Paths matching these prefixes will not require authentication. - /// For example, if set to `["/public"]`, requests to `/public/some_page.sql` will not require authentication, - /// but requests to `/index.sql` will still require it. - /// To make `/protected/public.sql` public while protecting its containing directory, - /// set `oidc_public_paths` to `["/protected/public.sql"]` and `oidc_protected_paths` to `["/protected"]`. - /// Be aware that any path starting with `/protected/public.sql` (e.g., `/protected/public.sql.backup`) will also become public. + /// Path prefixes accessible without OIDC authentication, relative to `site_prefix`. + /// All prefixes must begin with `/`. They override protected prefixes, including nested protected prefixes. A trailing slash limits a directory match: + /// `/public/` matches its contents while `/public` also matches `/publicity`. + /// Use a space-separated list for environment variables. #[serde(default)] pub oidc_public_paths: Vec, - /// Additional trusted audiences for OIDC JWT tokens, beyond the client ID. - /// By default (when None), all additional audiences are trusted for compatibility - /// with providers that include multiple audience values (like ZITADEL, Azure AD, etc.). - /// Set to an empty list to only allow the client ID as audience. - /// Set to a specific list to only allow those specific additional audiences. + /// JWT audiences accepted in addition to the client ID. Omitting the setting accepts all additional audiences. + /// Set `[]` to accept only the client ID, or list specific additional audiences. + /// Use a space-separated list for environment variables. #[serde(default)] pub oidc_additional_trusted_audiences: Option>, - /// A domain name to use for the HTTPS server. If this is set, the server will perform all the necessary - /// steps to set up an HTTPS server automatically. All you need to do is point your domain name to the - /// server's IP address. - /// - /// It will listen on port 443 for HTTPS connections, - /// and will automatically request a certificate from Let's Encrypt - /// using the ACME protocol (requesting a TLS-ALPN-01 challenge). + /// Public domain for automatic Let's Encrypt certificates. Point its DNS record to this server. + /// HTTPS always listens on port 443. A different port in `listen_on` or `port` also serves plain HTTP. pub https_domain: Option, - /// The hostname where your application is publicly accessible (e.g., "myapp.example.com"). - /// This is used for OIDC redirect URLs. If not set, `https_domain` will be used instead. + /// Public hostname for OIDC redirect URLs, for example `myapp.example.com`. + /// Wildcard and loopback listeners use `localhost` and the listener port when deriving this value. + #[cfg_attr(feature = "config-schema", schemars(extend("x-default-description" = "Uses `https_domain` or the listener address.")))] pub host: Option, - /// The email address to use when requesting a certificate from Let's Encrypt. - /// Defaults to `contact@`. + /// Contact email for Let's Encrypt certificate requests. + #[cfg_attr(feature = "config-schema", schemars(extend("x-default-description" = "`contact@`")))] pub https_certificate_email: Option, - /// The directory to store the Let's Encrypt certificate in. Defaults to `./sqlpage/https`. + /// Writable directory for caching HTTPS certificates. The relative default is resolved against the working directory. #[serde(default = "default_https_certificate_cache_dir")] + #[cfg_attr( + feature = "config-schema", + schemars(default = "schema::certificate_cache_directory") + )] pub https_certificate_cache_dir: PathBuf, - /// URL to the ACME directory. Defaults to the Let's Encrypt production directory. + /// ACME directory URL used to request HTTPS certificates. #[serde(default = "default_https_acme_directory_url")] pub https_acme_directory_url: String, - /// Whether we should run in development or production mode. Used to determine - /// whether to show error messages to the user. + /// Development or production mode. Production hides detailed errors from users and caches files between requests. #[serde(default)] pub environment: DevOrProd, - /// Serve the website from a sub path. For example, if you set this to `/sqlpage/`, the website will be - /// served from `https://yourdomain.com/sqlpage/`. Defaults to `/`. - /// This is useful if you want to serve the website on the same domain as other content, and - /// you are using a reverse proxy to route requests to the correct server. + /// Base path for all URLs. Set `/sqlpage/` to serve the site at `https://example.com/sqlpage/`. #[serde( deserialize_with = "deserialize_site_prefix", default = "default_site_prefix" )] pub site_prefix: String, - /// Maximum number of messages that can be stored in memory before sending them to the client. - /// This prevents a single request from using up all available memory. + /// Maximum number of rendered rows queued while waiting for a slow client. Must be greater than zero. #[serde(default = "default_max_pending_rows")] pub max_pending_rows: usize, - /// Whether to compress the http response body when the client supports it. - /// Enabling response compression hinders the ability of `SQLPage` to stream every single byte - /// of data as soon as it is produced. - /// As a rule of thub, enable response compression when your app is fast. + /// Compress HTTP responses when the client supports compression. This saves bandwidth but can buffer streamed output. #[serde(default = "default_compress_responses")] pub compress_responses: bool, - /// Content-Security-Policy header to send to the client. - /// If not set, a default policy allowing - /// - scripts from the same origin, - /// - script elements with the `nonce="{{@csp_nonce}}"` attribute, + /// Content-Security-Policy header for HTML responses. An empty string disables it. + /// A custom policy can use `'nonce-{NONCE}'` to include a fresh nonce for each request. #[serde(default)] + #[cfg_attr(feature = "config-schema", schemars(with = "String", extend( + "default" = crate::webserver::content_security_policy::DEFAULT_CONTENT_SECURITY_POLICY + )))] pub content_security_policy: ContentSecurityPolicyTemplate, - /// Whether `sqlpage.fetch` should load trusted certificates from the operating system's certificate store - /// By default, it loads Mozilla's root certificates that are embedded in the `SQLPage` binary, or the ones pointed to by the - /// `SSL_CERT_FILE` and `SSL_CERT_DIR` environment variables. + /// Load trusted HTTPS certificates for `sqlpage.fetch` from the operating system's certificate store. + /// When the system store is enabled, `SSL_CERT_FILE` and `SSL_CERT_DIR` select certificate sources. + /// Disabling this setting uses the embedded Mozilla roots. #[serde(default = "default_system_root_ca_certificates")] + #[cfg_attr(feature = "config-schema", schemars(default, extend( + "x-default-description" = "True when `SSL_CERT_FILE` or `SSL_CERT_DIR` is nonempty, otherwise false." + )))] pub system_root_ca_certificates: bool, - /// Maximum depth of recursion allowed in the `run_sql` function. + /// Maximum recursion depth for `sqlpage.run_sql`. Valid values range from 0 to 255. #[serde(default = "default_max_recursion_depth")] pub max_recursion_depth: u8, + /// Allow raw HTML in Markdown. Enable only when all Markdown content is trusted. #[serde(default = "default_markdown_allow_dangerous_html")] pub markdown_allow_dangerous_html: bool, + /// Allow dangerous protocols such as `javascript:` in Markdown links. Enable only when all Markdown content is trusted. #[serde(default = "default_markdown_allow_dangerous_protocol")] pub markdown_allow_dangerous_protocol: bool, + /// Time in milliseconds to cache a file before checking the filesystem for changes. + #[cfg_attr(feature = "config-schema", schemars(extend("x-default-description" = format!( + "{} in production, {} in development.", + DevOrProd::Production.default_cache_stale_duration_ms(), DevOrProd::Development.default_cache_stale_duration_ms() + ))))] pub cache_stale_duration_ms: Option, } @@ -418,18 +459,14 @@ impl AppConfig { #[must_use] pub fn cache_stale_duration_ms(&self) -> u64 { self.cache_stale_duration_ms - .unwrap_or_else(|| if self.environment.is_prod() { 1000 } else { 0 }) + .unwrap_or_else(|| self.environment.default_cache_stale_duration_ms()) } #[must_use] pub fn listen_on(&self) -> SocketAddr { - let mut addr = self.listen_on.unwrap_or_else(|| { - if self.https_domain.is_some() { - SocketAddr::from(([0, 0, 0, 0], 443)) - } else { - SocketAddr::from(([0, 0, 0, 0], 8080)) - } - }); + let mut addr = self + .listen_on + .unwrap_or_else(|| default_listen_on(self.https_domain.is_some())); if let Some(port) = self.port { addr.set_port(port); } @@ -437,6 +474,10 @@ impl AppConfig { } } +fn default_listen_on(https: bool) -> SocketAddr { + SocketAddr::from(([0, 0, 0, 0], if https { 443 } else { 8080 })) +} + impl RoutingConfig for AppConfig { fn prefix(&self) -> &str { &self.site_prefix @@ -457,6 +498,10 @@ fn configuration_directory() -> PathBuf { } } } + default_configuration_directory() +} + +fn default_configuration_directory() -> PathBuf { PathBuf::from("./sqlpage") } @@ -506,17 +551,19 @@ fn env_config() -> config::Environment { .with_list_parse_key("oidc_additional_trusted_audiences") } +#[derive(Deserialize)] +#[cfg_attr(feature = "config-schema", derive(schemars::JsonSchema))] +#[serde(untagged)] +enum PortOrUrl { + Port(u16), + Url(String), +} + fn deserialize_port<'de, D>(deserializer: D) -> Result, D::Error> where D: Deserializer<'de>, { // deserializes both 8080 and "tcp://1.1.1.1:9090" - #[derive(Deserialize)] - #[serde(untagged)] - enum PortOrUrl { - Port(u16), - Url(String), - } let port_or_url: Option = Deserialize::deserialize(deserializer)?; match port_or_url { Some(PortOrUrl::Port(p)) => Ok(Some(p)), @@ -712,7 +759,7 @@ fn default_max_email_attachment_size() -> usize { } fn default_https_certificate_cache_dir() -> PathBuf { - default_web_root().join("sqlpage").join("https") + default_web_root().join(CERTIFICATE_CACHE_DIRECTORY) } fn default_https_acme_directory_url() -> String { @@ -758,6 +805,7 @@ fn default_oidc_protected_paths() -> Vec { } #[derive(Debug, Deserialize, Serialize, PartialEq, Clone, Copy, Eq, Default)] +#[cfg_attr(feature = "config-schema", derive(schemars::JsonSchema))] #[serde(rename_all = "lowercase")] pub enum DevOrProd { #[default] @@ -766,6 +814,7 @@ pub enum DevOrProd { } #[derive(Debug, Deserialize, PartialEq, Clone, Copy, Eq, Default)] +#[cfg_attr(feature = "config-schema", derive(Serialize, schemars::JsonSchema))] #[serde(rename_all = "lowercase")] pub enum SmtpTlsMode { None, @@ -783,6 +832,10 @@ impl SmtpTlsMode { } } impl DevOrProd { + fn default_cache_stale_duration_ms(self) -> u64 { + if self.is_prod() { 1000 } else { 0 } + } + pub(crate) fn is_prod(self) -> bool { self == DevOrProd::Production } diff --git a/src/app_config/schema.rs b/src/app_config/schema.rs new file mode 100644 index 000000000..6fb55611b --- /dev/null +++ b/src/app_config/schema.rs @@ -0,0 +1,47 @@ +use super::{CERTIFICATE_CACHE_DIRECTORY, Duration}; +use crate::webserver::database::default_max_connections; +use schemars::Schema; +use serde_json::Value; +use sqlx::any::AnyKind; + +pub(super) fn working_directory() -> &'static str { + "." +} + +pub(super) fn certificate_cache_directory() -> &'static str { + CERTIFICATE_CACHE_DIRECTORY +} + +pub(super) fn timeout(duration: Duration) -> String { + format!( + "Disabled for SQLite, {} seconds for other databases.", + duration.as_secs() + ) +} + +pub(super) fn pool_sizes() -> String { + [ + ("PostgreSQL", AnyKind::Postgres, false), + ("MySQL", AnyKind::MySql, false), + ("SQLite on disk", AnyKind::Sqlite, false), + ("SQLite in memory", AnyKind::Sqlite, true), + ("MSSQL", AnyKind::Mssql, false), + ("ODBC", AnyKind::Odbc, false), + ] + .map(|(label, kind, memory)| format!("{label} {}", default_max_connections(kind, memory))) + .join(", ") +} + +/// JSON Schema defaults represent a single value supplied when the property is omitted. +/// Conditional defaults have a human-readable description, and optional settings can be unset. +pub(super) fn remove_unset_defaults(schema: &mut Schema) { + if let Some(properties) = schema.get_mut("properties").and_then(Value::as_object_mut) { + for field in properties.values_mut().filter_map(Value::as_object_mut) { + if field.contains_key("x-default-description") + || field.get("default") == Some(&Value::Null) + { + field.remove("default"); + } + } + } +} diff --git a/src/webserver/database/connect.rs b/src/webserver/database/connect.rs index 3c0e42030..ca9d5d3fa 100644 --- a/src/webserver/database/connect.rs +++ b/src/webserver/database/connect.rs @@ -104,20 +104,17 @@ where } fn max_connections(config: &AppConfig, kind: AnyKind) -> u32 { - if let Some(max) = config.max_database_pool_connections { - return max; - } - // Different databases have a different number of max concurrent connections allowed by default + config + .max_database_pool_connections + .unwrap_or_else(|| default_max_connections(kind, config.database_url.contains(":memory:"))) +} + +pub(crate) fn default_max_connections(kind: AnyKind, in_memory: bool) -> u32 { match kind { AnyKind::Postgres | AnyKind::Odbc => 50, // Default to PostgreSQL-like limits for Generic AnyKind::MySql => 75, - AnyKind::Sqlite => { - if config.database_url.contains(":memory:") { - 128 - } else { - 16 - } - } + AnyKind::Sqlite if in_memory => 128, + AnyKind::Sqlite => 16, AnyKind::Mssql => 100, } } diff --git a/src/webserver/database/mod.rs b/src/webserver/database/mod.rs index b8c2d6153..23a1b0be3 100644 --- a/src/webserver/database/mod.rs +++ b/src/webserver/database/mod.rs @@ -10,6 +10,8 @@ mod sqlpage_functions; mod error_highlighting; mod sql_to_json; +#[cfg(feature = "config-schema")] +pub(crate) use connect::default_max_connections; pub use sql::SqlFile; use sqlx::any::AnyKind; // SupportedDatabase is defined in this module diff --git a/tests/configuration_docs/mod.rs b/tests/configuration_docs/mod.rs index 244b07e6e..ff6c6187e 100644 --- a/tests/configuration_docs/mod.rs +++ b/tests/configuration_docs/mod.rs @@ -1,32 +1,71 @@ +#![cfg(feature = "config-schema")] + +use schemars::schema_for; use serde::Deserialize; use serde::de::value::Error as DeError; use serde::de::{Deserializer, Visitor}; +use serde_json::json; use sqlpage::app_config::AppConfig; use std::collections::BTreeSet; #[test] -fn configuration_md_documents_every_option() { - let documented = documented_option_names(); - let implemented = app_config_option_names(); - - let undocumented: Vec<_> = implemented.difference(&documented).collect(); - let unimplemented: Vec<_> = documented.difference(&implemented).collect(); - - assert!( - undocumented.is_empty() && unimplemented.is_empty(), - "configuration.md and AppConfig disagree.\n\ - Missing from configuration.md: {undocumented:?}\n\ - Documented but not in AppConfig: {unimplemented:?}" +fn every_public_setting_has_a_description() { + let schema = schema_for!(AppConfig); + let properties = schema.get("properties").unwrap().as_object().unwrap(); + assert_eq!( + properties.keys().cloned().collect::>(), + app_config_option_names() ); + for (name, property) in properties { + assert!( + property["description"] + .as_str() + .is_some_and(|text| !text.trim().is_empty()), + "{name} needs a Rust doc comment" + ); + } } -fn documented_option_names() -> BTreeSet { - let table = std::fs::read_to_string("configuration.md").unwrap(); - table - .lines() - .filter_map(|line| line.strip_prefix("| `")?.split('`').next()) - .map(str::to_owned) - .collect() +#[test] +fn schema_documents_input_types_and_effective_defaults() { + let schema = schema_for!(AppConfig); + let properties = schema.get("properties").unwrap(); + let timeout = &properties["database_connection_idle_timeout_seconds"]; + assert_eq!(timeout["type"], json!(["number", "null"])); + assert!( + timeout["x-default-description"] + .as_str() + .unwrap() + .contains("SQLite") + ); + assert!(timeout.get("default").is_none()); + assert_eq!(properties["site_prefix"]["default"], "/"); + assert_eq!(properties["smtp_tls_mode"]["default"], "starttls"); + assert_eq!(properties["web_root"]["default"], "."); + assert_eq!( + properties["configuration_directory"]["default"], + "./sqlpage" + ); + assert_eq!(properties["content_security_policy"]["type"], "string"); + assert!( + properties["content_security_policy"]["default"] + .as_str() + .unwrap() + .contains("{NONCE}") + ); + assert!( + properties["system_root_ca_certificates"] + .get("default") + .is_none() + ); + assert!(properties["database_url"].get("default").is_none()); + assert_eq!(properties["oidc_public_paths"]["default"], json!([])); + assert!( + properties["oidc_additional_trusted_audiences"] + .get("default") + .is_none() + ); + assert!(schema.get("required").is_none()); } fn app_config_option_names() -> BTreeSet { diff --git a/tests/js/site_configuration.spec.ts b/tests/js/site_configuration.spec.ts new file mode 100644 index 000000000..37cb1abe3 --- /dev/null +++ b/tests/js/site_configuration.spec.ts @@ -0,0 +1,50 @@ +import assert from "node:assert/strict"; +import { DatabaseSync } from "node:sqlite"; +import test from "node:test"; +import { buildConfigurationMigration } from "../../scripts/site-configuration.mjs"; + +test("the configuration migration keeps types, defaults, and per-setting search links", (t) => { + const db = new DatabaseSync(":memory:"); + t.after(() => db.close()); + db.exec(`CREATE VIRTUAL TABLE documentation_fts USING fts5( + title, description, example_source, + page UNINDEXED, parameters UNINDEXED, fragment UNINDEXED + );`); + const schema = { + properties: { + toggle: { type: "boolean", default: false, description: "Turn this on." }, + recipient: { + type: ["string", "null"], + description: "Sender's recipient.", + }, + count: { + type: "integer", + minimum: 0, + maximum: 8, + "x-default-description": "Depends on the database.", + description: "Limit.", + }, + }, + }; + db.exec(buildConfigurationMigration(schema)); + + assert.deepEqual( + db + .prepare("SELECT name, type, default_md FROM config_option ORDER BY name") + .all() + .map((row) => [row.name, row.type, row.default_md]), + [ + ["count", "integer (0 to 8)", "Depends on the database."], + ["recipient", "string or null", null], + ["toggle", "boolean", "`false`"], + ], + ); + assert.equal( + db + .prepare( + "SELECT description FROM documentation_fts WHERE documentation_fts MATCH 'recipient' AND page = '/configuration' AND fragment = 'recipient'", + ) + .get()?.description, + "Sender's recipient.", + ); +}); diff --git a/tests/js/tsconfig.json b/tests/js/tsconfig.json index 752910d94..f9b84cfc8 100644 --- a/tests/js/tsconfig.json +++ b/tests/js/tsconfig.json @@ -2,6 +2,7 @@ "extends": "../../tsconfig.json", "compilerOptions": { "lib": ["es2022"], + "allowJs": true, "module": "nodenext", "moduleResolution": "nodenext", "types": ["node"]