summary refs log tree commit diff
path: root/nixos/modules/services/web-servers/caddy/default.nix
blob: cef27e2e59f3f4ad88522f71cbd9330b981cb47e (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
{ config, lib, pkgs, ... }:

with lib;

let
  cfg = config.services.caddy;
  vhostToConfig = vhostName: vhostAttrs: ''
    ${vhostName} ${builtins.concatStringsSep " " vhostAttrs.serverAliases} {
      ${vhostAttrs.extraConfig}
    }
  '';
  configFile = pkgs.writeText "Caddyfile" (builtins.concatStringsSep "\n"
    ([ cfg.config ] ++ (mapAttrsToList vhostToConfig cfg.virtualHosts)));

  formattedConfig = pkgs.runCommand "formattedCaddyFile" { } ''
    ${cfg.package}/bin/caddy fmt ${configFile} > $out
  '';

  tlsConfig = {
    apps.tls.automation.policies = [{
      issuers = [{
        inherit (cfg) ca email;
        module = "acme";
      }];
    }];
  };

  adaptedConfig = pkgs.runCommand "caddy-config-adapted.json" { } ''
    ${cfg.package}/bin/caddy adapt \
      --config ${formattedConfig} --adapter ${cfg.adapter} > $out
  '';
  tlsJSON = pkgs.writeText "tls.json" (builtins.toJSON tlsConfig);

  # merge the TLS config options we expose with the ones originating in the Caddyfile
  configJSON =
    if cfg.ca != null then
      let tlsConfigMerge = ''
        {"apps":
          {"tls":
            {"automation":
              {"policies":
                (if .[0].apps.tls.automation.policies == .[1]?.apps.tls.automation.policies
                 then .[0].apps.tls.automation.policies
                 else (.[0].apps.tls.automation.policies + .[1]?.apps.tls.automation.policies)
                 end)
              }
            }
          }
        }'';
      in
      pkgs.runCommand "caddy-config.json" { } ''
        ${pkgs.jq}/bin/jq -s '.[0] * ${tlsConfigMerge}' ${adaptedConfig} ${tlsJSON} > $out
      ''
    else
      adaptedConfig;
in
{
  imports = [
    (mkRemovedOptionModule [ "services" "caddy" "agree" ] "this option is no longer necessary for Caddy 2")
  ];

  options.services.caddy = {
    enable = mkEnableOption "Caddy web server";

    config = mkOption {
      default = "";
      example = ''
        example.com {
          encode gzip
          log
          root /srv/http
        }
      '';
      type = types.lines;
      description = ''
        Verbatim Caddyfile to use.
        Caddy v2 supports multiple config formats via adapters (see <option>services.caddy.adapter</option>).
      '';
    };

    virtualHosts = mkOption {
      type = types.attrsOf (types.submodule (import ./vhost-options.nix {
        inherit config lib;
      }));
      default = { };
      example = literalExpression ''
        {
          "hydra.example.com" = {
            serverAliases = [ "www.hydra.example.com" ];
            extraConfig = ''''''
              encode gzip
              log
              root /srv/http
            '''''';
          };
        };
      '';
      description = "Declarative vhost config";
    };


    user = mkOption {
      default = "caddy";
      type = types.str;
      description = "User account under which caddy runs.";
    };

    group = mkOption {
      default = "caddy";
      type = types.str;
      description = "Group account under which caddy runs.";
    };

    adapter = mkOption {
      default = "caddyfile";
      example = "nginx";
      type = types.str;
      description = ''
        Name of the config adapter to use.
        See https://caddyserver.com/docs/config-adapters for the full list.
      '';
    };

    resume = mkOption {
      default = false;
      type = types.bool;
      description = ''
        Use saved config, if any (and prefer over configuration passed with <option>services.caddy.config</option>).
      '';
    };

    ca = mkOption {
      default = "https://acme-v02.api.letsencrypt.org/directory";
      example = "https://acme-staging-v02.api.letsencrypt.org/directory";
      type = types.nullOr types.str;
      description = ''
        Certificate authority ACME server. The default (Let's Encrypt
        production server) should be fine for most people. Set it to null if
        you don't want to include any authority (or if you want to write a more
        fine-graned configuration manually)
      '';
    };

    email = mkOption {
      default = "";
      type = types.str;
      description = "Email address (for Let's Encrypt certificate)";
    };

    dataDir = mkOption {
      default = "/var/lib/caddy";
      type = types.path;
      description = ''
        The data directory, for storing certificates. Before 17.09, this
        would create a .caddy directory. With 17.09 the contents of the
        .caddy directory are in the specified data directory instead.

        Caddy v2 replaced CADDYPATH with XDG directories.
        See https://caddyserver.com/docs/conventions#file-locations.
      '';
    };

    package = mkOption {
      default = pkgs.caddy;
      defaultText = literalExpression "pkgs.caddy";
      type = types.package;
      description = ''
        Caddy package to use.
      '';
    };
  };

  config = mkIf cfg.enable {
    systemd.services.caddy = {
      description = "Caddy web server";
      # upstream unit: https://github.com/caddyserver/dist/blob/master/init/caddy.service
      after = [ "network-online.target" ];
      wants = [ "network-online.target" ]; # systemd-networkd-wait-online.service
      wantedBy = [ "multi-user.target" ];
      startLimitIntervalSec = 14400;
      startLimitBurst = 10;
      serviceConfig = {
        ExecStart = "${cfg.package}/bin/caddy run ${optionalString cfg.resume "--resume"} --config ${configJSON}";
        ExecReload = "${cfg.package}/bin/caddy reload --config ${configJSON}";
        Type = "simple";
        User = cfg.user;
        Group = cfg.group;
        Restart = "on-abnormal";
        AmbientCapabilities = "cap_net_bind_service";
        CapabilityBoundingSet = "cap_net_bind_service";
        NoNewPrivileges = true;
        LimitNPROC = 512;
        LimitNOFILE = 1048576;
        PrivateTmp = true;
        PrivateDevices = true;
        ProtectHome = true;
        ProtectSystem = "full";
        ReadWriteDirectories = cfg.dataDir;
        KillMode = "mixed";
        KillSignal = "SIGQUIT";
        TimeoutStopSec = "5s";
      };
    };

    users.users = optionalAttrs (cfg.user == "caddy") {
      caddy = {
        group = cfg.group;
        uid = config.ids.uids.caddy;
        home = cfg.dataDir;
        createHome = true;
      };
    };

    users.groups = optionalAttrs (cfg.group == "caddy") {
      caddy.gid = config.ids.gids.caddy;
    };

  };
}