nixpkgs/nixos/modules/services/mail/listmonk.nix

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

224 lines
8.0 KiB
Nix
Raw Normal View History

2022-08-30 11:15:41 +00:00
{ config, lib, pkgs, ... }:
with lib;
let
cfg = config.services.listmonk;
tomlFormat = pkgs.formats.toml { };
cfgFile = tomlFormat.generate "listmonk.toml" cfg.settings;
# Escaping is done according to https://www.postgresql.org/docs/current/sql-syntax-lexical.html#SQL-SYNTAX-CONSTANTS
setDatabaseOption = key: value:
"UPDATE settings SET value = '${
lib.replaceStrings [ "'" ] [ "''" ] (builtins.toJSON value)
2022-08-30 11:15:41 +00:00
}' WHERE key = '${key}';";
updateDatabaseConfigSQL = pkgs.writeText "update-database-config.sql"
(concatStringsSep "\n" (mapAttrsToList setDatabaseOption
(if (cfg.database.settings != null) then
cfg.database.settings
else
{ })));
updateDatabaseConfigScript =
pkgs.writeShellScriptBin "update-database-config.sh" ''
${if cfg.database.mutableSettings then ''
if [ ! -f /var/lib/listmonk/.db_settings_initialized ]; then
${pkgs.postgresql}/bin/psql -d listmonk -f ${updateDatabaseConfigSQL} ;
touch /var/lib/listmonk/.db_settings_initialized
fi
'' else
"${pkgs.postgresql}/bin/psql -d listmonk -f ${updateDatabaseConfigSQL}"}
'';
databaseSettingsOpts = with types; {
freeformType =
oneOf [ (listOf str) (listOf (attrsOf anything)) str int bool ];
options = {
"app.notify_emails" = mkOption {
type = listOf str;
default = [ ];
description = "Administrator emails for system notifications";
2022-08-30 11:15:41 +00:00
};
"privacy.exportable" = mkOption {
type = listOf str;
default = [ "profile" "subscriptions" "campaign_views" "link_clicks" ];
description =
2022-08-30 11:15:41 +00:00
"List of fields which can be exported through an automatic export request";
};
"privacy.domain_blocklist" = mkOption {
type = listOf str;
default = [ ];
description =
2022-08-30 11:15:41 +00:00
"E-mail addresses with these domains are disallowed from subscribing.";
};
smtp = mkOption {
type = listOf (submodule {
freeformType = with types; attrsOf anything;
2022-08-30 11:15:41 +00:00
options = {
enabled = mkEnableOption "this SMTP server for listmonk";
2022-08-30 11:15:41 +00:00
host = mkOption {
type = types.str;
description = "Hostname for the SMTP server";
2022-08-30 11:15:41 +00:00
};
port = mkOption {
type = types.port;
description = "Port for the SMTP server";
2022-08-30 11:15:41 +00:00
};
max_conns = mkOption {
type = types.int;
description =
2022-08-30 11:15:41 +00:00
"Maximum number of simultaneous connections, defaults to 1";
default = 1;
};
tls_type = mkOption {
type = types.enum [ "none" "STARTTLS" "TLS" ];
description = "Type of TLS authentication with the SMTP server";
2022-08-30 11:15:41 +00:00
};
};
});
description = "List of outgoing SMTP servers";
2022-08-30 11:15:41 +00:00
};
# TODO: refine this type based on the smtp one.
"bounce.mailboxes" = mkOption {
type = listOf
(submodule { freeformType = with types; listOf (attrsOf anything); });
2022-08-30 11:15:41 +00:00
default = [ ];
description = "List of bounce mailboxes";
2022-08-30 11:15:41 +00:00
};
messengers = mkOption {
type = listOf str;
default = [ ];
description =
2022-08-30 11:15:41 +00:00
"List of messengers, see: <https://github.com/knadh/listmonk/blob/master/models/settings.go#L64-L74> for options.";
};
};
};
in {
###### interface
options = {
services.listmonk = {
enable = mkEnableOption "Listmonk, this module assumes a reverse proxy to be set";
2022-08-30 11:15:41 +00:00
database = {
createLocally = mkOption {
type = types.bool;
default = false;
description =
2022-08-30 11:15:41 +00:00
"Create the PostgreSQL database and database user locally.";
};
settings = mkOption {
default = null;
type = with types; nullOr (submodule databaseSettingsOpts);
description =
2022-08-30 11:15:41 +00:00
"Dynamic settings in the PostgreSQL database, set by a SQL script, see <https://github.com/knadh/listmonk/blob/master/schema.sql#L177-L230> for details.";
};
mutableSettings = mkOption {
type = types.bool;
default = true;
description = ''
2022-08-30 11:15:41 +00:00
Database settings will be reset to the value set in this module if this is not enabled.
Enable this if you want to persist changes you have done in the application.
'';
};
};
package = mkPackageOption pkgs "listmonk" {};
2022-08-30 11:15:41 +00:00
settings = mkOption {
type = types.submodule { freeformType = tomlFormat.type; };
description = ''
2022-08-30 11:15:41 +00:00
Static settings set in the config.toml, see <https://github.com/knadh/listmonk/blob/master/config.toml.sample> for details.
You can set secrets using the secretFile option with environment variables following <https://listmonk.app/docs/configuration/#environment-variables>.
'';
};
secretFile = mkOption {
type = types.nullOr types.str;
default = null;
description =
2022-08-30 11:15:41 +00:00
"A file containing secrets as environment variables. See <https://listmonk.app/docs/configuration/#environment-variables> for details on supported values.";
};
};
};
###### implementation
config = mkIf cfg.enable {
# Default parameters from https://github.com/knadh/listmonk/blob/master/config.toml.sample
services.listmonk.settings."app".address = mkDefault "localhost:9000";
services.listmonk.settings."db" = mkMerge [
({
max_open = mkDefault 25;
max_idle = mkDefault 25;
max_lifetime = mkDefault "300s";
})
(mkIf cfg.database.createLocally {
host = mkDefault "/run/postgresql";
port = mkDefault 5432;
user = mkDefault "listmonk";
database = mkDefault "listmonk";
})
];
services.postgresql = mkIf cfg.database.createLocally {
enable = true;
ensureUsers = [{
name = "listmonk";
nixos/postgresql: drop ensurePermissions, fix ensureUsers for postgresql15 Closes #216989 First of all, a bit of context: in PostgreSQL, newly created users don't have the CREATE privilege on the public schema of a database even with `ALL PRIVILEGES` granted via `ensurePermissions` which is how most of the DB users are currently set up "declaratively"[1]. This means e.g. a freshly deployed Nextcloud service will break early because Nextcloud itself cannot CREATE any tables in the public schema anymore. The other issue here is that `ensurePermissions` is a mere hack. It's effectively a mixture of SQL code (e.g. `DATABASE foo` is relying on how a value is substituted in a query. You'd have to parse a subset of SQL to actually know which object are permissions granted to for a user). After analyzing the existing modules I realized that in every case with a single exception[2] the UNIX system user is equal to the db user is equal to the db name and I don't see a compelling reason why people would change that in 99% of the cases. In fact, some modules would even break if you'd change that because the declarations of the system user & the db user are mixed up[3]. So I decided to go with something new which restricts the ways to use `ensure*` options rather than expanding those[4]. Effectively this means that * The DB user _must_ be equal to the DB name. * Permissions are granted via `ensureDBOwnerhip` for an attribute-set in `ensureUsers`. That way, the user is actually the owner and can perform `CREATE`. * For such a postgres user, a database must be declared in `ensureDatabases`. For anything else, a custom state management should be implemented. This can either be `initialScript`, doing it manual, outside of the module or by implementing proper state management for postgresql[5], but the current state of `ensure*` isn't even declarative, but a convergent tool which is what Nix actually claims to _not_ do. Regarding existing setups: there are effectively two options: * Leave everything as-is (assuming that system user == db user == db name): then the DB user will automatically become the DB owner and everything else stays the same. * Drop the `createDatabase = true;` declarations: nothing will change because a removal of `ensure*` statements is ignored, so it doesn't matter at all whether this option is kept after the first deploy (and later on you'd usually restore from backups anyways). The DB user isn't the owner of the DB then, but for an existing setup this is irrelevant because CREATE on the public schema isn't revoked from existing users (only not granted for new users). [1] not really declarative though because removals of these statements are simply ignored for instance: https://github.com/NixOS/nixpkgs/issues/206467 [2] `services.invidious`: I removed the `ensure*` part temporarily because it IMHO falls into the category "manage the state on your own" (see the commit message). See also https://github.com/NixOS/nixpkgs/pull/265857 [3] e.g. roundcube had `"DATABASE ${cfg.database.username}" = "ALL PRIVILEGES";` [4] As opposed to other changes that are considered a potential fix, but also add more things like collation for DBs or passwords that are _never_ touched again when changing those. [5] As suggested in e.g. https://github.com/NixOS/nixpkgs/issues/206467
2023-11-08 11:50:09 +00:00
ensureDBOwnership = true;
2022-08-30 11:15:41 +00:00
}];
ensureDatabases = [ "listmonk" ];
};
systemd.services.listmonk = {
description = "Listmonk - newsletter and mailing list manager";
after = [ "network.target" ]
++ optional cfg.database.createLocally "postgresql.service";
wantedBy = [ "multi-user.target" ];
serviceConfig = {
Type = "exec";
EnvironmentFile = mkIf (cfg.secretFile != null) [ cfg.secretFile ];
ExecStartPre = [
# StateDirectory cannot be used when DynamicUser = true is set this way.
# Indeed, it will try to create all the folders and realize one of them already exist.
# Therefore, we have to create it ourselves.
''${pkgs.coreutils}/bin/mkdir -p "''${STATE_DIRECTORY}/listmonk/uploads"''
# setup database if not already done
"${cfg.package}/bin/listmonk --config ${cfgFile} --idempotent --install --yes"
# apply db migrations (setup and migrations can not be done in one step
# with "--install --upgrade" listmonk ignores the upgrade)
"${cfg.package}/bin/listmonk --config ${cfgFile} --upgrade --yes"
2022-08-30 11:15:41 +00:00
"${updateDatabaseConfigScript}/bin/update-database-config.sh"
];
ExecStart = "${cfg.package}/bin/listmonk --config ${cfgFile}";
Restart = "on-failure";
StateDirectory = [ "listmonk" ];
User = "listmonk";
Group = "listmonk";
DynamicUser = true;
NoNewPrivileges = true;
CapabilityBoundingSet = "";
SystemCallArchitectures = "native";
SystemCallFilter = [ "@system-service" "~@privileged" ];
PrivateDevices = true;
2022-08-30 11:15:41 +00:00
ProtectControlGroups = true;
ProtectKernelTunables = true;
ProtectHome = true;
RestrictNamespaces = true;
RestrictRealtime = true;
UMask = "0027";
MemoryDenyWriteExecute = true;
LockPersonality = true;
RestrictAddressFamilies = [ "AF_INET" "AF_INET6" "AF_UNIX" ];
ProtectKernelModules = true;
PrivateUsers = true;
};
};
};
}