1{ config, lib, ... }:
2with lib;
3let
4 cfg = config.services.oauth2_proxy.nginx;
5in
6{
7 options.services.oauth2_proxy.nginx = {
8 proxy = mkOption {
9 type = types.str;
10 default = config.services.oauth2_proxy.httpAddress;
11 description = ''
12 The address of the reverse proxy endpoint for oauth2_proxy
13 '';
14 };
15 virtualHosts = mkOption {
16 type = types.listOf types.str;
17 default = [];
18 description = ''
19 A list of nginx virtual hosts to put behind the oauth2 proxy
20 '';
21 };
22 };
23 config.services.oauth2_proxy = mkIf (cfg.virtualHosts != [] && (hasPrefix "127.0.0.1:" cfg.proxy)) {
24 enable = true;
25 };
26 config.services.nginx = mkIf config.services.oauth2_proxy.enable (mkMerge
27 ((optional (cfg.virtualHosts != []) {
28 recommendedProxySettings = true; # needed because duplicate headers
29 }) ++ (map (vhost: {
30 virtualHosts.${vhost} = {
31 locations."/oauth2/" = {
32 proxyPass = cfg.proxy;
33 extraConfig = ''
34 proxy_set_header X-Scheme $scheme;
35 proxy_set_header X-Auth-Request-Redirect $scheme://$host$request_uri;
36 '';
37 };
38 locations."/oauth2/auth" = {
39 proxyPass = cfg.proxy;
40 extraConfig = ''
41 proxy_set_header X-Scheme $scheme;
42 # nginx auth_request includes headers but not body
43 proxy_set_header Content-Length "";
44 proxy_pass_request_body off;
45 '';
46 };
47 locations."/".extraConfig = ''
48 auth_request /oauth2/auth;
49 error_page 401 = /oauth2/sign_in;
50
51 # pass information via X-User and X-Email headers to backend,
52 # requires running with --set-xauthrequest flag
53 auth_request_set $user $upstream_http_x_auth_request_user;
54 auth_request_set $email $upstream_http_x_auth_request_email;
55 proxy_set_header X-User $user;
56 proxy_set_header X-Email $email;
57
58 # if you enabled --cookie-refresh, this is needed for it to work with auth_request
59 auth_request_set $auth_cookie $upstream_http_set_cookie;
60 add_header Set-Cookie $auth_cookie;
61 '';
62
63 };
64 }) cfg.virtualHosts)));
65}