summaryrefslogtreecommitdiffstats
path: root/nixos/modules/services/search/meilisearch.nix
blob: b1a32a47fa238df00e78e7e83bf1d94bae5fe51d (plain)
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
{
  config,
  lib,
  pkgs,
  ...
}:
let
  cfg = config.services.meilisearch;

  settingsFormat = pkgs.formats.toml { };

  # These secrets are used in the config file and can be set to paths.
  secrets-with-path =
    map
      (
        { environment, name }:
        {
          inherit name environment;
          setting = cfg.settings.${name};
        }
      )
      [
        {
          environment = "MEILI_SSL_CERT_PATH";
          name = "ssl_cert_path";
        }
        {
          environment = "MEILI_SSL_KEY_PATH";
          name = "ssl_key_path";
        }
        {
          environment = "MEILI_SSL_AUTH_PATH";
          name = "ssl_auth_path";
        }
        {
          environment = "MEILI_SSL_OCSP_PATH";
          name = "ssl_ocsp_path";
        }
      ];

  # We also handle `master_key` separately.
  # It cannot be set to a path, so we template it.
  master-key-placeholder = "@MASTER_KEY@";

  configFile = settingsFormat.generate "config.toml" (
    removeAttrs (
      if cfg.masterKeyFile != null then
        cfg.settings // { master_key = master-key-placeholder; }
      else
        removeAttrs cfg.settings [ "master_key" ]
    ) (map (secret: secret.name) secrets-with-path)
  );

