From bae4f32effc0036363e241c3a6c1648595bd764e Mon Sep 17 00:00:00 2001 From: arcnmx Date: Wed, 20 Mar 2024 12:54:08 -0700 Subject: [PATCH] feat(grocy): vouch reverse-proxy auth --- modules/nixos/nginx/lua.nix | 113 ++++++++++++++++++ modules/nixos/nginx/vouch.nix | 213 +++++++++++++++++++++++----------- nixos/access/grocy.nix | 36 ++++++ nixos/base/nixpkgs.nix | 1 + nixos/grocy.nix | 50 +++++++- overlays/nginx.nix | 25 ++++ systems/hakurei/nixos.nix | 18 +++ 7 files changed, 388 insertions(+), 68 deletions(-) create mode 100644 modules/nixos/nginx/lua.nix create mode 100644 nixos/access/grocy.nix create mode 100644 overlays/nginx.nix diff --git a/modules/nixos/nginx/lua.nix b/modules/nixos/nginx/lua.nix new file mode 100644 index 00000000..41a7334a --- /dev/null +++ b/modules/nixos/nginx/lua.nix @@ -0,0 +1,113 @@ +{pkgs, config, lib, ...}: let + inherit (lib.options) mkOption mkEnableOption; + inherit (lib.modules) mkIf mkMerge mkAfter mkOptionDefault; + inherit (lib.strings) hasPrefix; + inherit (lib.attrsets) mapAttrsToList; + inherit (config.services.nginx) lua; + cfg = lua; + enabled = cfg.http.enable || cfg.upstream.enable; + luaPkgPath = pkg: "${pkg.lib or pkg}/lib/lua/${pkgs.luajit_openresty.luaversion}/?.lua"; + luaModule = {config, ...}: let + cfg = config.lua; + mkSetBy = var: value: + if hasPrefix "/" "${value}" then "set_by_lua_file \$${var} ${value};" + else '' + set_by_lua_block ''$${var} { + ${value} + } + ''; + in { + options.lua = with lib.types; { + access = { + block = mkOption { + type = lines; + default = ""; + }; + files = mkOption { + type = listOf path; + default = [ ]; + }; + }; + set = mkOption { + type = attrsOf (either path lines); + default = { }; + }; + }; + config = { + extraConfig = mkMerge [ + (mkIf (cfg.access.block != "") (assert lua.http.enable; '' + access_by_lua_block { + ${cfg.access.block} + } + '')) + (mkIf (cfg.access.files != [ ]) (assert lua.http.enable; mkMerge ( + map (file: "access_by_lua_file ${file};") cfg.access.files + ))) + (mkIf (cfg.set != { }) (assert lua.http.enable && lua.ndk.enable; mkMerge ( + mapAttrsToList mkSetBy cfg.set + ))) + ]; + }; + }; + locationModule = {config, ...}: { + imports = [ luaModule ]; + }; + hostModule = {config, ...}: { + imports = [ luaModule ]; + + options = with lib.types; { + locations = mkOption { + type = attrsOf (submoduleWith { + modules = [ locationModule ]; + shorthandOnlyDefinesConfig = true; + }); + }; + }; + }; +in { + options.services.nginx = with lib.types; { + lua = { + ndk.enable = mkEnableOption "ngx_devel_kit"; + http.enable = mkEnableOption "ngx_http_lua_module"; + upstream.enable = mkEnableOption "ngx_http_lua_upstream"; + luaPackage = mkOption { + type = package; + default = pkgs.luajit_openresty; + readOnly = true; + }; + modules = mkOption { + type = listOf package; + }; + luaPath = mkOption { + type = separatedString ";"; + }; + }; + virtualHosts = mkOption { + type = attrsOf (submoduleWith { + modules = [ hostModule ]; + shorthandOnlyDefinesConfig = true; + }); + }; + }; + config = { + services.nginx = { + lua = { + modules = [ + cfg.luaPackage.pkgs.lua-resty-core + ] ++ cfg.luaPackage.pkgs.lua-resty-core.propagatedBuildInputs; + luaPath = mkMerge ( + map luaPkgPath cfg.modules + ++ [ (mkAfter ";") ] + ); + }; + additionalModules = mkMerge [ + (mkIf cfg.ndk.enable [ pkgs.nginxModules.develkit ]) + (mkIf cfg.http.enable [ pkgs.nginxModules.lua ]) + (mkIf cfg.upstream.enable [ pkgs.nginxModules.lua-upstream ]) + ]; + }; + systemd.services.nginx = mkIf config.services.nginx.enable { + environment.LUA_PATH = mkIf enabled (mkOptionDefault cfg.luaPath); + }; + }; +} diff --git a/modules/nixos/nginx/vouch.nix b/modules/nixos/nginx/vouch.nix index dfc32aab..4dcf290b 100644 --- a/modules/nixos/nginx/vouch.nix +++ b/modules/nixos/nginx/vouch.nix @@ -1,38 +1,55 @@ { + pkgs, config, lib, ... }: let inherit (lib.options) mkOption mkEnableOption; - inherit (lib.modules) mkIf mkMerge mkBefore mkDefault; + inherit (lib.modules) mkIf mkMerge mkBefore mkAfter mkOptionDefault mkOverride; + inherit (lib.attrsets) mapAttrsToList; + inherit (lib.strings) toLower replaceStrings concatStringsSep; inherit (config) networking; inherit (config.services) vouch-proxy nginx tailscale; inherit (nginx) vouch; + mkAlmostOptionDefault = mkOverride 1250; locationModule = {config, virtualHost, ...}: { options.vouch = with lib.types; { requireAuth = mkEnableOption "require auth to access this location"; + setProxyHeader = mkOption { + type = bool; + default = false; + description = "proxy_set_header X-Vouch-User"; + }; }; - config = mkIf config.vouch.requireAuth { - proxied.xvars.enable = true; + config = let + enableVouchLocal = vouch.localSso.enable && config.local.enable; + enableVouchTail = enableVouchLocal && tailscale.enable; + allowOrigin = url: "add_header Access-Control-Allow-Origin ${url};"; + in mkIf config.vouch.requireAuth { + lua = mkIf virtualHost.vouch.auth.lua.enable { + access.block = mkMerge [ + (mkBefore virtualHost.vouch.auth.lua.accessRequest) + (mkBefore virtualHost.vouch.auth.lua.accessVariables) + (mkBefore virtualHost.vouch.auth.lua.accessLogic) + ]; + }; + proxied.xvars.enable = mkIf (enableVouchTail || virtualHost.vouch.auth.lua.enable) true; extraConfig = assert virtualHost.vouch.enable; mkMerge [ - '' - add_header Access-Control-Allow-Origin ${vouch.url}; - add_header Access-Control-Allow-Origin ${vouch.authUrl}; - '' - (mkIf (vouch.localSso.enable && config.local.enable) '' - add_header Access-Control-Allow-Origin ${vouch.localUrl}; - '') - (mkIf (vouch.localSso.enable && config.local.enable && tailscale.enable) '' - add_header Access-Control-Allow-Origin $x_scheme://${vouch.tailDomain}; - '') - '' + (mkIf (!virtualHost.vouch.requireAuth) virtualHost.vouch.auth.requestDirective) + (allowOrigin vouch.url) + (allowOrigin vouch.authUrl) + (mkIf enableVouchLocal (allowOrigin vouch.localUrl)) + (mkIf enableVouchTail (allowOrigin "$x_scheme://${vouch.tailDomain}")) + (mkIf config.vouch.setProxyHeader '' proxy_set_header X-Vouch-User $auth_resp_x_vouch_user; - '' + '') ]; }; }; hostModule = {config, ...}: let cfg = config.vouch; + mkHeaderVar = header: toLower (replaceStrings [ "-" ] [ "_" ] header); + mkUpstreamVar = header: "\$upstream_http_${mkHeaderVar header}"; in { options = with lib.types; { locations = mkOption { @@ -43,57 +60,125 @@ requireAuth = mkEnableOption "require auth to access this host" // { default = true; }; - errorLocation = mkOption { - type = str; - default = "@error401"; - }; - authRequestLocation = mkOption { - type = str; - default = "/validate"; - }; - authRequestDirective = mkOption { - type = lines; - default = '' - auth_request ${cfg.authRequestLocation}; - ''; + auth = { + lua = { + enable = mkEnableOption "lua"; + accessRequest = mkOption { + type = lines; + default = '' + ngx.ctx.auth_res = ngx.location.capture("${cfg.auth.requestLocation}") + ''; + }; + accessVariables = mkOption { + type = lines; + }; + accessLogic = mkOption { + type = lines; + }; + }; + errorLocation = mkOption { + type = nullOr str; + default = "@error401"; + }; + requestLocation = mkOption { + type = str; + default = "/validate"; + }; + requestDirective = mkOption { + type = lines; + default = '' + auth_request ${cfg.auth.requestLocation}; + ''; + }; + variables = mkOption { + type = attrsOf str; + default = { + auth_resp_x_vouch_user = "X-Vouch-User"; + auth_resp_jwt = "X-Vouch-Token"; + auth_resp_err = "X-Vouch-Error"; + auth_resp_success = "X-Vouch-Success"; + auth_resp_redirect = "X-Vouch-Requested-URI"; + }; + }; }; }; }; config = { - extraConfig = mkIf (cfg.enable && cfg.requireAuth) '' - ${cfg.authRequestDirective} - error_page 401 = ${cfg.errorLocation}; - ''; + vouch.auth = { + lua = { + accessLogic = mkOptionDefault (mkAfter '' + if ngx.ctx.auth_res ~= nil and ngx.ctx.auth_res.status == ngx.HTTP_UNAUTHORIZED then + local vouch_url = ngx.var["vouch_url"] or "${vouch.url}" + local query_args = ngx.encode_args { + url = string.format("%s://%s%s", ngx.var.x_scheme, ngx.var.x_forwarded_host, ngx.var.request_uri), + ["X-Vouch-Token"] = ngx.ctx.auth_res.header["X-Vouch-Token"] or "", + error = ngx.ctx.auth_res.header["X-Vouch-Error"] or "", + -- ["vouch-failcount"] is now a session variable and shouldn't be needed anymore + } + + return ngx.redirect(string.format("%s/login?%s", vouch_url, query_args), ngx.HTTP_MOVED_TEMPORARILY) + end + if ngx.ctx.auth_res ~= nil and ngx.ctx.auth_res.status == ngx.HTTP_FORBIDDEN or ngx.ctx.auth_res.status == ngx.HTTP_UNAUTHORIZED then + return ngx.exit(ngx.ctx.auth_res.status) + end + + if ngx.ctx.auth_res ~= nil and ngx.ctx.auth_res.status ~= ngx.HTTP_OK then + return ngx.exit(ngx.HTTP_INTERNAL_SERVER_ERROR) + end + ''); + accessVariables = mkMerge (mapAttrsToList (authVar: header: mkOptionDefault + ''ngx.var["${authVar}"] = ngx.ctx.auth_res.header["${header}"] or ""'' + ) cfg.auth.variables); + }; + errorLocation = mkIf cfg.auth.lua.enable (mkAlmostOptionDefault null); + requestDirective = mkIf cfg.auth.lua.enable (mkAlmostOptionDefault ""); + }; + lua = mkIf (cfg.requireAuth && cfg.auth.lua.enable) { + access.block = mkMerge [ + (mkBefore cfg.auth.lua.accessRequest) + (mkBefore cfg.auth.lua.accessVariables) + (mkBefore cfg.auth.lua.accessLogic) + ]; + }; + extraConfig = let + localVouchUrl = '' + if ($x_forwarded_host ~ "\.local\.${networking.domain}$") { + set $vouch_url ${vouch.localUrl}; + } + ''; + tailVouchUrl = '' + if ($x_forwarded_host ~ "\.tail\.${networking.domain}$") { + set $vouch_url $x_scheme://${vouch.tailDomain}; + } + ''; + setVouchUrl = [ + (mkBefore '' + set $vouch_url ${vouch.url}; + '') + (mkIf (vouch.localSso.enable && config.local.enable or false) localVouchUrl) + (mkIf (vouch.localSso.enable && config.local.enable or false && tailscale.enable) tailVouchUrl) + ]; + in mkIf cfg.enable (mkMerge ( + [ + (mkIf (cfg.requireAuth) (mkBefore cfg.auth.requestDirective)) + (mkIf (cfg.auth.errorLocation != null) "error_page 401 = ${cfg.auth.errorLocation};") + ] ++ setVouchUrl + ++ mapAttrsToList (authVar: header: mkIf (!cfg.auth.lua.enable) ( + mkBefore "auth_request_set \$${authVar} ${mkUpstreamVar header};" + )) cfg.auth.variables + )); + proxied.xvars.enable = mkIf cfg.enable true; locations = mkIf cfg.enable { "/" = mkIf cfg.requireAuth { - vouch.requireAuth = true; + vouch.requireAuth = mkAlmostOptionDefault true; }; - ${cfg.errorLocation} = { + ${cfg.auth.errorLocation} = mkIf (cfg.auth.errorLocation != null) { proxied.xvars.enable = true; - extraConfig = let - localVouchUrl = '' - if ($x_forwarded_host ~ "\.local\.${networking.domain}$") { - set $vouch_url ${vouch.localUrl}; - } - ''; - tailVouchUrl = '' - if ($x_forwarded_host ~ "\.tail\.${networking.domain}$") { - set $vouch_url $x_scheme://${vouch.tailDomain}; - } - ''; - in - mkMerge [ - (mkBefore '' - set $vouch_url ${vouch.url}; - '') - (mkIf (vouch.localSso.enable && config.local.enable or false) localVouchUrl) - (mkIf (vouch.localSso.enable && config.local.enable or false && tailscale.enable) tailVouchUrl) - '' - return 302 $vouch_url/login?url=$x_scheme://$x_forwarded_host$request_uri&vouch-failcount=$auth_resp_failcount&X-Vouch-Token=$auth_resp_jwt&error=$auth_resp_err; - '' - ]; + extraConfig = '' + return 302 $vouch_url/login?url=$x_scheme://$x_forwarded_host$request_uri&X-Vouch-Token=$auth_resp_jwt&error=$auth_resp_err; + ''; }; - ${cfg.authRequestLocation} = { + ${cfg.auth.requestLocation} = { proxyPass = "${vouch.proxyOrigin}/validate"; proxy.headers.enableRecommended = true; extraConfig = let @@ -105,10 +190,6 @@ set $x_proxy_host ${vouchProxyHost}; proxy_pass_request_body off; proxy_set_header Content-Length ""; - auth_request_set $auth_resp_x_vouch_user $upstream_http_x_vouch_user; - auth_request_set $auth_resp_jwt $upstream_http_x_vouch_jwt; - auth_request_set $auth_resp_err $upstream_http_x_vouch_err; - auth_request_set $auth_resp_failcount $upstream_http_x_vouch_failcount; ''; }; }; @@ -157,7 +238,7 @@ in { vouch = mkMerge [ { proxyOrigin = mkIf (tailscale.enable && !vouch-proxy.enable) ( - mkDefault "http://login.tail.${networking.domain}" + mkAlmostOptionDefault "http://login.tail.${networking.domain}" ); } (mkIf vouch-proxy.enable { @@ -168,10 +249,10 @@ in { then "localhost" else listen; in - mkDefault "http://${host}:${toString port}"; - authUrl = mkDefault vouch-proxy.authUrl; - url = mkDefault vouch-proxy.url; - doubleProxy = mkDefault false; + mkAlmostOptionDefault "http://${host}:${toString port}"; + authUrl = mkAlmostOptionDefault vouch-proxy.authUrl; + url = mkAlmostOptionDefault vouch-proxy.url; + doubleProxy = mkAlmostOptionDefault false; }) ]; }; diff --git a/nixos/access/grocy.nix b/nixos/access/grocy.nix new file mode 100644 index 00000000..532a24db --- /dev/null +++ b/nixos/access/grocy.nix @@ -0,0 +1,36 @@ +{ + config, + lib, + ... +}: let + inherit (lib.modules) mkIf mkDefault; + inherit (config.services) grocy nginx; + name.shortServer = mkDefault "grocy"; +in { + config.services.nginx.virtualHosts = { + grocy = { + inherit name; + locations."/" = mkIf (!grocy.enable) { + proxy.headers.enableRecommended = true; + extraConfig = '' + set $x_proxy_host ${nginx.virtualHosts.grocy.serverName}; + ''; + }; + }; + grocy'local = { + inherit name; + local.enable = mkDefault true; + locations."/" = mkIf (!grocy.enable) { + proxyPass = mkDefault (if grocy.enable + then "http://localhost:${nginx.defaultHTTPListenPort}" + else nginx.virtualHosts.grocy.locations."/".proxyPass + ); + proxy.headers.enableRecommended = true; + extraConfig = '' + set $x_proxy_host ${nginx.virtualHosts.grocy.serverName}; + proxy_redirect $x_scheme://${nginx.virtualHosts.grocy.serverName}/ $x_scheme://$x_host/; + ''; + }; + }; + }; +} diff --git a/nixos/base/nixpkgs.nix b/nixos/base/nixpkgs.nix index 9dea092e..d23120ea 100644 --- a/nixos/base/nixpkgs.nix +++ b/nixos/base/nixpkgs.nix @@ -3,6 +3,7 @@ overlays = [ inputs.arcexprs.overlays.default (import ../../overlays/samba.nix) + (import ../../overlays/nginx.nix) ]; config = { allowUnfree = true; diff --git a/nixos/grocy.nix b/nixos/grocy.nix index 78b50711..443e6a4a 100644 --- a/nixos/grocy.nix +++ b/nixos/grocy.nix @@ -1,5 +1,8 @@ {config, lib, ...}: let - inherit (lib.modules) mkDefault; + inherit (lib.modules) mkIf mkDefault mkAfter; + inherit (lib.strings) escapeRegex; + inherit (config.services) nginx; + inherit (config) networking; in { config = { services.grocy = { @@ -12,10 +15,53 @@ in { }; services.nginx = let name.shortServer = mkDefault "grocy"; + lua.access.block = '' + local grocy_user_pat = "^([^@]+)@.*$" + if ngx.re.match(ngx.var.auth_resp_x_vouch_user, grocy_user_pat) then + ngx.var["grocy_user"] = ngx.re.sub(ngx.var.auth_resp_x_vouch_user, grocy_user_pat, "$1", "o") or "guest" + end + ''; + extraConfig = mkAfter '' + set $grocy_user guest; + set $grocy_middleware Grocy\Middleware\ReverseProxyAuthMiddleware; + + fastcgi_param GENSO_GROCY_USER $grocy_user; + fastcgi_param GROCY_REVERSE_PROXY_AUTH_HEADER GENSO_GROCY_USER; + fastcgi_param GROCY_REVERSE_PROXY_AUTH_USE_ENV true; + + fastcgi_param GROCY_AUTH_CLASS $grocy_middleware; + ''; in { + lua.http.enable = true; virtualHosts = { - grocy = { + grocy = {config, ...}: { inherit name; + vouch = { + enable = true; + requireAuth = false; + auth.lua = { + enable = true; + accessRequest = '' + local grocy_apikey = ngx.var["http_grocy_api_key"] + if grocy_apikey ~= nil and ngx.re.match(ngx.var.request_uri, "^/api(/|$)") then + -- bypass authentication and let grocy decide... + -- if the API key is valid, the middleware will use its user instead + -- if the API key is invalid, the middleware will fall back to the (invalid/empty) user string + ngx.ctx.auth_res = { + status = ngx.HTTP_OK, + header = { }, + } + ngx.var["grocy_user"] = "" + else + ngx.ctx.auth_res = ngx.location.capture("${config.vouch.auth.requestLocation}") + end + ''; + }; + }; + locations."~ \\.php$" = mkIf nginx.virtualHosts.grocy.vouch.enable { + vouch.requireAuth = true; + inherit extraConfig lua; + }; }; }; }; diff --git a/overlays/nginx.nix b/overlays/nginx.nix new file mode 100644 index 00000000..6a95731c --- /dev/null +++ b/overlays/nginx.nix @@ -0,0 +1,25 @@ +final: prev: let + inherit (final) lib; + luaOverlay = luafinal: luaprev: { + lua-resty-core = luaprev.lua-resty-core.overrideAttrs (old: rec { + version = lib.warnIf (old.version != "0.1.24") "lua-resty-core updated upstream" "0.1.28"; + src = old.src.override { + rev = "v${version}"; + sha256 = "sha256-RJ2wcHTu447wM0h1fa2qCBl4/p9XL6ZqX9pktRW64RI="; + }; + }); + }; +in { + nginxModules = prev.nginxModules // { + lua = let + inherit (prev.nginxModules) lua; + in lua // lib.warnIf (lua.version != "0.10.26") "nginxModules.lua updated upstream" { + preConfigure = lib.replaceStrings [ "patch " ] [ "#patch " ] lua.preConfigure; + }; + }; + luaInterpreters = prev.luaInterpreters.override (old: { + callPackage = final.newScope { + packageOverrides = lib.composeExtensions (final.packageOverrides or (_: _: { })) luaOverlay; + }; + }); +} diff --git a/systems/hakurei/nixos.nix b/systems/hakurei/nixos.nix index 08374916..97f4db0f 100644 --- a/systems/hakurei/nixos.nix +++ b/systems/hakurei/nixos.nix @@ -39,6 +39,7 @@ in { nixos.access.unifi nixos.access.kitchencam nixos.access.home-assistant + nixos.access.grocy nixos.access.proxmox nixos.access.plex nixos.access.invidious @@ -82,6 +83,14 @@ in { virtualHosts.home-assistant'local.allServerNames ]; }; + grocy = { + inherit (nginx) group; + domain = virtualHosts.grocy.serverName; + extraDomainNames = mkMerge [ + virtualHosts.grocy.serverAliases + virtualHosts.grocy'local.allServerNames + ]; + }; vouch = { inherit (nginx) group; domain = virtualHosts.vouch.serverName; @@ -213,6 +222,15 @@ in { locations."/".proxyPass = "http://${tei.lib.access.hostnameForNetwork.tail}:${toString home-assistant.config.http.server_port}"; }; home-assistant'local.ssl.cert.name = "home-assistant"; + grocy = { + # not the real grocy record-holder, so don't respond globally.. + local.denyGlobal = true; + ssl.cert.name = "grocy"; + locations."/".proxyPass = "http://${tei.lib.access.hostnameForNetwork.tail}"; + }; + grocy'local = { + ssl.cert.name = "grocy"; + }; ${access.freepbx.domain} = { local.enable = true; };