summary refs log tree commit diff
path: root/nixos/modules/services/matrix/mjolnir.nix
blob: 278924b05cf289134360bc528a5945c73a4e8b2b (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
{ config, lib, pkgs, ... }:

with lib;
let
  cfg = config.services.mjolnir;

  yamlConfig = {
    inherit (cfg) dataPath managementRoom protectedRooms;

    accessToken = "@ACCESS_TOKEN@"; # will be replaced in "generateConfig"
    homeserverUrl =
      if cfg.pantalaimon.enable then
        "http://${cfg.pantalaimon.options.listenAddress}:${toString cfg.pantalaimon.options.listenPort}"
      else
        cfg.homeserverUrl;

    rawHomeserverUrl = cfg.homeserverUrl;

    pantalaimon = {
      inherit (cfg.pantalaimon) username;

      use = cfg.pantalaimon.enable;
      password = "@PANTALAIMON_PASSWORD@"; # will be replaced in "generateConfig"
    };
  };

  moduleConfigFile = pkgs.writeText "module-config.yaml" (
    generators.toYAML { } (filterAttrs (_: v: v != null)
      (fold recursiveUpdate { } [ yamlConfig cfg.settings ])));

  # these config files will be merged one after the other to build the final config
  configFiles = [
    "${pkgs.mjolnir}/share/mjolnir/config/default.yaml"
    moduleConfigFile
  ];

  # this will generate the default.yaml file with all configFiles as inputs and
  # replace all secret strings using replace-secret
  generateConfig = pkgs.writeShellScript "mjolnir-generate-config" (
    let
      yqEvalStr = concatImapStringsSep " * " (pos: _: "select(fileIndex == ${toString (pos - 1)})") configFiles;
      yqEvalArgs = concatStringsSep " " configFiles;
    in
    ''
      set -euo pipefail

      umask 077

      # mjolnir will try to load a config from "./config/default.yaml" in the working directory
      # -> let's place the generated config there
      mkdir -p ${cfg.dataPath}/config

      # merge all config files into one, overriding settings of the previous one with the next config
      # e.g. "eval-all 'select(fileIndex == 0) * select(fileIndex == 1)' filea.yaml fileb.yaml" will merge filea.yaml with fileb.yaml
      ${pkgs.yq-go}/bin/yq eval-all -P '${yqEvalStr}' ${yqEvalArgs} > ${cfg.dataPath}/config/default.yaml

      ${optionalString (cfg.accessTokenFile != null) ''
        ${pkgs.replace-secret}/bin/replace-secret '@ACCESS_TOKEN@' '${cfg.accessTokenFile}' ${cfg.dataPath}/config/default.yaml
      ''}
      ${optionalString (cfg.pantalaimon.passwordFile != null) ''
        ${pkgs.replace-secret}/bin/replace-secret '@PANTALAIMON_PASSWORD@' '${cfg.pantalaimon.passwordFile}' ${cfg.dataPath}/config/default.yaml
      ''}
    ''
  );
in
{
  options.services.mjolnir = {
    enable = mkEnableOption "Mjolnir, a moderation tool for Matrix";

    homeserverUrl = mkOption {
      type = types.str;
      default = "https://matrix.org";
      description = ''
        Where the homeserver is located (client-server URL).

        If <literal>pantalaimon.enable</literal> is <literal>true</literal>, this option will become the homeserver to which <literal>pantalaimon</literal> connects.
        The listen address of <literal>pantalaimon</literal> will then become the <literal>homeserverUrl</literal> of <literal>mjolnir</literal>.
      '';
    };

    accessTokenFile = mkOption {
      type = with types; nullOr path;
      default = null;
      description = ''
        File containing the matrix access token for the <literal>mjolnir</literal> user.
      '';
    };

    pantalaimon = mkOption {
      description = ''
        <literal>pantalaimon</literal> options (enables E2E Encryption support).

        This will create a <literal>pantalaimon</literal> instance with the name "mjolnir".
      '';
      default = { };
      type = types.submodule {
        options = {
          enable = mkEnableOption ''
            If true, accessToken is ignored and the username/password below will be
            used instead. The access token of the bot will be stored in the dataPath.
          '';

          username = mkOption {
            type = types.str;
            description = "The username to login with.";
          };

          passwordFile = mkOption {
            type = with types; nullOr path;
            default = null;
            description = ''
              File containing the matrix password for the <literal>mjolnir</literal> user.
            '';
          };

          options = mkOption {
            type = types.submodule (import ./pantalaimon-options.nix);
            default = { };
            description = ''
              passthrough additional options to the <literal>pantalaimon</literal> service.
            '';
          };
        };
      };
    };

    dataPath = mkOption {
      type = types.path;
      default = "/var/lib/mjolnir";
      description = ''
        The directory the bot should store various bits of information in.
      '';
    };

    managementRoom = mkOption {
      type = types.str;
      default = "#moderators:example.org";
      description = ''
        The room ID where people can use the bot. The bot has no access controls, so
        anyone in this room can use the bot - secure your room!
        This should be a room alias or room ID - not a matrix.to URL.
        Note: <literal>mjolnir</literal> is fairly verbose - expect a lot of messages from it.
      '';
    };

    protectedRooms = mkOption {
      type = types.listOf types.str;
      default = [ ];
      example = literalExpression ''
        [
          "https://matrix.to/#/#yourroom:example.org"
          "https://matrix.to/#/#anotherroom:example.org"
        ]
      '';
      description = ''
        A list of rooms to protect (matrix.to URLs).
      '';
    };

    settings = mkOption {
      default = { };
      type = (pkgs.formats.yaml { }).type;
      example = literalExpression ''
        {
          autojoinOnlyIfManager = true;
          automaticallyRedactForReasons = [ "spam" "advertising" ];
        }
      '';
      description = ''
        Additional settings (see <link xlink:href="https://github.com/matrix-org/mjolnir/blob/main/config/default.yaml">mjolnir default config</link> for available settings). These settings will override settings made by the module config.
      '';
    };
  };

  config = mkIf config.services.mjolnir.enable {
    assertions = [
      {
        assertion = !(cfg.pantalaimon.enable && cfg.pantalaimon.passwordFile == null);
        message = "Specify pantalaimon.passwordFile";
      }
      {
        assertion = !(cfg.pantalaimon.enable && cfg.accessTokenFile != null);
        message = "Do not specify accessTokenFile when using pantalaimon";
      }
      {
        assertion = !(!cfg.pantalaimon.enable && cfg.accessTokenFile == null);
        message = "Specify accessTokenFile when not using pantalaimon";
      }
    ];

    services.pantalaimon-headless.instances."mjolnir" = mkIf cfg.pantalaimon.enable
      {
        homeserver = cfg.homeserverUrl;
      } // cfg.pantalaimon.options;

    systemd.services.mjolnir = {
      description = "mjolnir - a moderation tool for Matrix";
      wants = [ "network-online.target" ] ++ optionals (cfg.pantalaimon.enable) [ "pantalaimon-mjolnir.service" ];
      after = [ "network-online.target" ] ++ optionals (cfg.pantalaimon.enable) [ "pantalaimon-mjolnir.service" ];
      wantedBy = [ "multi-user.target" ];

      serviceConfig = {
        ExecStart = ''${pkgs.mjolnir}/bin/mjolnir'';
        ExecStartPre = [ generateConfig ];
        WorkingDirectory = cfg.dataPath;
        StateDirectory = "mjolnir";
        StateDirectoryMode = "0700";
        ProtectSystem = "strict";
        ProtectHome = true;
        PrivateTmp = true;
        NoNewPrivileges = true;
        PrivateDevices = true;
        User = "mjolnir";
        Restart = "on-failure";

        /* TODO: wait for #102397 to be resolved. Then load secrets from $CREDENTIALS_DIRECTORY+"/NAME"
        DynamicUser = true;
        LoadCredential = [] ++
          optionals (cfg.accessTokenFile != null) [
            "access_token:${cfg.accessTokenFile}"
          ] ++
          optionals (cfg.pantalaimon.passwordFile != null) [
            "pantalaimon_password:${cfg.pantalaimon.passwordFile}"
          ];
        */
      };
    };

    users = {
      users.mjolnir = {
        group = "mjolnir";
        isSystemUser = true;
      };
      groups.mjolnir = { };
    };
  };

  meta = {
    doc = ./mjolnir.xml;
    maintainers = with maintainers; [ jojosch ];
  };
}