nixpkgs/nixos/modules/services/development/zammad.nix
Maximilian Bosch 48459567ae 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-13 17:16:25 +01:00

324 lines
9.5 KiB
Nix

{ config, lib, pkgs, ... }:
with lib;
let
cfg = config.services.zammad;
settingsFormat = pkgs.formats.yaml { };
filterNull = filterAttrs (_: v: v != null);
serviceConfig = {
Type = "simple";
Restart = "always";
User = "zammad";
Group = "zammad";
PrivateTmp = true;
StateDirectory = "zammad";
WorkingDirectory = cfg.dataDir;
};
environment = {
RAILS_ENV = "production";
NODE_ENV = "production";
RAILS_SERVE_STATIC_FILES = "true";
RAILS_LOG_TO_STDOUT = "true";
};
databaseConfig = settingsFormat.generate "database.yml" cfg.database.settings;
in
{
options = {
services.zammad = {
enable = mkEnableOption (lib.mdDoc "Zammad, a web-based, open source user support/ticketing solution");
package = mkOption {
type = types.package;
default = pkgs.zammad;
defaultText = literalExpression "pkgs.zammad";
description = lib.mdDoc "Zammad package to use.";
};
dataDir = mkOption {
type = types.path;
default = "/var/lib/zammad";
description = lib.mdDoc ''
Path to a folder that will contain Zammad working directory.
'';
};
host = mkOption {
type = types.str;
default = "127.0.0.1";
example = "192.168.23.42";
description = lib.mdDoc "Host address.";
};
openPorts = mkOption {
type = types.bool;
default = false;
description = lib.mdDoc "Whether to open firewall ports for Zammad";
};
port = mkOption {
type = types.port;
default = 3000;
description = lib.mdDoc "Web service port.";
};
websocketPort = mkOption {
type = types.port;
default = 6042;
description = lib.mdDoc "Websocket service port.";
};
database = {
type = mkOption {
type = types.enum [ "PostgreSQL" "MySQL" ];
default = "PostgreSQL";
example = "MySQL";
description = lib.mdDoc "Database engine to use.";
};
host = mkOption {
type = types.nullOr types.str;
default = {
PostgreSQL = "/run/postgresql";
MySQL = "localhost";
}.${cfg.database.type};
defaultText = literalExpression ''
{
PostgreSQL = "/run/postgresql";
MySQL = "localhost";
}.''${config.services.zammad.database.type};
'';
description = lib.mdDoc ''
Database host address.
'';
};
port = mkOption {
type = types.nullOr types.port;
default = null;
description = lib.mdDoc "Database port. Use `null` for default port.";
};
name = mkOption {
type = types.str;
default = "zammad";
description = lib.mdDoc ''
Database name.
'';
};
user = mkOption {
type = types.nullOr types.str;
default = "zammad";
description = lib.mdDoc "Database user.";
};
passwordFile = mkOption {
type = types.nullOr types.path;
default = null;
example = "/run/keys/zammad-dbpassword";
description = lib.mdDoc ''
A file containing the password for {option}`services.zammad.database.user`.
'';
};
createLocally = mkOption {
type = types.bool;
default = true;
description = lib.mdDoc "Whether to create a local database automatically.";
};
settings = mkOption {
type = settingsFormat.type;
default = { };
example = literalExpression ''
{
}
'';
description = lib.mdDoc ''
The {file}`database.yml` configuration file as key value set.
See \<TODO\>
for list of configuration parameters.
'';
};
};
secretKeyBaseFile = mkOption {
type = types.nullOr types.path;
default = null;
example = "/run/keys/secret_key_base";
description = lib.mdDoc ''
The path to a file containing the
`secret_key_base` secret.
Zammad uses `secret_key_base` to encrypt
the cookie store, which contains session data, and to digest
user auth tokens.
Needs to be a 64 byte long string of hexadecimal
characters. You can generate one by running
```
openssl rand -hex 64 >/path/to/secret_key_base_file
```
This should be a string, not a nix path, since nix paths are
copied into the world-readable nix store.
'';
};
};
};
config = mkIf cfg.enable {
services.zammad.database.settings = {
production = mapAttrs (_: v: mkDefault v) (filterNull {
adapter = {
PostgreSQL = "postgresql";
MySQL = "mysql2";
}.${cfg.database.type};
database = cfg.database.name;
pool = 50;
timeout = 5000;
encoding = "utf8";
username = cfg.database.user;
host = cfg.database.host;
port = cfg.database.port;
});
};
networking.firewall.allowedTCPPorts = mkIf cfg.openPorts [
config.services.zammad.port
config.services.zammad.websocketPort
];
users.users.zammad = {
isSystemUser = true;
home = cfg.dataDir;
group = "zammad";
};
users.groups.zammad = { };
assertions = [
{
assertion = cfg.database.createLocally -> cfg.database.user == "zammad" && cfg.database.name == "zammad";
message = "services.zammad.database.user must be set to \"zammad\" if services.zammad.database.createLocally is set to true";
}
{
assertion = cfg.database.createLocally -> cfg.database.passwordFile == null;
message = "a password cannot be specified if services.zammad.database.createLocally is set to true";
}
];
services.mysql = optionalAttrs (cfg.database.createLocally && cfg.database.type == "MySQL") {
enable = true;
package = mkDefault pkgs.mariadb;
ensureDatabases = [ cfg.database.name ];
ensureUsers = [
{
name = cfg.database.user;
ensurePermissions = { "${cfg.database.name}.*" = "ALL PRIVILEGES"; };
}
];
};
services.postgresql = optionalAttrs (cfg.database.createLocally && cfg.database.type == "PostgreSQL") {
enable = true;
ensureDatabases = [ cfg.database.name ];
ensureUsers = [
{
name = cfg.database.user;
ensureDBOwnership = true;
}
];
};
systemd.services.zammad-web = {
inherit environment;
serviceConfig = serviceConfig // {
# loading all the gems takes time
TimeoutStartSec = 1200;
};
after = [
"network.target"
"postgresql.service"
];
requires = [
"postgresql.service"
];
description = "Zammad web";
wantedBy = [ "multi-user.target" ];
preStart = ''
# Blindly copy the whole project here.
chmod -R +w .
rm -rf ./public/assets/
rm -rf ./tmp/*
rm -rf ./log/*
cp -r --no-preserve=owner ${cfg.package}/* .
chmod -R +w .
# config file
cp ${databaseConfig} ./config/database.yml
chmod -R +w .
${optionalString (cfg.database.passwordFile != null) ''
{
echo -n " password: "
cat ${cfg.database.passwordFile}
} >> ./config/database.yml
''}
${optionalString (cfg.secretKeyBaseFile != null) ''
{
echo "production: "
echo -n " secret_key_base: "
cat ${cfg.secretKeyBaseFile}
} > ./config/secrets.yml
''}
if [ `${config.services.postgresql.package}/bin/psql \
--host ${cfg.database.host} \
${optionalString
(cfg.database.port != null)
"--port ${toString cfg.database.port}"} \
--username ${cfg.database.user} \
--dbname ${cfg.database.name} \
--command "SELECT COUNT(*) FROM pg_class c \
JOIN pg_namespace s ON s.oid = c.relnamespace \
WHERE s.nspname NOT IN ('pg_catalog', 'pg_toast', 'information_schema') \
AND s.nspname NOT LIKE 'pg_temp%';" | sed -n 3p` -eq 0 ]; then
echo "Initialize database"
./bin/rake --no-system db:migrate
./bin/rake --no-system db:seed
else
echo "Migrate database"
./bin/rake --no-system db:migrate
fi
echo "Done"
'';
script = "./script/rails server -b ${cfg.host} -p ${toString cfg.port}";
};
systemd.services.zammad-websocket = {
inherit serviceConfig environment;
after = [ "zammad-web.service" ];
requires = [ "zammad-web.service" ];
description = "Zammad websocket";
wantedBy = [ "multi-user.target" ];
script = "./script/websocket-server.rb -b ${cfg.host} -p ${toString cfg.websocketPort} start";
};
systemd.services.zammad-scheduler = {
inherit environment;
serviceConfig = serviceConfig // { Type = "forking"; };
after = [ "zammad-web.service" ];
requires = [ "zammad-web.service" ];
description = "Zammad scheduler";
wantedBy = [ "multi-user.target" ];
script = "./script/scheduler.rb start";
};
};
meta.maintainers = with lib.maintainers; [ garbas taeer ];
}