Wallos: Open-source, self-hostable personal subscription tracker. Visualize your recurring expenses, manage your budget, and save money.
feat(admin): let the deployment own the instance SMTP settings and the server URL
thorstenhornung11ea12e69eb3c
diff --git a/admin.php b/admin.phpindex 3ace79f..d70a2b4 100644--- a/admin.php+++ b/admin.php@@ -2,16 +2,19 @@require_once 'includes/header.php';require_once 'includes/oidc_settings.php';require_once 'includes/ssrf_helper.php';+require_once 'includes/instance_config.php';if ($isAdmin != 1) {header('Location: index.php');exit;}-// get admin settings from admin table-$stmt = $db->prepare('SELECT * FROM admin');-$result = $stmt->execute();-$settings = $result->fetchArray(SQLITE3_ASSOC);+// get admin settings from admin table, with anything the deployment owns+// applied over them+$adminConfiguration = wallos_get_effective_admin_configuration($db);+$settings = $adminConfiguration['settings'];+$instanceManagedFields = $adminConfiguration['managed_fields'];+$instanceNotes = $adminConfiguration['notes'];$oidcConfiguration = wallos_get_effective_oidc_configuration($db);$oidcSettings = $oidcConfiguration['settings'];@@ -302,38 +305,54 @@ $loginDisabledAllowed = $userCount == 1 && $settings['registrations_open'] == 0;<div class="admin-form"><div class="form-group-inline"><input type="text" name="smtpaddress" id="smtpaddress" autocomplete="off"- placeholder="<?= translate('smtp_address', $i18n) ?>" value="<?= htmlspecialchars($settings['smtp_address']) ?>" />+ placeholder="<?= translate('smtp_address', $i18n) ?>" value="<?= htmlspecialchars($settings['smtp_address']) ?>"+ <?= oidc_input_attrs('smtp_address', $instanceManagedFields) ?> /><input type="text" name="smtpport" id="smtpport" autocomplete="off"- placeholder="<?= translate('port', $i18n) ?>" class="one-third" value="<?= htmlspecialchars($settings['smtp_port']) ?>" />+ placeholder="<?= translate('port', $i18n) ?>" class="one-third" value="<?= htmlspecialchars($settings['smtp_port']) ?>"+ <?= oidc_input_attrs('smtp_port', $instanceManagedFields) ?> /></div><div class="form-group-inline"><div><input type="radio" name="encryption" id="encryptionnone" value="none"- <?= empty($settings['encryption']) || $settings['encryption'] == "none" ? "checked" : "" ?> />+ <?= empty($settings['encryption']) || $settings['encryption'] == "none" ? "checked" : "" ?>+ <?= oidc_input_attrs('encryption', $instanceManagedFields) ?> /><label for="encryptionnone"><?= translate('none', $i18n) ?></label></div><div><input type="radio" name="encryption" id="encryptiontls" value="tls"- <?= $settings['encryption'] == "tls" ? "checked" : "" ?> />+ <?= $settings['encryption'] == "tls" ? "checked" : "" ?>+ <?= oidc_input_attrs('encryption', $instanceManagedFields) ?> /><label for="encryptiontls"><?= translate('tls', $i18n) ?></label></div><div><input type="radio" name="encryption" id="encryptionssl" value="ssl"- <?= $settings['encryption'] == "ssl" ? "checked" : "" ?> />+ <?= $settings['encryption'] == "ssl" ? "checked" : "" ?>+ <?= oidc_input_attrs('encryption', $instanceManagedFields) ?> /><label for="encryptionssl"><?= translate('ssl', $i18n) ?></label></div></div><div class="form-group-inline"><input type="text" name="smtpusername" id="smtpusername" autocomplete="off"- placeholder="<?= translate('smtp_username', $i18n) ?>" value="<?= htmlspecialchars($settings['smtp_username']) ?>" />+ placeholder="<?= translate('smtp_username', $i18n) ?>" value="<?= htmlspecialchars($settings['smtp_username']) ?>"+ <?= oidc_input_attrs('smtp_username', $instanceManagedFields) ?> /></div><div class="form-group-inline">- <input type="password" name="smtppassword" id="smtppassword" autocomplete="off"- placeholder="<?= translate('smtp_password', $i18n) ?>" value="<?= htmlspecialchars($settings['smtp_password']) ?>" />+ <?php if (isset($instanceManagedFields['smtp_password'])): ?>+ <?php /* The value is never rendered when the deployment owns it: a mounted+ secret that reaches the page source has left the place it was+ mounted into. The field says it is set, and nothing more. */ ?>+ <input type="password" name="smtppassword" id="smtppassword" autocomplete="off"+ placeholder="<?= translate('smtp_password', $i18n) ?>" value=""+ <?= oidc_input_attrs('smtp_password', $instanceManagedFields) ?> />+ <?php else: ?>+ <input type="password" name="smtppassword" id="smtppassword" autocomplete="off"+ placeholder="<?= translate('smtp_password', $i18n) ?>" value="<?= htmlspecialchars($settings['smtp_password']) ?>" />+ <?php endif; ?></div><div class="form-group-inline"><input type="text" name="fromemail" id="fromemail" autocomplete="off"- placeholder="<?= translate('from_email', $i18n) ?>" value="<?= htmlspecialchars($settings['from_email']) ?>" />+ placeholder="<?= translate('from_email', $i18n) ?>" value="<?= htmlspecialchars($settings['from_email']) ?>"+ <?= oidc_input_attrs('from_email', $instanceManagedFields) ?> /></div><div class="buttons"><input type="button" class="secondary-button thin mobile-grow" value="<?= translate('test', $i18n) ?>"@@ -349,6 +368,19 @@ $loginDisabledAllowed = $userCount == 1 && $settings['registrations_open'] == 0;<i class="fa-solid fa-circle-info"></i><?= translate('smtp_usage_info', $i18n) ?></p>+ <?php if (!empty($instanceManagedFields)): ?>+ <p>+ <i class="fa-solid fa-circle-info"></i>+ Fields managed by environment variables are shown here but cannot be+ edited in the UI: <?= htmlspecialchars(implode(', ', $instanceManagedFields)) ?>.+ </p>+ <?php endif; ?>+ <?php foreach ($instanceNotes as $instanceNote): ?>+ <p>+ <i class="fa-solid fa-circle-info"></i>+ <?= htmlspecialchars($instanceNote) ?>+ </p>+ <?php endforeach; ?></div></div></section>diff --git a/endpoints/admin/savesmtpsettings.php b/endpoints/admin/savesmtpsettings.phpindex 4b01e61..2a0c8d7 100644--- a/endpoints/admin/savesmtpsettings.php+++ b/endpoints/admin/savesmtpsettings.php@@ -3,6 +3,7 @@require_once '../../includes/connect_endpoint.php';require_once '../../includes/validate_endpoint_admin.php';require_once '../../includes/ssrf_helper.php';+require_once '../../includes/instance_config.php';$postData = file_get_contents("php://input");$data = json_decode($postData, true);@@ -37,14 +38,58 @@ if ($smtpPortInt < 1 || $smtpPortInt > 65535) {}// Save settings-$stmt = $db->prepare('UPDATE admin SET smtp_address = :smtp_address, smtp_port = :smtp_port, encryption = :encryption, smtp_username = :smtp_username, smtp_password = :smtp_password, from_email = :from_email');-$stmt->bindValue(':smtp_address', $smtpAddress, SQLITE3_TEXT);-$stmt->bindValue(':smtp_port', $smtpPort, SQLITE3_TEXT);+//+// A column the environment owns is not written. The inputs for those are+// disabled in the admin page, but a disabled input still has a value a script+// can read and post, so the server decides rather than the page: an environment+// value copied into the database would outlive the variable that set it, and+// removing the variable would then silently restore a stale mail server.+$managedFields = wallos_get_effective_admin_configuration($db)['managed_fields'];$encryption = empty($data['encryption']) ? 'tls' : $data['encryption'];-$stmt->bindValue(':encryption', $encryption, SQLITE3_TEXT);-$stmt->bindValue(':smtp_username', $smtpUsername, SQLITE3_TEXT);-$stmt->bindValue(':smtp_password', $smtpPassword, SQLITE3_TEXT);-$stmt->bindValue(':from_email', $fromEmail, SQLITE3_TEXT);++$columns = [+ 'smtp_address' => $smtpAddress,+ 'smtp_port' => $smtpPort,+ 'encryption' => $encryption,+ 'smtp_username' => $smtpUsername,+ 'smtp_password' => $smtpPassword,+ 'from_email' => $fromEmail,+];++$assignments = [];+$values = [];++foreach ($columns as $column => $value) {+ if (isset($managedFields[$column])) {+ continue;+ }++ $assignments[] = $column . ' = :' . $column;+ $values[':' . $column] = $value;+}++if ($assignments === []) {+ // Every field comes from the deployment. Nothing to store, and nothing+ // went wrong.+ die(json_encode([+ "success" => true,+ "message" => translate('success', $i18n)+ ]));+}++$stmt = $db->prepare('UPDATE admin SET ' . implode(', ', $assignments));++if ($stmt === false) {+ die(json_encode([+ "success" => false,+ "message" => translate('error', $i18n)+ ]));+}++foreach ($values as $parameter => $value) {+ $stmt->bindValue($parameter, $value, SQLITE3_TEXT);+}+$result = $stmt->execute();if ($result) {diff --git a/endpoints/cronjobs/sendresetpasswordemails.php b/endpoints/cronjobs/sendresetpasswordemails.phpindex 7792d13..921c70e 100644--- a/endpoints/cronjobs/sendresetpasswordemails.php+++ b/endpoints/cronjobs/sendresetpasswordemails.php@@ -7,11 +7,11 @@ require_once 'validate.php';require_once __DIR__ . '/../../includes/connect_endpoint_crontabs.php';require 'settimezone.php';+require_once __DIR__ . '/../../includes/instance_config.php';-$query = "SELECT * FROM admin";-$stmt = $db->prepare($query);-$result = $stmt->execute();-$admin = $result->fetchArray(SQLITE3_ASSOC);+// The admin row with anything the deployment owns applied over it, so this job+// uses the same mail server the admin page shows.+$admin = wallos_get_admin_settings($db);$query = "SELECT * FROM password_resets WHERE email_sent = 0";$stmt = $db->prepare($query);diff --git a/endpoints/cronjobs/sendverificationemails.php b/endpoints/cronjobs/sendverificationemails.phpindex 841e87d..61d805c 100644--- a/endpoints/cronjobs/sendverificationemails.php+++ b/endpoints/cronjobs/sendverificationemails.php@@ -7,11 +7,11 @@ require_once 'validate.php';require_once __DIR__ . '/../../includes/connect_endpoint_crontabs.php';require 'settimezone.php';+require_once __DIR__ . '/../../includes/instance_config.php';-$query = "SELECT * FROM admin";-$stmt = $db->prepare($query);-$result = $stmt->execute();-$admin = $result->fetchArray(SQLITE3_ASSOC);+// The admin row with anything the deployment owns applied over it, so this job+// uses the same mail server the admin page shows.+$admin = wallos_get_admin_settings($db);if ($admin['require_email_verification'] == 0) {if (php_sapi_name() !== 'cli') {diff --git a/includes/instance_config.php b/includes/instance_config.phpnew file mode 100644index 0000000..ce74ee7--- /dev/null+++ b/includes/instance_config.php@@ -0,0 +1,238 @@+<?php++/*+ Instance settings the deployment can own.++ Wallos keeps its instance SMTP and its public URL in the admin table, entered+ through the admin page. That works, and it keeps working exactly as before —+ but it means the credentials of the mail server live in the database, and that+ somebody has to type them in again by hand after every fresh volume. In a+ container deployment the mail server is not a user preference; it is part of+ the deployment, like the port and the volume, and it belongs in the same place.++ The mechanism here is the one this project already uses for OIDC: read the+ variable, remember which field the environment owns, and show that field in+ the admin page without letting anybody edit it there. A secret may come from a+ file instead — OIDC_CLIENT_SECRET_FILE already does this — because a mounted+ file is how Docker and Kubernetes hand a secret to a container without putting+ it in the process environment where every `docker inspect` can read it.++ Nothing here changes an installation that sets no variable. Every value still+ comes from the admin table, and every field is still editable.+*/++/**+ * One environment variable, from wherever PHP put it.+ *+ * getenv() alone is not enough: some SAPI configurations populate $_ENV or+ * $_SERVER and not the process environment.+ *+ * @param string $name+ * @return string|null+ */+function wallos_env_value($name)+{+ $value = getenv($name);+ if ($value !== false) {+ return $value;+ }++ if (array_key_exists($name, $_ENV)) {+ return $_ENV[$name];+ }++ if (array_key_exists($name, $_SERVER)) {+ return $_SERVER[$name];+ }++ return null;+}++/**+ * @param string $name+ * @return bool+ */+function wallos_has_env_value($name)+{+ return wallos_env_value($name) !== null;+}++/**+ * A value that may be given directly or as the path to a file holding it.+ *+ * <NAME>_FILE wins over <NAME>, because an installation that has moved a secret+ * into a file has done so deliberately and a leftover environment variable must+ * not quietly take precedence over it.+ *+ * The trailing newline a file usually ends with is not part of a password, and+ * a value that is nothing but whitespace is not a configured value at all.+ *+ * @param string $name+ * @return array{value: string|null, source: string|null, note: string|null}+ */+function wallos_env_secret($name)+{+ $missing = ['value' => null, 'source' => null, 'note' => null];++ if (wallos_has_env_value($name . '_FILE')) {+ $path = trim((string) wallos_env_value($name . '_FILE'));++ if ($path === '') {+ return ['value' => null, 'source' => null, 'note' => $name . '_FILE is empty.'];+ }++ if (!is_readable($path)) {+ return ['value' => null, 'source' => null,+ 'note' => $name . '_FILE names a file that cannot be read.'];+ }++ $contents = file_get_contents($path);++ if ($contents === false) {+ return ['value' => null, 'source' => null,+ 'note' => $name . '_FILE could not be read.'];+ }++ $contents = trim($contents);++ if ($contents === '') {+ return ['value' => null, 'source' => null,+ 'note' => $name . '_FILE names an empty file.'];+ }++ return ['value' => $contents, 'source' => $name . '_FILE', 'note' => null];+ }++ if (wallos_has_env_value($name)) {+ return ['value' => (string) wallos_env_value($name), 'source' => $name, 'note' => null];+ }++ return $missing;+}++/**+ * The admin columns the environment can own, and the variable that owns each.+ *+ * @return array<string, string> column => variable name+ */+function wallos_instance_config_variables()+{+ return [+ 'smtp_address' => 'WALLOS_SMTP_HOST',+ 'smtp_port' => 'WALLOS_SMTP_PORT',+ 'encryption' => 'WALLOS_SMTP_ENCRYPTION',+ 'smtp_username' => 'WALLOS_SMTP_USERNAME',+ 'smtp_password' => 'WALLOS_SMTP_PASSWORD',+ 'from_email' => 'WALLOS_SMTP_FROM',+ 'server_url' => 'WALLOS_SERVER_URL',+ ];+}++/**+ * The columns whose value may also come from a file.+ *+ * @return string[]+ */+function wallos_instance_config_secrets()+{+ return ['smtp_password'];+}++/**+ * The admin row, with anything the environment owns applied over it.+ *+ * Returns the row unchanged when no variable is set, which is every+ * installation that has not asked for this.+ *+ * @param SQLite3 $db+ * @return array{settings: array, managed_fields: array<string, string>, notes: string[]}+ */+function wallos_get_effective_admin_configuration($db)+{+ $settings = [];+ $stmt = $db->prepare('SELECT * FROM admin');++ if ($stmt !== false) {+ $result = $stmt->execute();+ $row = $result === false ? false : $result->fetchArray(SQLITE3_ASSOC);++ if ($row !== false) {+ $settings = $row;+ }+ }++ $managedFields = [];+ $notes = [];+ $secrets = wallos_instance_config_secrets();++ foreach (wallos_instance_config_variables() as $column => $variable) {+ if (in_array($column, $secrets, true)) {+ $secret = wallos_env_secret($variable);++ if ($secret['note'] !== null) {+ $notes[] = $secret['note'];+ }++ if ($secret['value'] === null) {+ continue;+ }++ $settings[$column] = $secret['value'];+ $managedFields[$column] = $secret['source'];+ continue;+ }++ if (!wallos_has_env_value($variable)) {+ continue;+ }++ $value = trim((string) wallos_env_value($variable));++ // An empty variable is not a configuration. Treating it as one would+ // let a typo in a compose file silently switch mail off with the admin+ // page showing the field as managed and blank.+ if ($value === '') {+ $notes[] = $variable . ' is empty and was ignored.';+ continue;+ }++ if ($column === 'encryption') {+ $encryption = strtolower($value);++ if (!in_array($encryption, ['none', 'tls', 'ssl'], true)) {+ $notes[] = $variable . ' must be none, tls or ssl; the stored value was kept.';+ continue;+ }++ $value = $encryption;+ }++ if ($column === 'smtp_port') {+ $port = (int) $value;++ if ((string) $port !== $value || $port < 1 || $port > 65535) {+ $notes[] = $variable . ' must be a port number; the stored value was kept.';+ continue;+ }+ }++ $settings[$column] = $value;+ $managedFields[$column] = $variable;+ }++ return ['settings' => $settings, 'managed_fields' => $managedFields, 'notes' => $notes];+}++/**+ * The admin row every consumer should read.+ *+ * A convenience over the function above for the callers that only want the+ * values — the mail jobs, the pages that ask whether mail is configured at all.+ *+ * @param SQLite3 $db+ * @return array+ */+function wallos_get_admin_settings($db)+{+ return wallos_get_effective_admin_configuration($db)['settings'];+}diff --git a/login.php b/login.phpindex 6a47b11..c90ab60 100644--- a/login.php+++ b/login.php@@ -266,9 +266,11 @@ if (isset($_POST['username']) && isset($_POST['password'])) {$registrations = false;$resetPasswordEnabled = false;if (!$password_login_disabled) {- $adminQuery = "SELECT registrations_open, max_users, server_url, smtp_address FROM admin";- $adminResult = $db->query($adminQuery);- $adminRow = $adminResult->fetchArray(SQLITE3_ASSOC);+ // Through the instance configuration, so that a mail server the deployment+ // owns offers the password reset link. Configured and invisible would be+ // the worst of the three possible outcomes.+ require_once 'includes/instance_config.php';+ $adminRow = wallos_get_admin_settings($db);$registrationsOpen = $adminRow['registrations_open'];$maxUsers = $adminRow['max_users'];diff --git a/passwordreset.php b/passwordreset.phpindex 600c7f8..01451fe 100644--- a/passwordreset.php+++ b/passwordreset.php@@ -37,7 +37,8 @@ if (isset($_COOKIE['colorTheme'])) {$colorTheme = $_COOKIE['colorTheme'];}-$settings = $db->querySingle("SELECT * FROM admin", true);+require_once 'includes/instance_config.php';+$settings = wallos_get_admin_settings($db);if ($settings['smtp_address'] == "" || $settings['server_url'] == "") {header("Location: .");exit();diff --git a/tests/cases/instance_config_test.php b/tests/cases/instance_config_test.phpnew file mode 100644index 0000000..295bca1--- /dev/null+++ b/tests/cases/instance_config_test.php@@ -0,0 +1,340 @@+<?php+/*+ The instance SMTP and the public URL can come from the deployment.++ Wallos keeps them in the admin table, entered through the admin page, and that+ is still where they come from when nothing else says otherwise. What this adds+ is the layer above: an operator who runs this in a container can put the mail+ server in the compose file, where the port and the volume already are, and put+ the password in a mounted file instead of in the database.++ The cases below are the ones a layer like this gets wrong:++ - it must be inert. An installation that sets nothing must read exactly what+ it read before, or a feature nobody asked for has changed everybody's mail.+ - an empty variable is a typo, not a configuration. Treating it as one+ switches mail off and shows the field as managed and blank.+ - a value the environment owns must never be written back to the database,+ or removing the variable silently restores a stale mail server.+ - a secret that comes from a file must not be rendered into the page source,+ which is the whole reason it was mounted rather than passed.+*/++require_once WALLOS_ROOT . '/includes/instance_config.php';++/**+ * Runs $body with the given environment, and puts the environment back.+ *+ * @param array $variables name => value, or null to unset+ * @param callable $body+ */+function instance_config_with_env($variables, callable $body)+{+ $previous = [];++ foreach ($variables as $name => $value) {+ $previous[$name] = getenv($name);++ if ($value === null) {+ putenv($name);+ unset($_ENV[$name], $_SERVER[$name]);+ continue;+ }++ putenv($name . '=' . $value);+ $_ENV[$name] = $value;+ }++ try {+ $body();+ } finally {+ foreach ($previous as $name => $value) {+ unset($_ENV[$name], $_SERVER[$name]);++ if ($value === false) {+ putenv($name);+ continue;+ }++ putenv($name . '=' . $value);+ $_ENV[$name] = $value;+ }+ }+}++/**+ * The admin row as an installation that has configured SMTP by hand has it.+ *+ * @param SQLite3 $db+ */+function instance_config_store_smtp($db)+{+ $stmt = $db->prepare("UPDATE admin SET smtp_address = 'stored.example.com', smtp_port = '587',+ encryption = 'tls', smtp_username = 'stored-user',+ smtp_password = 'stored-password', from_email = '[email protected]',+ server_url = 'https://stored.example.com'");+ $stmt->execute();+}++wallos_test('with no variables set, the stored settings are what comes back', function () {+ // The case that matters most, because it is every installation that has not+ // asked for any of this.+ $db = wallos_test_open_database();+ instance_config_store_smtp($db);++ instance_config_with_env([+ 'WALLOS_SMTP_HOST' => null,+ 'WALLOS_SMTP_PORT' => null,+ 'WALLOS_SMTP_ENCRYPTION' => null,+ 'WALLOS_SMTP_USERNAME' => null,+ 'WALLOS_SMTP_PASSWORD' => null,+ 'WALLOS_SMTP_PASSWORD_FILE' => null,+ 'WALLOS_SMTP_FROM' => null,+ 'WALLOS_SERVER_URL' => null,+ ], function () use ($db) {+ $configuration = wallos_get_effective_admin_configuration($db);++ assert_same('stored.example.com', $configuration['settings']['smtp_address'], 'the stored host');+ assert_same('stored-password', $configuration['settings']['smtp_password'], 'the stored password');+ assert_same([], $configuration['managed_fields'], 'nothing is managed by the environment');+ assert_same([], $configuration['notes'], 'and there is nothing to report');+ });++ $db->close();+});++wallos_test('a variable replaces the stored value and says which field it owns', function () {+ $db = wallos_test_open_database();+ instance_config_store_smtp($db);++ instance_config_with_env([+ 'WALLOS_SMTP_HOST' => 'mail.example.net',+ 'WALLOS_SMTP_PORT' => '2525',+ 'WALLOS_SMTP_ENCRYPTION' => 'ssl',+ 'WALLOS_SERVER_URL' => 'https://wallos.example.net',+ ], function () use ($db) {+ $configuration = wallos_get_effective_admin_configuration($db);++ assert_same('mail.example.net', $configuration['settings']['smtp_address'], 'the host comes from the environment');+ assert_same('2525', $configuration['settings']['smtp_port'], 'and the port');+ assert_same('ssl', $configuration['settings']['encryption'], 'and the encryption');+ assert_same('https://wallos.example.net', $configuration['settings']['server_url'], 'and the public URL');++ assert_same('WALLOS_SMTP_HOST', $configuration['managed_fields']['smtp_address'] ?? null,+ 'the field names the variable that owns it');++ // Untouched fields keep coming from the database, so an installation can+ // move one value into the deployment without moving all of them.+ assert_same('stored-user', $configuration['settings']['smtp_username'], 'the username is still the stored one');+ assert_true(!isset($configuration['managed_fields']['smtp_username']), 'and is not reported as managed');+ });++ $db->close();+});++wallos_test('an empty variable is a typo rather than a configuration', function () {+ // Reading it as "the host is now nothing" would switch mail off and show+ // the field as managed and blank, which looks like the feature working.+ $db = wallos_test_open_database();+ instance_config_store_smtp($db);++ instance_config_with_env(['WALLOS_SMTP_HOST' => ' '], function () use ($db) {+ $configuration = wallos_get_effective_admin_configuration($db);++ assert_same('stored.example.com', $configuration['settings']['smtp_address'],+ 'the stored host is kept');+ assert_true(!isset($configuration['managed_fields']['smtp_address']),+ 'and the field is not claimed by the environment');+ assert_contains('WALLOS_SMTP_HOST', implode(' ', $configuration['notes']),+ 'the admin page is told the variable was ignored');+ });++ $db->close();+});++wallos_test('a value that is not one of the allowed ones is refused, not stored', function () {+ $db = wallos_test_open_database();+ instance_config_store_smtp($db);++ instance_config_with_env([+ 'WALLOS_SMTP_ENCRYPTION' => 'starttls',+ 'WALLOS_SMTP_PORT' => 'not-a-port',+ ], function () use ($db) {+ $configuration = wallos_get_effective_admin_configuration($db);++ assert_same('tls', $configuration['settings']['encryption'], 'the stored encryption is kept');+ // Cast, because smtp_port is an INTEGER column and the environment+ // hands strings: what matters is the number, not which of the two the+ // value came from.+ assert_same('587', (string) $configuration['settings']['smtp_port'], 'and the stored port');++ $notes = implode(' ', $configuration['notes']);+ assert_contains('WALLOS_SMTP_ENCRYPTION', $notes, 'the encryption value is reported');+ assert_contains('WALLOS_SMTP_PORT', $notes, 'and the port');+ });++ $db->close();+});++wallos_test('a port at the edges is accepted and one outside them is not', function () {+ $db = wallos_test_open_database();+ instance_config_store_smtp($db);++ foreach (['1' => '1', '65535' => '65535', '0' => '587', '65536' => '587', '-1' => '587', '25 ' => '25'] as $set => $expected) {+ instance_config_with_env(['WALLOS_SMTP_PORT' => $set], function () use ($db, $set, $expected) {+ $configuration = wallos_get_effective_admin_configuration($db);++ assert_same($expected, (string) $configuration['settings']['smtp_port'],+ 'WALLOS_SMTP_PORT=' . var_export($set, true) . ' resolves to ' . $expected);+ });+ }++ $db->close();+});++wallos_test('a secret can come from a mounted file', function () {+ $db = wallos_test_open_database();+ instance_config_store_smtp($db);++ $path = WALLOS_TEST_TMP . '/smtp-password-' . uniqid('', true);+ // A file written by Docker or Kubernetes ends in a newline, and the newline+ // is not part of the password.+ file_put_contents($path, "from-the-file\n");++ instance_config_with_env(['WALLOS_SMTP_PASSWORD_FILE' => $path], function () use ($db) {+ $configuration = wallos_get_effective_admin_configuration($db);++ assert_same('from-the-file', $configuration['settings']['smtp_password'],+ 'the password is the content of the file, without its newline');+ assert_contains('WALLOS_SMTP_PASSWORD_FILE',+ $configuration['managed_fields']['smtp_password'] ?? '',+ 'and the field names the file variable, not the plain one');+ });++ unlink($path);+ $db->close();+});++wallos_test('the file wins over the plain variable, and a missing file is reported', function () {+ $db = wallos_test_open_database();+ instance_config_store_smtp($db);++ $path = WALLOS_TEST_TMP . '/smtp-password-' . uniqid('', true);+ file_put_contents($path, 'from-the-file');++ instance_config_with_env([+ 'WALLOS_SMTP_PASSWORD' => 'from-the-variable',+ 'WALLOS_SMTP_PASSWORD_FILE' => $path,+ ], function () use ($db) {+ $configuration = wallos_get_effective_admin_configuration($db);++ // An installation that has moved a secret into a file did that+ // deliberately; a leftover variable must not quietly win.+ assert_same('from-the-file', $configuration['settings']['smtp_password'],+ 'the file wins over the plain variable');+ });++ unlink($path);++ instance_config_with_env([+ 'WALLOS_SMTP_PASSWORD' => 'from-the-variable',+ 'WALLOS_SMTP_PASSWORD_FILE' => $path,+ ], function () use ($db) {+ $configuration = wallos_get_effective_admin_configuration($db);++ // Falling back to the plain variable here would be worse than failing:+ // the secret was moved out of the environment on purpose.+ assert_same('stored-password', $configuration['settings']['smtp_password'],+ 'a file that is not there does not fall back to the variable');+ assert_contains('WALLOS_SMTP_PASSWORD_FILE', implode(' ', $configuration['notes']),+ 'and the admin page is told why');+ });++ $db->close();+});++wallos_test('a fresh installation that configured nothing by hand can still send mail', function () {+ // The point of the whole thing, asked as the application asks it.+ // passwordreset.php refuses to run unless smtp_address and server_url are+ // both set, and on a fresh volume the admin row has neither. An operator+ // who put them in the compose file has configured this installation, and+ // the page has to agree — otherwise the feature is configured and+ // invisible, which is worse than not configured at all.+ $db = wallos_test_open_database();++ $stored = wallos_get_admin_settings($db);+ assert_true(empty($stored['smtp_address']), 'a fresh installation has no mail server');++ instance_config_with_env([+ 'WALLOS_SMTP_HOST' => 'mail.example.net',+ 'WALLOS_SMTP_PORT' => '587',+ 'WALLOS_SMTP_USERNAME' => 'wallos',+ 'WALLOS_SMTP_PASSWORD' => 'secret',+ 'WALLOS_SMTP_ENCRYPTION' => 'tls',+ 'WALLOS_SERVER_URL' => 'https://wallos.example.net',+ ], function () use ($db) {+ $settings = wallos_get_admin_settings($db);++ // The exact condition passwordreset.php puts on the page.+ assert_true($settings['smtp_address'] != "" && $settings['server_url'] != "",+ 'the password reset page opens');++ // And the one the mail job puts on itself before building a PHPMailer.+ assert_true((bool) ($settings['smtp_address'] && $settings['smtp_port']+ && $settings['smtp_username'] && $settings['smtp_password'] && $settings['encryption']),+ 'and the mail job finds a complete configuration');+ });++ $db->close();+});++wallos_test('a value the environment owns is never written back to the database', function () {+ // The inputs are disabled in the admin page, but a disabled input still has+ // a value a script can read and post, so the endpoint has to decide. If it+ // did not, removing the variable later would silently restore a stale mail+ // server that nobody remembers configuring.+ $source = file_get_contents(WALLOS_ROOT . '/endpoints/admin/savesmtpsettings.php');++ assert_contains("wallos_get_effective_admin_configuration(\$db)['managed_fields']", $source,+ 'the save endpoint asks which fields the environment owns');+ assert_contains('if (isset($managedFields[$column])) {', $source,+ 'and skips them when building the update');+ assert_true(strpos($source, "UPDATE admin SET smtp_address = :smtp_address, smtp_port") === false,+ 'the fixed statement that wrote every column is gone');+});++wallos_test('a managed secret is not rendered into the page source', function () {+ // The reason a secret is mounted rather than passed is that it should not+ // be readable from somewhere else. Printing it into the admin page as the+ // value of an input undoes that.+ $source = file_get_contents(WALLOS_ROOT . '/admin.php');++ assert_contains("isset(\$instanceManagedFields['smtp_password'])", $source,+ 'the password field asks whether the deployment owns it');++ $managedBlock = substr($source, strpos($source, "isset(\$instanceManagedFields['smtp_password'])"), 700);+ $else = strpos($managedBlock, 'else');+ assert_true($else !== false, 'the field has both branches');++ assert_true(strpos(substr($managedBlock, 0, $else), "htmlspecialchars(\$settings['smtp_password'])") === false,+ 'the managed branch renders an empty value rather than the secret');+});++wallos_test('every reader of the instance mail settings goes through one place', function () {+ // Two readers that disagree is how "I configured it and the reset link+ // never appeared" happens: the mail job uses the environment and the login+ // page still asks the database whether mail is configured at all.+ foreach ([+ 'login.php',+ 'passwordreset.php',+ 'endpoints/cronjobs/sendresetpasswordemails.php',+ 'endpoints/cronjobs/sendverificationemails.php',+ 'admin.php',+ ] as $path) {+ $source = file_get_contents(WALLOS_ROOT . '/' . $path);++ assert_contains('instance_config.php', $source, $path . ' includes the instance configuration');+ assert_true(preg_match('/SELECT \* FROM admin|SELECT registrations_open, max_users, server_url, smtp_address FROM admin/', $source) !== 1,+ $path . ' does not read the admin row directly any more');+ }+});