about summary refs log tree commit diff
path: root/nixpkgs/nixos/modules/services/security/authelia.nix
blob: cf1c57e34c4ef8532a858c7a5f4f66b8ba255059 (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
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
{ lib
, pkgs
, config
, ...
}:

let
  cfg = config.services.authelia;

  format = pkgs.formats.yaml { };
  configFile = format.generate "config.yml" cfg.settings;

  autheliaOpts = with lib; { name, ... }: {
    options = {
      enable = mkEnableOption "Authelia instance";

      name = mkOption {
        type = types.str;
        default = name;
        description = ''
          Name is used as a suffix for the service name, user, and group.
          By default it takes the value you use for `<instance>` in:
          {option}`services.authelia.<instance>`
        '';
      };

      package = mkPackageOption pkgs "authelia" { };

      user = mkOption {
        default = "authelia-${name}";
        type = types.str;
        description = "The name of the user for this authelia instance.";
      };

      group = mkOption {
        default = "authelia-${name}";
        type = types.str;
        description = "The name of the group for this authelia instance.";
      };

      secrets = mkOption {
        description = ''
          It is recommended you keep your secrets separate from the configuration.
          It's especially important to keep the raw secrets out of your nix configuration,
          as the values will be preserved in your nix store.
          This attribute allows you to configure the location of secret files to be loaded at runtime.

          https://www.authelia.com/configuration/methods/secrets/
        '';
        default = { };
        type = types.submodule {
          options = {
            manual = mkOption {
              default = false;
              example = true;
              description = ''
                Configuring authelia's secret files via the secrets attribute set
                is intended to be convenient and help catch cases where values are required
                to run at all.
                If a user wants to set these values themselves and bypass the validation they can set this value to true.
              '';
              type = types.bool;
            };

            # required
            jwtSecretFile = mkOption {
              type = types.nullOr types.path;
              default = null;
              description = ''
                Path to your JWT secret used during identity verificaton.
              '';
            };

            oidcIssuerPrivateKeyFile = mkOption {
              type = types.nullOr types.path;
              default = null;
              description = ''
                Path to your private key file used to encrypt OIDC JWTs.
              '';
            };

            oidcHmacSecretFile = mkOption {
              type = types.nullOr types.path;
              default = null;
              description = ''
                Path to your HMAC secret used to sign OIDC JWTs.
              '';
            };

            sessionSecretFile = mkOption {
              type = types.nullOr types.path;
              default = null;
              description = ''
                Path to your session secret. Only used when redis is used as session storage.
              '';
            };

            # required
            storageEncryptionKeyFile = mkOption {
              type = types.nullOr types.path;
              default = null;
              description = ''
                Path to your storage encryption key.
              '';
            };
          };
        };
      };

      environmentVariables = mkOption {
        type = types.attrsOf types.str;
        description = ''
          Additional environment variables to provide to authelia.
          If you are providing secrets please consider the options under {option}`services.authelia.<instance>.secrets`
          or make sure you use the `_FILE` suffix.
          If you provide the raw secret rather than the location of a secret file that secret will be preserved in the nix store.
          For more details: https://www.authelia.com/configuration/methods/secrets/
        '';
        default = { };
      };

      settings = mkOption {
        description = ''
          Your Authelia config.yml as a Nix attribute set.
          There are several values that are defined and documented in nix such as `default_2fa_method`,
          but additional items can also be included.

          https://github.com/authelia/authelia/blob/master/config.template.yml
        '';
        default = { };
        example = ''
          {
            theme = "light";
            default_2fa_method = "totp";
            log.level = "debug";
            server.disable_healthcheck = true;
          }
        '';
        type = types.submodule {
          freeformType = format.type;
          options = {
            theme = mkOption {
              type = types.enum [ "light" "dark" "grey" "auto" ];
              default = "light";
              example = "dark";
              description = "The theme to display.";
            };

            default_2fa_method = mkOption {
              type = types.enum [ "" "totp" "webauthn" "mobile_push" ];
              default = "";
              example = "webauthn";
              description = ''
                Default 2FA method for new users and fallback for preferred but disabled methods.
              '';
            };

            server = {
              host = mkOption {
                type = types.str;
                default = "localhost";
                example = "0.0.0.0";
                description = "The address to listen on.";
              };

              port = mkOption {
                type = types.port;
                default = 9091;
                description = "The port to listen on.";
              };
            };

            log = {
              level = mkOption {
                type = types.enum [ "info" "debug" "trace" ];
                default = "debug";
                example = "info";
                description = "Level of verbosity for logs: info, debug, trace.";
              };

              format = mkOption {
                type = types.enum [ "json" "text" ];
                default = "json";
                example = "text";
                description = "Format the logs are written as.";
              };

              file_path = mkOption {
                type = types.nullOr types.path;
                default = null;
                example = "/var/log/authelia/authelia.log";
                description = "File path where the logs will be written. If not set logs are written to stdout.";
              };

              keep_stdout = mkOption {
                type = types.bool;
                default = false;
                example = true;
                description = "Whether to also log to stdout when a `file_path` is defined.";
              };
            };

            telemetry = {
              metrics = {
                enabled = mkOption {
                  type = types.bool;
                  default = false;
                  example = true;
                  description = "Enable Metrics.";
                };

                address = mkOption {
                  type = types.str;
                  default = "tcp://127.0.0.1:9959";
                  example = "tcp://0.0.0.0:8888";
                  description = "The address to listen on for metrics. This should be on a different port to the main `server.port` value.";
                };
              };
            };
          };
        };
      };

      settingsFiles = mkOption {
        type = types.listOf types.path;
        default = [ ];
        example = [ "/etc/authelia/config.yml" "/etc/authelia/access-control.yml" "/etc/authelia/config/" ];
        description = ''
          Here you can provide authelia with configuration files or directories.
          It is possible to give authelia multiple files and use the nix generated configuration
          file set via {option}`services.authelia.<instance>.settings`.
        '';
      };
    };
  };
in
{
  options.services.authelia.instances = with lib; mkOption {
    default = { };
    type = types.attrsOf (types.submodule autheliaOpts);
    description = ''
      Multi-domain protection currently requires multiple instances of Authelia.
      If you don't require multiple instances of Authelia you can define just the one.

      https://www.authelia.com/roadmap/active/multi-domain-protection/
    '';
    example = ''
      {
        main = {
          enable = true;
          secrets.storageEncryptionKeyFile = "/etc/authelia/storageEncryptionKeyFile";
          secrets.jwtSecretFile = "/etc/authelia/jwtSecretFile";
          settings = {
            theme = "light";
            default_2fa_method = "totp";
            log.level = "debug";
            server.disable_healthcheck = true;
          };
        };
        preprod = {
          enable = false;
          secrets.storageEncryptionKeyFile = "/mnt/pre-prod/authelia/storageEncryptionKeyFile";
          secrets.jwtSecretFile = "/mnt/pre-prod/jwtSecretFile";
          settings = {
            theme = "dark";
            default_2fa_method = "webauthn";
            server.host = "0.0.0.0";
          };
        };
        test.enable = true;
        test.secrets.manual = true;
        test.settings.theme = "grey";
        test.settings.server.disable_healthcheck = true;
        test.settingsFiles = [ "/mnt/test/authelia" "/mnt/test-authelia.conf" ];
        };
      }
    '';
  };

  config =
    let
      mkInstanceServiceConfig = instance:
        let
          execCommand = "${instance.package}/bin/authelia";
          configFile = format.generate "config.yml" instance.settings;
          configArg = "--config ${builtins.concatStringsSep "," (lib.concatLists [[configFile] instance.settingsFiles])}";
        in
        {
          description = "Authelia authentication and authorization server";
          wantedBy = [ "multi-user.target" ];
          after = [ "network.target" ];
          environment =
            (lib.filterAttrs (_: v: v != null) {
              AUTHELIA_JWT_SECRET_FILE = instance.secrets.jwtSecretFile;
              AUTHELIA_STORAGE_ENCRYPTION_KEY_FILE = instance.secrets.storageEncryptionKeyFile;
              AUTHELIA_SESSION_SECRET_FILE = instance.secrets.sessionSecretFile;
              AUTHELIA_IDENTITY_PROVIDERS_OIDC_ISSUER_PRIVATE_KEY_FILE = instance.secrets.oidcIssuerPrivateKeyFile;
              AUTHELIA_IDENTITY_PROVIDERS_OIDC_HMAC_SECRET_FILE = instance.secrets.oidcHmacSecretFile;
            })
            // instance.environmentVariables;

          preStart = "${execCommand} ${configArg} validate-config";
          serviceConfig = {
            User = instance.user;
            Group = instance.group;
            ExecStart = "${execCommand} ${configArg}";
            Restart = "always";
            RestartSec = "5s";
            StateDirectory = "authelia-${instance.name}";
            StateDirectoryMode = "0700";

            # Security options:
            AmbientCapabilities = "";
            CapabilityBoundingSet = "";
            DeviceAllow = "";
            LockPersonality = true;
            MemoryDenyWriteExecute = true;
            NoNewPrivileges = true;

            PrivateTmp = true;
            PrivateDevices = true;
            PrivateUsers = true;

            ProtectClock = true;
            ProtectControlGroups = true;
            ProtectHome = "read-only";
            ProtectHostname = true;
            ProtectKernelLogs = true;
            ProtectKernelModules = true;
            ProtectKernelTunables = true;
            ProtectProc = "noaccess";
            ProtectSystem = "strict";

            RestrictAddressFamilies = [ "AF_INET" "AF_INET6" "AF_UNIX" ];
            RestrictNamespaces = true;
            RestrictRealtime = true;
            RestrictSUIDSGID = true;

            SystemCallArchitectures = "native";
            SystemCallErrorNumber = "EPERM";
            SystemCallFilter = [
              "@system-service"
              "~@cpu-emulation"
              "~@debug"
              "~@keyring"
              "~@memlock"
              "~@obsolete"
              "~@privileged"
              "~@setuid"
            ];
          };
        };
      mkInstanceUsersConfig = instance: {
        groups."authelia-${instance.name}" =
          lib.mkIf (instance.group == "authelia-${instance.name}") {
            name = "authelia-${instance.name}";
          };
        users."authelia-${instance.name}" =
          lib.mkIf (instance.user == "authelia-${instance.name}") {
            name = "authelia-${instance.name}";
            isSystemUser = true;
            group = instance.group;
          };
      };
      instances = lib.attrValues cfg.instances;
    in
    {
      assertions = lib.flatten (lib.flip lib.mapAttrsToList cfg.instances (name: instance:
        [
          {
            assertion = instance.secrets.manual || (instance.secrets.jwtSecretFile != null && instance.secrets.storageEncryptionKeyFile != null);
            message = ''
              Authelia requires a JWT Secret and a Storage Encryption Key to work.
              Either set them like so:
              services.authelia.${name}.secrets.jwtSecretFile = /my/path/to/jwtsecret;
              services.authelia.${name}.secrets.storageEncryptionKeyFile = /my/path/to/encryptionkey;
              Or set services.authelia.${name}.secrets.manual = true and provide them yourself via
              environmentVariables or settingsFiles.
              Do not include raw secrets in nix settings.
            '';
          }
        ]
      ));

      systemd.services = lib.mkMerge
        (map
          (instance: lib.mkIf instance.enable {
            "authelia-${instance.name}" = mkInstanceServiceConfig instance;
          })
          instances);
      users = lib.mkMerge
        (map
          (instance: lib.mkIf instance.enable (mkInstanceUsersConfig instance))
          instances);
    };
}