summaryrefslogtreecommitdiffstats
path: root/nixos/modules/services/networking/cgit.nix
blob: 47ddbc2f9772e6595ae60190c8c487188d3acb47 (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
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
{
  config,
  lib,
  pkgs,
  ...
}:
let
  cfgs = config.services.cgit;

  settingType =
    with lib.types;
    oneOf [
      bool
      int
      str
    ];
  repeatedSettingType =
    with lib.types;
    oneOf [
      settingType
      (listOf settingType)
    ];

  genAttrs' = names: f: lib.listToAttrs (map f names);

  regexEscape =
    let
      # taken from https://github.com/python/cpython/blob/05cb728d68a278d11466f9a6c8258d914135c96c/Lib/re.py#L251-L266
      special = [
        "("
        ")"
        "["
        "]"
        "{"
        "}"
        "?"
        "*"
        "+"
        "-"
        "|"
        "^"
        "$"
        "\\"
        "."
        "&"
        "~"
        "#"
        " "
        "\t"
        "\n"
        "\r"
        "" # \v / 0x0B
        "" # \f / 0x0C
      ];
    in
    lib.replaceStrings special (map (c: "\\${c}") special);

  stripLocation = cfg: lib.removeSuffix "/" cfg.nginx.location;

  regexLocation = cfg: regexEscape (stripLocation cfg);

  mkFastcgiPass = name: cfg: ''
    ${
      if cfg.nginx.location == "/" then
        ''
          fastcgi_param PATH_INFO $uri;
        ''
      else
        ''
          fastcgi_split_path_info ^(${regexLocation cfg})(/.+)$;
          fastcgi_param PATH_INFO $fastcgi_path_info;
        ''
    }fastcgi_pass unix:${config.services.fcgiwrap.instances."cgit-${name}".socket.address};
  '';

  cgitrcLine =
    name: value:
    "${name}=${
      if value == true then
        "1"
      else if value == false then
        "0"
      else
        toString value
    }";

  # list value as multiple lines (for "readme" for example)
  cgitrcEntry =
    name: value: if lib.isList value then map (cgitrcLine name) value else [ (cgitrcLine name value) ];

  mkCgitrc =
    cfg:
    pkgs.writeText "cgitrc" ''
      # global settings
      ${lib.concatStringsSep "\n" (
        lib.flatten (
          lib.mapAttrsToList cgitrcEntry ({ virtual-root = cfg.nginx.location; } // cfg.settings)
        )
      )}
      ${lib.optionalString (cfg.scanPath != null) (cgitrcLine "scan-path" cfg.scanPath)}

      # repository settings
      ${lib.concatStrings (
        lib.mapAttrsToList (url: settings: ''
          ${cgitrcLine "repo.url" url}
          ${lib.concatStringsSep "\n" (lib.mapAttrsToList (name: cgitrcLine "repo.${name}") settings)}
        '') cfg.repos
      )}

      # extra config
      ${cfg.extraConfig}
    '';

  fcgiwrapUnitName = name: "fcgiwrap-cgit-${name}";
  fcgiwrapRuntimeDir = name: "/run/${fcgiwrapUnitName name}";
  gitProjectRoot =
    name: cfg: if cfg.scanPath != null then cfg.scanPath else "${fcgiwrapRuntimeDir name}/repos";

in
{
  options = {
    services.cgit = lib.mkOption {
      description = "Configure cgit instances.";
      default = { };
      type = lib.types.attrsOf (
        lib.types.submodule (
          { config, ... }:
          {
            options = {
              enable = lib.mkEnableOption "cgit";

              package = lib.mkPackageOption pkgs "cgit" { };

              nginx.virtualHost = lib.mkOption {
                description = "VirtualHost to serve cgit on, defaults to the attribute name.";
                type = lib.types.str;
                default = config._module.args.name;
                example = "git.example.com";
              };

              nginx.location = lib.mkOption {
                description = "Location to serve cgit under.";
                type = lib.types.str;
                default = "/";
                example = "/git/";
              };

              repos = lib.mkOption {
                description = "cgit repository settings, see {manpage}`cgitrc(5)`";
                type = with lib.types; attrsOf (attrsOf settingType);
                default = { };
                example = {
                  blah = {
                    path = "/var/lib/git/example";
                    desc = "An example repository";
                  };
                };
              };

              scanPath = lib.mkOption {
                description = "A path which will be scanned for repositories.";
                type = lib.types.nullOr lib.types.path;
                default = null;
                example = "/var/lib/git";
              };

              settings = lib.mkOption {
                description = "cgit configuration, see {manpage}`cgitrc(5)`";
                type = lib.types.attrsOf repeatedSettingType;
                default = { };
                example = lib.literalExpression ''
                  {
                    enable-follow-links = true;
                    source-filter = "''${pkgs.cgit}/lib/cgit/filters/syntax-highlighting.py";
                  }
                '';
              };

              extraConfig = lib.mkOption {
                description = "These lines go to the end of cgitrc verbatim.";
                type = lib.types.lines;
                default = "";
              };

              user = lib.mkOption {
                description = "User to run the cgit service as.";
                type = lib.types.str;
                default = "cgit";
              };

              group = lib.mkOption {
                description = "Group to run the cgit service as.";
                type = lib.types.str;
                default = "cgit";
              };

              gitHttpBackend.enable = lib.mkOption {
                description = ''
                  Whether to bypass cgit and use git-http-backend for HTTP clones.
                  While this enables HTTP clones to use the more efficient smart protocol,
                  it does not support access control via cgit's settings (e.g. the `ignore` repository setting).

                  If you want to disallow access to some repositories with this backend,
                  enable `checkExportOkFiles` and set `strict-export = "git-daemon-export-ok"` in `settings`.
                '';
                type = lib.types.bool;
                default = true;
              };

              gitHttpBackend.checkExportOkFiles = lib.mkOption {
                description = ''
                  Whether git-http-backend should only export repositories that contain a `git-daemon-export-ok` file.

                  When the backend is enabled and the check is disabled all repositories can be cloned
                  irrespective of cgit's settings (e.g. the `ignore` repository setting).

                  When enabled you must also configure `strict-export = "git-daemon-export-ok"`
                  in `settings` to make cgit check for the same files.
                '';
                type = lib.types.bool;
              };
            };
          }
        )
      );
    };
  };

  config = lib.mkIf (lib.any (cfg: cfg.enable) (lib.attrValues cfgs)) {
    assertions = lib.flatten (
      lib.mapAttrsToList (vhost: cfg: [
        {
          assertion = !cfg.enable || (cfg.scanPath == null) != (cfg.repos == { });
          message = "Misconfigured services.cgit.${vhost}: Exactly one of scanPath or repos must be set.";
        }
        {
          assertion =
            cfg.enable
            -> cfg.gitHttpBackend.enable
            -> cfg.gitHttpBackend.checkExportOkFiles
            -> (cfg.settings ? strict-export && cfg.settings.strict-export == "git-daemon-export-ok");
          message = "Misconfigured services.cgit.${vhost}: When gitHttpBackend.checkExportOkFiles is true then settings.strict-export must be \"git-daemon-export-ok\".";
        }
        {
          assertion =
            cfg.enable
            -> cfg.gitHttpBackend.enable
            -> !cfg.gitHttpBackend.checkExportOkFiles
            -> cfg.settings ? strict-export
            -> cfg.settings.strict-export == null;
          message = "Misconfigured services.cgit.${vhost}: settings.strict-export is set but the gitHttpBackend is enabled and checkExportOkFiles is false.";
        }
      ]) cfgs
    );

    users = lib.mkMerge (
      lib.flip lib.mapAttrsToList cfgs (
        _: cfg: {
          users.${cfg.user} = {
            isSystemUser = true;
            inherit (cfg) group;
          };
          groups.${cfg.group} = { };
        }
      )
    );

    services.fcgiwrap.instances = lib.flip lib.mapAttrs' cfgs (
      name: cfg:
      lib.nameValuePair "cgit-${name}" {
        process = { inherit (cfg) user group; };
        socket = { inherit (config.services.nginx) user group; };
      }
    );

    systemd.services = lib.flip lib.mapAttrs' cfgs (
      name: cfg:
      lib.nameValuePair (fcgiwrapUnitName name) (
        lib.mkIf (cfg.repos != { }) {
          serviceConfig.RuntimeDirectory = fcgiwrapUnitName name;
          preStart = ''
            GIT_PROJECT_ROOT=${lib.escapeShellArg (gitProjectRoot name cfg)}
            mkdir -p "$GIT_PROJECT_ROOT"
            cd "$GIT_PROJECT_ROOT"
            ${lib.concatLines (
              lib.flip lib.mapAttrsToList cfg.repos (
                name: repo: ''
                  ln -s ${lib.escapeShellArg repo.path} ${lib.escapeShellArg name}
                ''
              )
            )}
          '';
        }
      )
    );

    services.nginx.enable = true;

    services.nginx.virtualHosts = lib.mkMerge (
      lib.mapAttrsToList (name: cfg: {
        ${cfg.nginx.virtualHost} = {
          locations =
            (genAttrs' [ "cgit.css" "cgit.js" "cgit.png" "favicon.ico" "robots.txt" ] (
              fileName:
              lib.nameValuePair "= ${stripLocation cfg}/${fileName}" {
                alias = lib.mkDefault "${cfg.package}/cgit/${fileName}";
              }
            ))
            // lib.optionalAttrs cfg.gitHttpBackend.enable {
              "~ ${regexLocation cfg}/.+/(info/refs|git-upload-pack)" = {
                fastcgiParams = rec {
                  SCRIPT_FILENAME = "${pkgs.git}/libexec/git-core/git-http-backend";
                  GIT_PROJECT_ROOT = gitProjectRoot name cfg;
                  HOME = GIT_PROJECT_ROOT;
                }
                // lib.optionalAttrs (!cfg.gitHttpBackend.checkExportOkFiles) {
                  GIT_HTTP_EXPORT_ALL = "1";
                };
                extraConfig = mkFastcgiPass name cfg;
              };
            }
            // {
              "${stripLocation cfg}/" = {
                fastcgiParams = {
                  SCRIPT_FILENAME = "${cfg.package}/cgit/cgit.cgi";
                  QUERY_STRING = "$args";
                  HTTP_HOST = "$server_name";
                  CGIT_CONFIG = mkCgitrc cfg;
                };
                extraConfig = mkFastcgiPass name cfg;
              };
            };
        };
      }) cfgs
    );
  };
}