in
{
  meta.maintainers = with lib.maintainers; [
    happysalada
  ];
  meta.doc = ./meilisearch.md;

  imports = [
    (lib.mkRenamedOptionModule
      [ "services" "meilisearch" "environment" ]
      [ "services" "meilisearch" "settings" "env" ]
    )
    (lib.mkRenamedOptionModule
      [ "services" "meilisearch" "logLevel" ]
      [ "services" "meilisearch" "settings" "log_level" ]
    )
    (lib.mkRenamedOptionModule
      [ "services" "meilisearch" "noAnalytics" ]
      [ "services" "meilisearch" "settings" "no_analytics" ]
    )
    (lib.mkRenamedOptionModule
      [ "services" "meilisearch" "maxIndexSize" ]
      [ "services" "meilisearch" "settings" "max_index_size" ]
    )
    (lib.mkRenamedOptionModule
      [ "services" "meilisearch" "payloadSizeLimit" ]
      [ "services" "meilisearch" "settings" "http_payload_size_limit" ]
    )
    (lib.mkRenamedOptionModule
      [ "services" "meilisearch" "dumplessUpgrade" ]
      [ "services" "meilisearch" "settings" "experimental_dumpless_upgrade" ]
    )
    (lib.mkRemovedOptionModule [ "services" "meilisearch" "masterKeyEnvironmentFile" ] ''
      Use `services.meilisearch.masterKeyFile` instead. It does not require you to prefix the file with "MEILI_MASTER_KEY=".
      If you were abusing this option to set other options, you can now configure them with `services.meilisearch.settings`.
    '')
  ];

  options.services.meilisearch = {
    enable = lib.mkEnableOption "Meilisearch - a RESTful search API";

    package = lib.mkPackageOption pkgs "meilisearch" {
      extraDescription = ''
        Use this if you require specific features to be enabled. The default package has no features.
      '';
    };

    listenAddress = lib.mkOption {
      default = "localhost";
      type = lib.types.str;
      description = ''
        The IP address that Meilisearch will listen on.

        It can also be a hostname like "localhost". If it resolves to an IPv4 and IPv6 address, Meilisearch will listen on both.
      '';
    };

    listenPort = lib.mkOption {
      default = 7700;
      type = lib.types.port;
      description = ''
        The port that Meilisearch will listen on.
      '';
    };

    masterKeyFile = lib.mkOption {
      description = ''
        Path to file which contains the master key.
        By doing so, all routes will be protected and will require a key to be accessed.
        If no master key is provided, all routes can be accessed without requiring any key.

        You can generate a master key by running `openssl rand -base64 36`.
        Alternatively, you can start Meilisearch without a master key and use the pre-generated key from the service's logs that can be obtained by `journalctl -u meilisearch | grep -- --master-key`.
      '';
      default = null;
      type = lib.types.nullOr lib.types.path;
    };

    settings = lib.mkOption {
      description = ''
        Configuration settings for Meilisearch.
        Look at the documentation for available options:
        https://github.com/meilisearch/meilisearch/blob/main/config.toml
        https://www.meilisearch.com/docs/learn/self_hosted/configure_meilisearch_at_launch#all-instance-options
      '';

      default = { };

      type = lib.types.submodule {
        freeformType = settingsFormat.type;

        imports = map (secret: {
          # give them proper types, just so they're easier to consume from this file
          options.${secret.name} = lib.mkOption {
            # but they should not show up in documentation as special in any way.
            visible = false;

            type = lib.types.nullOr lib.types.path;
            default = null;
          };
        }) secrets-with-path;
      };
    };
  };

  config = lib.mkIf cfg.enable {
    assertions = [
      {
        assertion = !cfg.settings ? master_key;
        message = ''
          Do not set `services.meilisearch.settings.master_key` in your configuration.
          Use `services.meilisearch.masterKeyFile` instead.
        '';
      }
    ];

    services.meilisearch.settings = {
      # we use `listenAddress` and `listenPort` to derive the `http_addr` setting.
      # this is the only setting we treat like this.
      # we do this because some dependent services like Misskey/Sharkey need separate host,port for no good reason.
      http_addr = "${cfg.listenAddress}:${toString cfg.listenPort}";

      # upstream's default for `db_path` is `/var/lib/meilisearch/data.ms/`, but ours is different for no reason.
      db_path = lib.mkDefault "/var/lib/meilisearch";
      # these are equivalent to the upstream defaults, because we set a working directory.
      # they are only set here for consistency with `db_path`.
      dump_dir = lib.mkDefault "/var/lib/meilisearch/dumps";
      snapshot_dir = lib.mkDefault "/var/lib/meilisearch/snapshots";

      # this is intentionally different from upstream's default.
      no_analytics = lib.mkDefault true;

      # allow updating without manual intervention
      upgrade_db = lib.mkDefault true;
    };

    # used to restore dumps
    environment.systemPackages = [ cfg.package ];

    systemd.services.meilisearch = {
      description = "Meilisearch daemon";
      wantedBy = [ "multi-user.target" ];
      after = [ "network.target" ];

      environment = builtins.listToAttrs (
        map (secret: {
          name = secret.environment;
          value = lib.mkIf (secret.setting != null) "%d/${secret.name}";
        }) secrets-with-path
      );

      serviceConfig = {
        Type = "simple";
        DynamicUser = true;
        Restart = "always";
        LoadCredential = lib.mkMerge (
          [
            (lib.mkIf (cfg.masterKeyFile != null) [ "master_key:${cfg.masterKeyFile}" ])
          ]
          ++ map (
            secret: lib.mkIf (secret.setting != null) [ "${secret.name}:${secret.setting}" ]
          ) secrets-with-path
        );
        ExecStartPre = [
          "${lib.getExe' pkgs.coreutils "install"} -m 700 '${configFile}' \"\${RUNTIME_DIRECTORY}/config.toml\""
        ]
        ++ lib.optionals (cfg.masterKeyFile != null) [
          "${lib.getExe pkgs.replace-secret} '${master-key-placeholder}' \"\${CREDENTIALS_DIRECTORY}/master_key\" \"\${RUNTIME_DIRECTORY}/config.toml\""
        ];
        ExecStart = "${lib.getExe cfg.package} --config-file-path \${RUNTIME_DIRECTORY}/config.toml";
        StateDirectory = "meilisearch";
        WorkingDirectory = "%S/meilisearch";
        RuntimeDirectory = "meilisearch";
        RuntimeDirectoryMode = "0700";
        ReadWritePaths = [
          cfg.settings.db_path
          cfg.settings.dump_dir
          cfg.settings.snapshot_dir
        ];

        ProtectSystem = "strict";
        ProtectHome = true;
        ProtectClock = true;
        ProtectHostname = true;
        ProtectKernelLogs = true;
        ProtectKernelModules = true;
        ProtectKernelTunables = true;
        ProtectControlGroups = true;
        PrivateTmp = true;
        PrivateMounts = true;
        PrivateUsers = true;
        PrivateDevices = true;
        RestrictRealtime = true;
        RestrictNamespaces = true;
        RestrictSUIDSGID = true;
        LockPersonality = true;
        MemoryDenyWriteExecute = true;
        RemoveIPC = true;

        # Meilisearch needs to determine cgroup memory limits to set its own memory limits.
        # This means this can't be set to "pid"
        ProcSubset = "all";
        ProtectProc = "invisible";

        NoNewPrivileges = true;

        # Meilisearch does not support listening on AF_UNIX sockets,
        # so we currently restrict it to only AF_INET and AF_INET6.
        RestrictAddressFamilies = [
          "AF_INET"
          "AF_INET6"
        ];

        CapabilityBoundingSet = "";
        SystemCallArchitectures = "native";
        SystemCallFilter = [
          "@system-service"
          "~@privileged @resources"
        ];

        UMask = "0077";
      };
    };
  };
}