summary refs log tree commit diff
path: root/nixos/modules/services/web-apps/hedgedoc.nix
blob: 1a66f077b09d7b32a02dab3867a48d2665e79081 (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
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
{ config, lib, pkgs, ... }:

let
  inherit (lib) mkOption types mdDoc literalExpression;

  cfg = config.services.hedgedoc;

  # 21.03 will not be an official release - it was instead 21.05.  This
  # versionAtLeast statement remains set to 21.03 for backwards compatibility.
  # See https://github.com/NixOS/nixpkgs/pull/108899 and
  # https://github.com/NixOS/rfcs/blob/master/rfcs/0080-nixos-release-schedule.md.
  name = if lib.versionAtLeast config.system.stateVersion "21.03" then
    "hedgedoc"
  else
    "codimd";

  settingsFormat = pkgs.formats.json { };
in
{
  meta.maintainers = with lib.maintainers; [ SuperSandro2000 h7x4 ];

  imports = [
    (lib.mkRenamedOptionModule [ "services" "codimd" ] [ "services" "hedgedoc" ])
    (lib.mkRenamedOptionModule [ "services" "hedgedoc" "configuration" ] [ "services" "hedgedoc" "settings" ])
    (lib.mkRenamedOptionModule [ "services" "hedgedoc" "groups" ] [ "users" "users" "hedgedoc" "extraGroups" ])
    (lib.mkRemovedOptionModule [ "services" "hedgedoc" "workDir" ] ''
      This option has been removed in favor of systemd managing the state directory.

      If you have set this option without specifying `services.settings.uploadsDir`,
      please move these files to `/var/lib/hedgedoc/uploads`, or set the option to point
      at the correct location.
    '')
  ];

  options.services.hedgedoc = {
    package = lib.mkPackageOptionMD pkgs "hedgedoc" { };
    enable = lib.mkEnableOption (mdDoc "the HedgeDoc Markdown Editor");

    settings = mkOption {
      type = types.submodule {
        freeformType = settingsFormat.type;
        options = {
          domain = mkOption {
            type = with types; nullOr str;
            default = null;
            example = "hedgedoc.org";
            description = mdDoc ''
              Domain to use for website.

              This is useful if you are trying to run hedgedoc behind
              a reverse proxy.
            '';
          };
          urlPath = mkOption {
            type = with types; nullOr str;
            default = null;
            example = "hedgedoc";
            description = mdDoc ''
              URL path for the website.

              This is useful if you are hosting hedgedoc on a path like
              `www.example.com/hedgedoc`
            '';
          };
          host = mkOption {
            type = with types; nullOr str;
            default = "localhost";
            description = mdDoc ''
              Address to listen on.
            '';
          };
          port = mkOption {
            type = types.port;
            default = 3000;
            example = 80;
            description = mdDoc ''
              Port to listen on.
            '';
          };
          path = mkOption {
            type = with types; nullOr path;
            default = null;
            example = "/run/hedgedoc/hedgedoc.sock";
            description = mdDoc ''
              Path to UNIX domain socket to listen on

              ::: {.note}
                If specified, {option}`host` and {option}`port` will be ignored.
              :::
            '';
          };
          protocolUseSSL = mkOption {
            type = types.bool;
            default = false;
            example = true;
            description = mdDoc ''
              Use `https://` for all links.

              This is useful if you are trying to run hedgedoc behind
              a reverse proxy.

              ::: {.note}
                Only applied if {option}`domain` is set.
              :::
            '';
          };
          allowOrigin = mkOption {
            type = with types; listOf str;
            default = with cfg.settings; [ host ] ++ lib.optionals (domain != null) [ domain ];
            defaultText = literalExpression ''
              with config.services.hedgedoc.settings; [ host ] ++ lib.optionals (domain != null) [ domain ]
            '';
            example = [ "localhost" "hedgedoc.org" ];
            description = mdDoc ''
              List of domains to whitelist.
            '';
          };
          db = mkOption {
            type = types.attrs;
            default = {
              dialect = "sqlite";
              storage = "/var/lib/${name}/db.sqlite";
            };
            defaultText = literalExpression ''
              {
                dialect = "sqlite";
                storage = "/var/lib/hedgedoc/db.sqlite";
              }
            '';
            example = literalExpression ''
              db = {
                username = "hedgedoc";
                database = "hedgedoc";
                host = "localhost:5432";
                # or via socket
                # host = "/run/postgresql";
                dialect = "postgresql";
              };
            '';
            description = mdDoc ''
              Specify the configuration for sequelize.
              HedgeDoc supports `mysql`, `postgres`, `sqlite` and `mssql`.
              See <https://sequelize.readthedocs.io/en/v3/>
              for more information.

              ::: {.note}
                The relevant parts will be overriden if you set {option}`dbURL`.
              :::
            '';
          };
          useSSL = mkOption {
            type = types.bool;
            default = false;
            description = mdDoc ''
              Enable to use SSL server.

              ::: {.note}
                This will also enable {option}`protocolUseSSL`.

                It will also require you to set the following:

                - {option}`sslKeyPath`
                - {option}`sslCertPath`
                - {option}`sslCAPath`
                - {option}`dhParamPath`
              :::
            '';
          };
          uploadsPath = mkOption {
            type = types.path;
            default = "/var/lib/${name}/uploads";
            defaultText = "/var/lib/hedgedoc/uploads";
            description = mdDoc ''
              Directory for storing uploaded images.
            '';
          };

          # Declared because we change the default to false.
          allowGravatar = mkOption {
            type = types.bool;
            default = false;
            example = true;
            description = mdDoc ''
              Whether to enable [Libravatar](https://wiki.libravatar.org/) as
              profile picture source on your instance.

              Despite the naming of the setting, Hedgedoc replaced Gravatar
              with Libravatar in [CodiMD 1.4.0](https://hedgedoc.org/releases/1.4.0/)
            '';
          };
        };
      };

      description = mdDoc ''
        HedgeDoc configuration, see
        <https://docs.hedgedoc.org/configuration/>
        for documentation.
      '';
    };

    environmentFile = mkOption {
      type = with types; nullOr path;
      default = null;
      example = "/var/lib/hedgedoc/hedgedoc.env";
      description = mdDoc ''
        Environment file as defined in {manpage}`systemd.exec(5)`.

        Secrets may be passed to the service without adding them to the world-readable
        Nix store, by specifying placeholder variables as the option value in Nix and
        setting these variables accordingly in the environment file.

        ```
          # snippet of HedgeDoc-related config
          services.hedgedoc.settings.dbURL = "postgres://hedgedoc:\''${DB_PASSWORD}@db-host:5432/hedgedocdb";
          services.hedgedoc.settings.minio.secretKey = "$MINIO_SECRET_KEY";
        ```

        ```
          # content of the environment file
          DB_PASSWORD=verysecretdbpassword
          MINIO_SECRET_KEY=verysecretminiokey
        ```

        Note that this file needs to be available on the host on which
        `HedgeDoc` is running.
      '';
    };
  };

  config = lib.mkIf cfg.enable {
    users.groups.${name} = { };
    users.users.${name} = {
      description = "HedgeDoc service user";
      group = name;
      isSystemUser = true;
    };

    services.hedgedoc.settings = {
      defaultNotePath = lib.mkDefault "${cfg.package}/public/default.md";
      docsPath = lib.mkDefault "${cfg.package}/public/docs";
      viewPath = lib.mkDefault "${cfg.package}/public/views";
    };

    systemd.services.hedgedoc = {
      description = "HedgeDoc Service";
      documentation = [ "https://docs.hedgedoc.org/" ];
      wantedBy = [ "multi-user.target" ];
      after = [ "networking.target" ];
      preStart =
        let
          configFile = settingsFormat.generate "hedgedoc-config.json" {
            production = cfg.settings;
          };
        in
        ''
          ${pkgs.envsubst}/bin/envsubst \
            -o /run/${name}/config.json \
            -i ${configFile}
          ${pkgs.coreutils}/bin/mkdir -p ${cfg.settings.uploadsPath}
        '';
      serviceConfig = {
        User = name;
        Group = name;

        Restart = "always";
        ExecStart = "${cfg.package}/bin/hedgedoc";
        RuntimeDirectory = [ name ];
        StateDirectory = [ name ];
        WorkingDirectory = "/run/${name}";
        ReadWritePaths = [
          "-${cfg.settings.uploadsPath}"
        ] ++ lib.optionals (cfg.settings.db ? "storage") [ "-${cfg.settings.db.storage}" ];
        EnvironmentFile = lib.mkIf (cfg.environmentFile != null) [ cfg.environmentFile ];
        Environment = [
          "CMD_CONFIG_FILE=/run/${name}/config.json"
          "NODE_ENV=production"
        ];

        # Hardening
        AmbientCapabilities = "";
        CapabilityBoundingSet = "";
        LockPersonality = true;
        NoNewPrivileges = true;
        PrivateDevices = true;
        PrivateMounts = true;
        PrivateTmp = true;
        PrivateUsers = true;
        ProcSubset = "pid";
        ProtectClock = true;
        ProtectControlGroups = true;
        ProtectHome = true;
        ProtectHostname = true;
        ProtectKernelLogs = true;
        ProtectKernelModules = true;
        ProtectKernelTunables = true;
        ProtectProc = "invisible";
        ProtectSystem = "strict";
        RemoveIPC = true;
        RestrictAddressFamilies = [
          "AF_INET"
          "AF_INET6"
          # Required for connecting to database sockets,
          # and listening to unix socket at `cfg.settings.path`
          "AF_UNIX"
        ];
        RestrictNamespaces = true;
        RestrictRealtime = true;
        RestrictSUIDSGID = true;
        SocketBindAllow = lib.mkIf (cfg.settings.path == null) cfg.settings.port;
        SocketBindDeny = "any";
        SystemCallArchitectures = "native";
        SystemCallFilter = [
          "@system-service"
          "~@privileged @obsolete"
          "@pkey"
        ];
        UMask = "0007";
      };
    };
  };
}