summaryrefslogtreecommitdiff
path: root/service.nix
blob: 9c93fe87e034ba25f4cb5fd59cea2957cad9736c (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
{ config, lib, pkgs, ... }:

let
  lex_surf = pkgs.callPackage ./default.nix {};
  cfg = config.services.lex-surf;
in
{
  options.services.lex-surf = {
    enable = lib.mkEnableOption "lex-surf";

    domain = lib.mkOption {
      type = lib.types.str;
      description = "Domain under which lex-surf will be served.";
    };

    fetchUser = lib.mkOption {
      type = lib.types.str;
      description = "User account used to run lex-fetch.";
    };

    enableACME = lib.mkOption {
      type = lib.types.bool;
      description = "Whether to generate certificates.";
      default = false;
    };

    nginx =
      let
        nginxOpts =
          (import <nixpkgs/nixos/modules/services/web-servers/nginx/vhost-options.nix> {
            inherit config lib;
          }).options;
      in
      lib.mkOption {
        type = lib.types.submodule {
          options = lib.removeAttrs nginxOpts ["serverName" "useACMEHost" "acmeRoot"];
        };
        default = {};
      };
  };

  config = lib.mkIf cfg.enable (
    let
      socketPath = "/run/lex-serve/http.sock";
      ccTLDs = lib.splitString "\n" (lib.strings.trim (builtins.readFile ./cc-tlds.txt));
      chunkList =
        n: list:
        if list == [ ] then [ ] else [ (lib.lists.take n list) ] ++ (chunkList n (lib.lists.drop n list));
      # Let's Encrypt only supports 100 domains per certificate.
      # We could also use a wildcard certificate but that requires
      # the dns-01 challenge which takes more effort to set up.
      ccChunks = chunkList 100 ccTLDs;
    in
    {
      systemd.services.lex-serve = {
        serviceConfig = {
          ExecStart = "${lex_surf}/bin/lex-serve";
          DynamicUser = true;
          RuntimeDirectory = "lex-serve";
          WorkingDirectory = lex_surf;
          LogExtraFields = "LOG_FORMAT=logfmt";
        };

        environment = {
          SOCKET_PATH = socketPath;
          DOMAIN = cfg.domain;
          LAWS_DIR = "/var/lib/lex-fetch";
        };
        wantedBy = ["multi-user.target"];
      };

      systemd.services."lex-fetch@" = {
        serviceConfig = {
          ExecStart = "${lex_surf}/bin/lex-fetch %i /var/lib/lex-fetch/%i.json";
          User = cfg.fetchUser;
          StateDirectory = "lex-fetch"; # creates /var/lib/lex-fetch
          LogExtraFields = "LOG_FORMAT=logfmt";
        };

        environment = {
          SOCKET_PATH = socketPath;
        };
      };

      systemd.timers =
        let
          countries = lib.filter (name: lib.elem name ccTLDs) (
            builtins.attrNames (builtins.readDir ./lex-fetch)
          );
        in
        builtins.listToAttrs (
          map (country: {
            name = "lex-fetch-${country}";
            value = {
              wantedBy = ["timers.target"];
              timerConfig = {
                OnCalendar = "daily";
                Unit = "lex-fetch@${country}.service";
              };
            };
          }) countries
        );

      security.acme.certs = lib.mkIf cfg.enableACME (
        builtins.listToAttrs (
          lib.imap0 (i: ccTLDs: {
            name = "batch${toString i}.${cfg.domain}";
            value =
              let
                domains = map (tld: "${tld}.${cfg.domain}") ccTLDs;
              in
              {
                domain = builtins.head domains;
                extraDomainNames = builtins.tail domains;
                group = config.services.nginx.group;
                webroot = "/var/lib/acme/acme-challenge";
              };
          }) ccChunks
        ) // {
          ${cfg.domain} = {
            group = config.services.nginx.group;
            webroot = "/var/lib/acme/acme-challenge";
          };
        }
      );

      services.nginx = {
        enable = true;

        virtualHosts =
          {
            ${cfg.domain} = lib.mkMerge [
              cfg.nginx
              {
                locations."/" = {
                  proxyPass = "http://unix:${socketPath}";
                  recommendedProxySettings = true;
                };
                locations."/assets/" = {
                  root = lex_surf;
                  tryFiles = "$uri =404";
                };
                useACMEHost = if cfg.enableACME then cfg.domain else null;
              }
            ];
          }
          // (builtins.listToAttrs (
            lib.imap0 (i: ccTLDs: {
              name = "host${toString i}.${cfg.domain}";
              value = lib.mkMerge [
                cfg.nginx
                {
                  serverName =
                    let
                      escapedDomain = builtins.replaceStrings ["."] ["\\."] cfg.domain;
                    in
                    "~^(?<cc>${lib.strings.concatStringsSep "|" ccTLDs})\\.${escapedDomain}$";
                  useACMEHost = if cfg.enableACME then "batch${toString i}.${cfg.domain}" else null;
                  locations."/" = {
                    proxyPass = "http://unix:${socketPath}";
                    recommendedProxySettings = true;
                  };
                  locations."=/laws.json" = {
                    root = "/var/lib/lex-fetch";
                    tryFiles = "/$cc.json =404";
                    extraConfig = ''
                      gzip on;
                      gzip_types *;
                    '';
                  };
                }
              ];
            }) ccChunks
          ));
      };
    }
  );
}