ctucx.git: nixfiles

ctucx' nixfiles

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 
{ config, lib, ... }:

let
  cfg = config.services.nginx-sni-proxy;
  upstreams = with lib; (concatStringsSep "\n" (mapAttrsToList (host: dest:
      "${host} ${dest}:443;"
    ) (concatMapAttrs (dest: hosts:
      (genAttrs hosts (host: dest))
    ) cfg.upstreamHosts
  )));

in {

  options.services.nginx-sni-proxy = {
    enable = lib.mkEnableOption "nginx SNI proxy";

    upstreamHosts = lib.mkOption {
      type = with lib.types; attrsOf (listOf str);
      default = {};
    };
  };

  config.services.nginx = lib.mkIf cfg.enable {
    defaultSSLListenPort = 7443;
    defaultListenAddresses = [ "[::1]" ];

    streamConfig = ''
      map $ssl_preread_server_name $sni_upstream {
        ${upstreams}
        default [::1]:7443;
      }
      server {
        listen 0.0.0.0:443;
        listen [::]:443;
        ssl_preread on;
        resolver 1.1.1.1;
        proxy_pass $sni_upstream;
      }
    '';

    appendHttpConfig = ''
      server {
        listen        0.0.0.0:80;
        listen        [::]:80;
        server_name   _;
        return 301 https://$host$request_uri;
      }
    '';
  };

}