nix

configuration files that power my machines
Log | Files | Refs | README | LICENSE

caddy.nix (1734B)


      1 {
      2   config,
      3   lib,
      4   ...
      5 }: let
      6   cfg = config.services.haravara.caddy;
      7 
      8   mkAuthSnippet = name: authDomain: ''
      9     (${name}) {
     10       forward_auth 127.0.0.1:4180 {
     11         uri /oauth2/auth
     12         copy_headers X-Auth-Request-User X-Auth-Request-Email
     13 
     14         @error status 401
     15         handle_response @error {
     16           redir * https://${authDomain}/oauth2/start?rd=https://{host}{uri}
     17         }
     18       }
     19     }
     20   '';
     21 in {
     22   options.services.haravara.caddy = {
     23     enable = lib.mkEnableOption "Caddy reverse proxy and static site server";
     24     email = lib.mkOption {
     25       type = lib.types.str;
     26     };
     27     authDomains = lib.mkOption {
     28       type = lib.types.attrsOf lib.types.str;
     29       description = "Attribute set of auth snippets to domain names. Key 'auth' is special and used as is, others prefixed with auth_";
     30     };
     31   };
     32 
     33   config = lib.mkIf cfg.enable {
     34     services.caddy = {
     35       enable = true;
     36       inherit (cfg) email;
     37 
     38       globalConfig = ''
     39         servers {
     40           metrics
     41         }
     42       '';
     43 
     44       extraConfig =
     45         (lib.concatStringsSep "\n" (lib.mapAttrsToList (name: domain:
     46           mkAuthSnippet "auth_${name}"
     47           domain)
     48         cfg.authDomains))
     49         + ''
     50           (remote_auth) {
     51             forward_auth https://${cfg.authDomains.haravara} {
     52               uri /oauth2/auth
     53               copy_headers X-Auth-Request-User X-Auth-Request-Email
     54               header_up Host ${cfg.authDomains.haravara}
     55 
     56               @error status 401
     57               handle_response @error {
     58                 redir * https://${cfg.authDomains.haravara}/oauth2/start?rd=https://{host}{uri}
     59               }
     60             }
     61           }
     62         '';
     63     };
     64 
     65     networking.firewall.allowedTCPPorts = [80 443];
     66   };
     67 }