From 3a796de04ac8d4e6941fc9c62403626c230b1078 Mon Sep 17 00:00:00 2001 From: lovasoa Date: Sun, 6 Dec 2026 16:29:34 +0100 Subject: [PATCH 1/3] Publish a searchable configuration reference --- Cargo.lock | 25 ++ Cargo.toml | 3 + configuration.md | 2 + examples/official-site/configuration.sql | 19 ++ examples/official-site/documentation.sql | 5 +- examples/official-site/llms.txt.sql | 2 +- .../official-site/reference/search-index.sql | 4 + examples/official-site/search.sql | 10 +- .../templates/docs-parameters.handlebars | 5 +- .../sqlpage/templates/shell-docs.handlebars | 2 +- examples/official-site/test.hurl | 28 ++ package.json | 4 +- scripts/official-site/configuration.rs | 95 +++++++ scripts/official-site/main.rs | 2 + src/app_config.rs | 269 +++++++++++------- src/app_config/schema.rs | 47 +++ src/webserver/database/connect.rs | 19 +- src/webserver/database/mod.rs | 2 + 18 files changed, 417 insertions(+), 126 deletions(-) create mode 100644 examples/official-site/configuration.sql create mode 100644 scripts/official-site/configuration.rs create mode 100644 src/app_config/schema.rs diff --git a/Cargo.lock b/Cargo.lock index a63558a68..5bb6b3325 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4272,10 +4272,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" @@ -4377,6 +4390,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" @@ -4693,6 +4717,7 @@ dependencies = [ "rustls", "rustls-acme", "rustls-native-certs", + "schemars 1.2.3", "serde", "serde_json", "sha2 0.11.3", diff --git a/Cargo.toml b/Cargo.toml index 1c4471428..4724e5518 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -19,6 +19,7 @@ include = [ [[example]] name = "build-site" path = "scripts/official-site/main.rs" +required-features = ["config-schema"] [lints.rust] elided_lifetimes_in_paths = "deny" @@ -65,6 +66,7 @@ futures-util = "0.3.21" tokio = { version = "1.24.1", features = ["macros", "rt", "process", "sync"] } tokio-stream = "0.1.9" anyhow = "1" +schemars = { version = "1", optional = true } serde = "1" serde_json = { version = "1.0.82", features = [ "preserve_order", @@ -140,6 +142,7 @@ opentelemetry-semantic-conventions = { version = "0.33", features = ["semconv_ex [features] +config-schema = ["dep:schemars"] default = [] odbc-static = ["odbc-sys", "odbc-sys/vendored-unix-odbc"] lambda-web = [ diff --git a/configuration.md b/configuration.md index 9b4e504c8..d961fcc3f 100644 --- a/configuration.md +++ b/configuration.md @@ -53,6 +53,8 @@ Here are the available configuration options and their default values: | `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). | +See the [configuration reference](https://sql-page.com/configuration) for every server setting, 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. diff --git a/examples/official-site/configuration.sql b/examples/official-site/configuration.sql new file mode 100644 index 000000000..c2d0ac906 --- /dev/null +++ b/examples/official-site/configuration.sql @@ -0,0 +1,19 @@ +select 'dynamic' as component, sqlpage.run_sql('sqlpage/docs-shell.sql', json_object( + 'title', 'Configuration | SQLPage', + 'section', 'Documentation', + 'current', 'Configuration', + 'outline', '[{"title":"Options","link":"#options"}]' +)) as properties; + +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, optionally prefixed with `SQLPAGE_`. 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', '**Default:** ' || 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..aee6919c9 100644 --- a/examples/official-site/documentation.sql +++ b/examples/official-site/documentation.sql @@ -28,7 +28,10 @@ select case kind when 'component' then 'Components' else 'Functions' end as titl (kind = 'component' and name in ('form', 'table', 'map', 'chart', 'button')) or (kind = 'function' and name in ('fetch', 'link', 'run_sql', 'variables')) ) as links -from reference_entry group by kind order by kind; +from reference_entry group by kind +union all +select 'Configuration', 'settings', '/configuration', 'Look up server settings, accepted values, and defaults.', null +order by title; 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..57c04ef7a 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): Server settings, accepted values, and defaults ## Components diff --git a/examples/official-site/reference/search-index.sql b/examples/official-site/reference/search-index.sql index 1611378bf..9c7766b12 100644 --- a/examples/official-site/reference/search-index.sql +++ b/examples/official-site/reference/search-index.sql @@ -23,3 +23,7 @@ JOIN reference_entry AS e ON e.kind = 'component' AND e.name = x.component; INSERT INTO documentation_fts(title, description, page, parameters) SELECT title, description, '/blog.sql', json_object('post', title) FROM blog_posts; + +INSERT INTO documentation_fts(title, description, page, fragment) +SELECT name || ' (SQLPAGE_' || upper(name) || ')', description_md, '/configuration', name +FROM config_option; diff --git a/examples/official-site/search.sql b/examples/official-site/search.sql index eede7173a..f74ebdf9d 100644 --- a/examples/official-site/search.sql +++ b/examples/official-site/search.sql @@ -7,6 +7,11 @@ 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) or 'sqlpage_' || name = lower($search) +limit 1; + select 'shell-docs' as component, 'Search' as section, coalesce($search || ' | ', '') || 'SQLPage documentation search' as title; @@ -17,7 +22,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..aef663e25 100644 --- a/examples/official-site/sqlpage/templates/docs-parameters.handlebars +++ b/examples/official-site/sqlpage/templates/docs-parameters.handlebars @@ -14,7 +14,10 @@ {{#if required}}Required{{/if}} -
{{{markdown description_md}}}
+
+ {{{markdown description_md}}} + {{#if default_md}}
{{{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 a4687a922..d5c51f4d6 100644 --- a/examples/official-site/sqlpage/templates/shell-docs.handlebars +++ b/examples/official-site/sqlpage/templates/shell-docs.handlebars @@ -104,7 +104,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 8e9bc41a5..3d4d71ba8 100644 --- a/examples/official-site/test.hurl +++ b/examples/official-site/test.hurl @@ -19,6 +19,34 @@ 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/search.sql?search=web_root +HTTP 302 +[Asserts] +header "Location" == "/functions.sql?function=web_root" + +GET http://localhost:8080/search.sql?search=SQLPAGE_WEB_ROOT +HTTP 302 +[Asserts] +header "Location" == "/configuration#web_root" + +GET http://localhost:8080/search.sql?search=SMTP +HTTP 200 +[Asserts] +xpath "//main//a[starts-with(@href, '/configuration#smtp_')]" count > 1 + GET http://localhost:8080/components.sql HTTP 200 [Asserts] diff --git a/package.json b/package.json index 510907eff..794bd2312 100644 --- a/package.json +++ b/package.json @@ -8,8 +8,8 @@ "typecheck": "tsc && tsc -p tests/js && tsc -p tests/end-to-end", "format": "biome format --write .", "fix": "biome check --fix --unsafe .", - "site:build": "cargo run --locked --example build-site", - "site:test": "cargo test --locked --example build-site", + "site:build": "cargo run --locked --features config-schema --example build-site", + "site:test": "cargo test --locked --features config-schema --example build-site", "site": "npm run build && npm run site:build && cd target/official-site && cargo run --locked --manifest-path ../../Cargo.toml" }, "repository": { diff --git a/scripts/official-site/configuration.rs b/scripts/official-site/configuration.rs new file mode 100644 index 000000000..504db7673 --- /dev/null +++ b/scripts/official-site/configuration.rs @@ -0,0 +1,95 @@ +use anyhow::{Context, Result}; +use schemars::generate::SchemaSettings; +use serde_json::Value; +use sqlpage::app_config::AppConfig; +use sqlx::executor::Executor; +use sqlx::query::query; +use sqlx::sqlite::SqliteConnection; + +pub(super) async fn insert(db: &mut SqliteConnection) -> Result<()> { + db.execute( + "CREATE TABLE config_option ( + name TEXT PRIMARY KEY, + type TEXT NOT NULL, + default_md TEXT, + description_md TEXT NOT NULL + ) STRICT", + ) + .await?; + let schema = SchemaSettings::draft2020_12() + .with(|settings| settings.inline_subschemas = true) + .into_generator() + .into_root_schema_for::(); + let properties = schema + .get("properties") + .and_then(Value::as_object) + .context("Missing AppConfig properties")?; + for (name, option) in properties { + let description = option["description"] + .as_str() + .filter(|text| !text.trim().is_empty()) + .with_context(|| format!("{name} needs a Rust doc comment"))?; + let kind = schema_type(option).with_context(|| format!("Documenting {name}"))?; + let default = option["x-default-description"] + .as_str() + .map(str::to_owned) + .or_else(|| { + option.get("default").map(|value| { + let value = value.to_string(); + let ticks = value.split(|c| c != '`').map(str::len).max().unwrap_or(0); + let delimiter = "`".repeat(ticks + 1); + format!("{delimiter}{value}{delimiter}") + }) + }); + query( + "INSERT INTO config_option (name, type, default_md, description_md) VALUES (?, ?, ?, ?)", + ) + .bind(name) + .bind(kind) + .bind(default) + .bind(description) + .execute(&mut *db) + .await + .with_context(|| format!("Storing configuration option {name}"))?; + } + Ok(()) +} + +fn schema_type(schema: &Value) -> Result { + if let Some(values) = schema["enum"].as_array() { + return Ok(values + .iter() + .map(Value::to_string) + .collect::>() + .join(" | ")); + } + if let Some(types) = schema["anyOf"].as_array() { + return Ok(types + .iter() + .map(schema_type) + .collect::>>()? + .join(" or ")); + } + if let Some(types) = schema["type"].as_array() { + return Ok(types + .iter() + .map(|kind| format_type(schema, kind)) + .collect::>>()? + .join(" or ")); + } + format_type(schema, &schema["type"]) +} + +fn format_type(schema: &Value, kind: &Value) -> Result { + let kind = kind.as_str().context("Missing configuration option type")?; + Ok(match kind { + "array" => format!("{}[]", schema_type(&schema["items"])?), + "integer" | "number" => match (schema.get("minimum"), schema.get("maximum")) { + (Some(min), Some(max)) => format!("{kind} ({min} to {max})"), + (Some(min), None) => format!("{kind} (≥ {min})"), + (None, Some(max)) => format!("{kind} (≤ {max})"), + (None, None) => kind.to_owned(), + }, + _ => kind.to_owned(), + }) +} diff --git a/scripts/official-site/main.rs b/scripts/official-site/main.rs index 8069eebc5..467e44edd 100644 --- a/scripts/official-site/main.rs +++ b/scripts/official-site/main.rs @@ -1,3 +1,4 @@ +mod configuration; mod parameters; use anyhow::{Context, Result, ensure}; @@ -73,6 +74,7 @@ async fn main() -> Result<()> { if let Some(names) = missing { anyhow::bail!("Missing component documentation for {names}"); } + configuration::insert(&mut tx).await?; tx.execute(read(&site.join("reference/search-index.sql"))?.as_str()) .await .context("Building the documentation search index")?; diff --git a/src/app_config.rs b/src/app_config.rs index 6e9166457..ca1b58673 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(range(min = 1), 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(range(min = 1, max = 65535), 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. + /// Public prefixes take precedence over protected prefixes. + /// 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")] + #[cfg_attr(feature = "config-schema", schemars(range(min = 1)))] 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 From e9eef8a4bf70954735cf278657dce5a484506774 Mon Sep 17 00:00:00 2001 From: lovasoa Date: Sun, 6 Dec 2026 16:34:19 +0100 Subject: [PATCH 2/3] Keep the generated reference as the settings catalog --- configuration.md | 49 +-------- scripts/official-site/configuration.rs | 3 + scripts/official-site/configuration/tests.rs | 109 +++++++++++++++++++ src/app_config.rs | 3 +- tests/configuration_docs/mod.rs | 70 ------------ tests/mod.rs | 1 - 6 files changed, 115 insertions(+), 120 deletions(-) create mode 100644 scripts/official-site/configuration/tests.rs delete mode 100644 tests/configuration_docs/mod.rs diff --git a/configuration.md b/configuration.md index d961fcc3f..53475a804 100644 --- a/configuration.md +++ b/configuration.md @@ -6,53 +6,6 @@ or a [JSON](https://en.wikipedia.org/wiki/JSON) file placed in `sqlpage/sqlpage. 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). | - See the [configuration reference](https://sql-page.com/configuration) for every server setting, its accepted values, and its default. Multiple configuration file formats are supported: @@ -60,7 +13,7 @@ you can use a [`.json5`](https://json5.org/) file, a [`.toml`](https://toml.io/) ## 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. diff --git a/scripts/official-site/configuration.rs b/scripts/official-site/configuration.rs index 504db7673..c4045880f 100644 --- a/scripts/official-site/configuration.rs +++ b/scripts/official-site/configuration.rs @@ -93,3 +93,6 @@ fn format_type(schema: &Value, kind: &Value) -> Result { _ => kind.to_owned(), }) } + +#[cfg(test)] +mod tests; diff --git a/scripts/official-site/configuration/tests.rs b/scripts/official-site/configuration/tests.rs new file mode 100644 index 000000000..b593aefd8 --- /dev/null +++ b/scripts/official-site/configuration/tests.rs @@ -0,0 +1,109 @@ +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 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" + ); + } +} + +#[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["smtp_port"]["minimum"], 1); + assert_eq!(properties["smtp_port"]["maximum"], 65535); + 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 { + let mut collector = OptionNameCollector::default(); + let _ = AppConfig::deserialize(&mut collector); + collector + .names + .iter() + .map(|name| (*name).to_owned()) + .collect() +} + +/// Serde hands the names it expects, renames included, to `deserialize_struct`. +#[derive(Default)] +struct OptionNameCollector { + names: &'static [&'static str], +} + +impl<'de> Deserializer<'de> for &mut OptionNameCollector { + type Error = DeError; + + fn deserialize_struct>( + self, + _name: &'static str, + fields: &'static [&'static str], + _visitor: V, + ) -> Result { + self.names = fields; + Err(serde::de::Error::custom("names collected")) + } + + fn deserialize_any>(self, _visitor: V) -> Result { + Err(serde::de::Error::custom("AppConfig is not a struct")) + } + + serde::forward_to_deserialize_any! { + bool i8 i16 i32 i64 u8 u16 u32 u64 f32 f64 char str string bytes byte_buf + option unit unit_struct newtype_struct seq tuple tuple_struct map enum + identifier ignored_any + } +} diff --git a/src/app_config.rs b/src/app_config.rs index ca1b58673..8b548e864 100644 --- a/src/app_config.rs +++ b/src/app_config.rs @@ -355,7 +355,8 @@ pub struct AppConfig { /// Path prefixes that require OIDC authentication, relative to `site_prefix`. /// For example, use `["/admin", "/users/settings"]` to require login for both prefixes. - /// Public prefixes take precedence over protected prefixes. + /// Begin each prefix 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, diff --git a/tests/configuration_docs/mod.rs b/tests/configuration_docs/mod.rs deleted file mode 100644 index 244b07e6e..000000000 --- a/tests/configuration_docs/mod.rs +++ /dev/null @@ -1,70 +0,0 @@ -use serde::Deserialize; -use serde::de::value::Error as DeError; -use serde::de::{Deserializer, Visitor}; -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 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() -} - -fn app_config_option_names() -> BTreeSet { - let mut collector = OptionNameCollector::default(); - let _ = AppConfig::deserialize(&mut collector); - collector - .names - .iter() - .map(|name| (*name).to_owned()) - .collect() -} - -/// Serde hands the names it expects, renames included, to `deserialize_struct`. -#[derive(Default)] -struct OptionNameCollector { - names: &'static [&'static str], -} - -impl<'de> Deserializer<'de> for &mut OptionNameCollector { - type Error = DeError; - - fn deserialize_struct>( - self, - _name: &'static str, - fields: &'static [&'static str], - _visitor: V, - ) -> Result { - self.names = fields; - Err(serde::de::Error::custom("names collected")) - } - - fn deserialize_any>(self, _visitor: V) -> Result { - Err(serde::de::Error::custom("AppConfig is not a struct")) - } - - serde::forward_to_deserialize_any! { - bool i8 i16 i32 i64 u8 u16 u32 u64 f32 f64 char str string bytes byte_buf - option unit unit_struct newtype_struct seq tuple tuple_struct map enum - identifier ignored_any - } -} diff --git a/tests/mod.rs b/tests/mod.rs index eca6edb11..4fbf38b1e 100644 --- a/tests/mod.rs +++ b/tests/mod.rs @@ -1,6 +1,5 @@ mod basic; mod common; -mod configuration_docs; mod cookies; mod core; mod data_formats; From b5fc73394cd15b57c9b1beff6f5b1540cdd90366 Mon Sep 17 00:00:00 2001 From: Ophir Lojkine Date: Sun, 6 Dec 2026 18:57:29 +0000 Subject: [PATCH 3/3] Declare SQLPage configuration defaults once --- scripts/official-site/configuration/tests.rs | 4 + src/app_config.rs | 242 ++++++++----------- src/app_config/schema.rs | 10 +- 3 files changed, 100 insertions(+), 156 deletions(-) diff --git a/scripts/official-site/configuration/tests.rs b/scripts/official-site/configuration/tests.rs index b593aefd8..f57d231a0 100644 --- a/scripts/official-site/configuration/tests.rs +++ b/scripts/official-site/configuration/tests.rs @@ -46,6 +46,10 @@ fn schema_documents_input_types_and_effective_defaults() { properties["configuration_directory"]["default"], "./sqlpage" ); + assert_eq!( + properties["https_certificate_cache_dir"]["default"], + "sqlpage/https" + ); assert_eq!(properties["content_security_policy"]["type"], "string"); assert!( properties["content_security_policy"]["default"] diff --git a/src/app_config.rs b/src/app_config.rs index 8b548e864..032f99a81 100644 --- a/src/app_config.rs +++ b/src/app_config.rs @@ -19,7 +19,8 @@ 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"; +const DEFAULT_CONFIGURATION_DIRECTORY: &str = "./sqlpage"; +const DEFAULT_SITE_PREFIX: &str = "/"; #[cfg(feature = "config-schema")] mod schema; @@ -208,21 +209,26 @@ pub fn load_from_env() -> anyhow::Result { /// 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))] +#[serde(default = "AppConfig::runtime_defaults")] +#[cfg_attr( + feature = "config-schema", + derive(schemars::JsonSchema), + schemars( + default = "AppConfig::portable_defaults", + 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!( + #[cfg_attr(feature = "config-schema", schemars(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, /// 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. @@ -231,7 +237,6 @@ pub struct AppConfig { /// 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" )] @@ -242,7 +247,6 @@ pub struct AppConfig { /// 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" )] @@ -252,11 +256,10 @@ pub struct AppConfig { 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")] + #[serde(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) @@ -265,7 +268,7 @@ pub struct AppConfig { 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")] + #[serde(deserialize_with = "deserialize_port")] #[cfg_attr(feature = "config-schema", schemars(with = "Option", extend("x-default-description" = "The port in `listen_on`.")))] pub port: Option, @@ -273,36 +276,23 @@ pub struct AppConfig { pub unix_socket: Option, /// 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 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, /// 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, /// 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, /// 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 hostname or IP address used by `sqlpage.send_mail`. Required when configuring a port, credentials, or sender. @@ -327,15 +317,12 @@ pub struct AppConfig { /// 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 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 in bytes of submitted forms and uploaded files. - #[serde(default = "default_max_file_size")] pub max_uploaded_file_size: usize, /// 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. @@ -343,14 +330,12 @@ pub struct AppConfig { pub oidc_issuer_url: Option, /// Client ID assigned by the OIDC provider. - #[serde(default = "default_oidc_client_id")] pub oidc_client_id: String, /// Client secret required to authenticate with the OIDC provider. Keep this value private. pub oidc_client_secret: Option, /// 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, /// Path prefixes that require OIDC authentication, relative to `site_prefix`. @@ -358,20 +343,17 @@ pub struct AppConfig { /// Begin each prefix 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, /// 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, /// 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>, /// Public domain for automatic Let's Encrypt certificates. Point its DNS record to this server. @@ -388,40 +370,27 @@ pub struct AppConfig { pub https_certificate_email: Option, /// 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, /// ACME directory URL used to request HTTPS certificates. - #[serde(default = "default_https_acme_directory_url")] pub https_acme_directory_url: String, /// Development or production mode. Production hides detailed errors from users and caches files between requests. - #[serde(default)] pub environment: DevOrProd, /// 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" - )] + #[serde(deserialize_with = "deserialize_site_prefix")] pub site_prefix: String, /// Maximum number of rendered rows queued while waiting for a slow client. Must be greater than zero. - #[serde(default = "default_max_pending_rows")] #[cfg_attr(feature = "config-schema", schemars(range(min = 1)))] pub max_pending_rows: usize, /// 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 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 )))] @@ -430,22 +399,18 @@ pub struct AppConfig { /// 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( + #[cfg_attr(feature = "config-schema", schemars(extend( "x-default-description" = "True when `SSL_CERT_FILE` or `SSL_CERT_DIR` is nonempty, otherwise false." )))] pub system_root_ca_certificates: bool, /// 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. @@ -457,6 +422,76 @@ pub struct AppConfig { } impl AppConfig { + /// Defaults shared by deserialization and the generated configuration reference. + fn portable_defaults() -> Self { + Self { + // from_cli chooses the default database after resolving the configuration directory. + database_url: String::new(), + database_password: None, + max_database_pool_connections: None, + database_connection_idle_timeout: None, + database_connection_max_lifetime: None, + sqlite_extensions: Vec::new(), + listen_on: None, + port: None, + unix_socket: None, + database_connection_retries: 6, + database_connection_acquire_timeout_seconds: 10.0, + web_root: PathBuf::from("."), + configuration_directory: PathBuf::from(DEFAULT_CONFIGURATION_DIRECTORY), + allow_exec: false, + smtp_host: None, + smtp_port: None, + smtp_username: None, + smtp_password: None, + smtp_from: None, + smtp_tls_mode: SmtpTlsMode::default(), + max_email_attachment_size: 10 * 1024 * 1024, + max_uploaded_file_size: 5 * 1024 * 1024, + oidc_issuer_url: None, + oidc_client_id: "sqlpage".to_owned(), + oidc_client_secret: None, + oidc_scopes: "openid email profile".to_owned(), + oidc_protected_paths: vec!["/".to_owned()], + oidc_public_paths: Vec::new(), + oidc_additional_trusted_audiences: None, + https_domain: None, + host: None, + https_certificate_email: None, + https_certificate_cache_dir: PathBuf::from("sqlpage/https"), + https_acme_directory_url: "https://acme-v02.api.letsencrypt.org/directory".to_owned(), + environment: DevOrProd::default(), + site_prefix: DEFAULT_SITE_PREFIX.to_owned(), + max_pending_rows: 256, + compress_responses: false, + content_security_policy: ContentSecurityPolicyTemplate::default(), + system_root_ca_certificates: false, + max_recursion_depth: 10, + markdown_allow_dangerous_html: false, + markdown_allow_dangerous_protocol: false, + cache_stale_duration_ms: None, + } + } + + fn runtime_defaults() -> Self { + let defaults = Self::portable_defaults(); + let working_directory = std::env::current_dir().unwrap_or_else(|e| { + log::error!("Unable to get current directory: {e}"); + defaults.web_root.clone() + }); + Self { + #[cfg(test)] + database_url: "sqlite://:memory:?cache=shared".to_owned(), + configuration_directory: configuration_directory(), + https_certificate_cache_dir: working_directory + .join(&defaults.https_certificate_cache_dir), + web_root: working_directory, + system_root_ca_certificates: + crate::webserver::http_client::default_system_root_ca_certificates_from_env(), + ..defaults + } + } + #[must_use] pub fn cache_stale_duration_ms(&self) -> u64 { self.cache_stale_duration_ms @@ -499,11 +534,7 @@ fn configuration_directory() -> PathBuf { } } } - default_configuration_directory() -} - -fn default_configuration_directory() -> PathBuf { - PathBuf::from("./sqlpage") + PathBuf::from(DEFAULT_CONFIGURATION_DIRECTORY) } fn cannonicalize_if_possible(path: &Path) -> PathBuf { @@ -618,7 +649,7 @@ fn normalize_site_prefix(prefix: &str) -> String { let prefix = prefix.trim_start_matches('/').trim_end_matches('/'); if prefix.is_empty() { - return default_site_prefix(); + return DEFAULT_SITE_PREFIX.to_owned(); } let encoded_prefix = percent_encoding::percent_encode(prefix.as_bytes(), &TO_ENCODE); @@ -644,10 +675,6 @@ fn test_normalize_site_prefix() { assert_eq!(normalize_site_prefix("a b/c"), "/a%20b/c/"); } -fn default_site_prefix() -> String { - '/'.to_string() -} - fn validate_smtp_host(host: &str) -> anyhow::Result<()> { anyhow::ensure!( !host.trim().is_empty() @@ -667,17 +694,6 @@ fn parse_socket_addr(host_str: &str) -> anyhow::Result { .with_context(|| format!("Resolving host '{host_str}'")) } -#[cfg(test)] -fn default_database_url() -> String { - "sqlite://:memory:?cache=shared".to_owned() -} -#[cfg(not(test))] -fn default_database_url() -> String { - // When using a custom configuration directory, the default database URL - // will be set later in `AppConfig::from_cli`. - String::new() -} - fn create_default_database(configuration_directory: &Path) -> String { let prefix = "sqlite://".to_owned(); @@ -736,75 +752,6 @@ fn encode_uri(path: &Path) -> std::borrow::Cow<'_, str> { percent_encoding::percent_encode(path_bytes, ASCII_SET).into() } -fn default_database_connection_retries() -> u32 { - 6 -} - -fn default_database_connection_acquire_timeout_seconds() -> f64 { - 10. -} - -fn default_web_root() -> PathBuf { - std::env::current_dir().unwrap_or_else(|e| { - log::error!("Unable to get current directory: {e}"); - PathBuf::from(&std::path::Component::CurDir) - }) -} - -fn default_max_file_size() -> usize { - 5 * 1024 * 1024 -} - -fn default_max_email_attachment_size() -> usize { - 10 * 1024 * 1024 -} - -fn default_https_certificate_cache_dir() -> PathBuf { - default_web_root().join(CERTIFICATE_CACHE_DIRECTORY) -} - -fn default_https_acme_directory_url() -> String { - "https://acme-v02.api.letsencrypt.org/directory".to_string() -} - -/// If the sending queue exceeds this number of outgoing messages, an error will be thrown -/// This prevents a single request from using up all available memory -fn default_max_pending_rows() -> usize { - 256 -} - -fn default_compress_responses() -> bool { - false -} - -fn default_system_root_ca_certificates() -> bool { - crate::webserver::http_client::default_system_root_ca_certificates_from_env() -} - -fn default_max_recursion_depth() -> u8 { - 10 -} - -fn default_markdown_allow_dangerous_html() -> bool { - false -} - -fn default_markdown_allow_dangerous_protocol() -> bool { - false -} - -fn default_oidc_client_id() -> String { - "sqlpage".to_string() -} - -fn default_oidc_scopes() -> String { - "openid email profile".to_string() -} - -fn default_oidc_protected_paths() -> Vec { - vec!["/".to_string()] -} - #[derive(Debug, Deserialize, Serialize, PartialEq, Clone, Copy, Eq, Default)] #[cfg_attr(feature = "config-schema", derive(schemars::JsonSchema))] #[serde(rename_all = "lowercase")] @@ -895,11 +842,6 @@ mod test { static ENV_LOCK: Mutex<()> = Mutex::new(()); - #[test] - fn test_default_site_prefix() { - assert_eq!(default_site_prefix(), "/".to_string()); - } - #[test] fn smtp_defaults_to_starttls() { assert_eq!(tests::test_config().smtp_tls_mode, SmtpTlsMode::Starttls); @@ -1089,6 +1031,11 @@ mod test { config.web_root, env_web_dir, "Environment variable should override config file" ); + assert_eq!( + config.https_certificate_cache_dir, + env::current_dir().unwrap().join("sqlpage").join("https"), + "The certificate cache should default to a path relative to the working directory" + ); assert_eq!( config.configuration_directory, cannonicalize_if_possible(&PathBuf::from("./sqlpage")), @@ -1142,7 +1089,7 @@ mod test { assert_eq!( config.web_root, - default_web_root(), + env::current_dir().unwrap(), "Web root should default to current directory when not specified" ); assert_eq!( @@ -1150,5 +1097,6 @@ mod test { cannonicalize_if_possible(&PathBuf::from("./sqlpage")), "Configuration directory should default to ./sqlpage when not specified" ); + assert_eq!(config.site_prefix, "/"); } } diff --git a/src/app_config/schema.rs b/src/app_config/schema.rs index 6fb55611b..3afebf54e 100644 --- a/src/app_config/schema.rs +++ b/src/app_config/schema.rs @@ -1,16 +1,8 @@ -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 -} +use std::time::Duration; pub(super) fn timeout(duration: Duration) -> String { format!(