{%- from 'vars/globals.map.jinja' import GLOBALS %}
{%- from 'docker/docker.map.jinja' import DOCKER %}
{%- from 'nginx/map.jinja' import NGINXMERGED %}
{%- set role = grains.id.split('_') | last %}
{%- set influxpass = salt['pillar.get']('secrets:influx_pass') %}
{%- set influxauth = ('so:' + influxpass) | base64_encode %}

worker_processes auto;
error_log /var/log/nginx/error.log;
pid /run/nginx.pid;
user nobody;

include /usr/share/nginx/modules/*.conf;

events {
	worker_connections 1024;
}

http {
	log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
						'$status $body_bytes_sent "$http_referer" '
						'"$http_user_agent" "$http_x_forwarded_for"';

	access_log  /var/log/nginx/access.log  main;

	sendfile            on;
	tcp_nopush          on;
	tcp_nodelay         on;
	keepalive_timeout   65;
	types_hash_max_size 2048;
	client_max_body_size 2500M;

	server_tokens off;

	include             /etc/nginx/mime.types;
	default_type        application/octet-stream;

	limit_req_zone $binary_remote_addr zone=auth_throttle:10m rate={{ NGINXMERGED.config.throttle_login_rate }}r/m;

	include /etc/nginx/conf.d/*.conf;

	{%- if role in ['fleet'] %}

	server {
		listen 8443;
		server_name {{ GLOBALS.hostname }};
		root /opt/socore/html;
		location /artifacts/ {
			try_files $uri =206;
			proxy_read_timeout    90;
			proxy_connect_timeout 90;
			proxy_set_header      Host $host;
			proxy_set_header      X-Real-IP $remote_addr;
			proxy_set_header      X-Forwarded-For $proxy_add_x_forwarded_for;
			proxy_set_header      Proxy "";
			proxy_set_header      X-Forwarded-Proto $scheme;
		}
	}

    {%- endif %}

	{%- if GLOBALS.is_manager %}

	server {
		listen 80 default_server;
		server_name _;
		return 307 https://{{ GLOBALS.url_base }}$request_uri;
	}

	server {
		listen 8443;
		server_name {{ GLOBALS.url_base }};
		root /opt/socore/html;
		location /artifacts/ {
			try_files $uri =206;
			proxy_read_timeout    90;
			proxy_connect_timeout 90;
			proxy_set_header      Host $host;
			proxy_set_header      X-Real-IP $remote_addr;
			proxy_set_header      X-Forwarded-For $proxy_add_x_forwarded_for;
			proxy_set_header      Proxy "";
			proxy_set_header      X-Forwarded-Proto $scheme;
		}
	}

	server {
		listen 443 ssl default_server;
		http2 on;
		server_name _;
		return 307 https://{{ GLOBALS.url_base }}$request_uri;

		add_header 	Content-Security-Policy     "default-src 'self' 'unsafe-inline' 'unsafe-eval' https: data: blob: wss:; frame-ancestors 'self'";
		add_header 	X-Frame-Options             SAMEORIGIN;
		add_header 	X-XSS-Protection            "1; mode=block";
		add_header 	X-Content-Type-Options      nosniff;
		add_header 	Strict-Transport-Security   "max-age=31536000; includeSubDomains";
		add_header 	referrer-Policy             no-referrer;

		ssl_certificate "/etc/pki/nginx/server.crt";
		ssl_certificate_key "/etc/pki/nginx/server.key";
		ssl_session_cache shared:SSL:1m;
		ssl_session_timeout  10m;
		ssl_ciphers TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384:TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256:TLS_ECDHE_RSA_WITH_ARIA_256_GCM_SHA384:TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256:TLS_ECDHE_RSA_WITH_ARIA_128_GCM_SHA256:TLS_RSA_WITH_AES_256_GCM_SHA384:TLS_RSA_WITH_AES_256_CCM:TLS_RSA_WITH_ARIA_256_GCM_SHA384:TLS_RSA_WITH_AES_128_GCM_SHA256:TLS_RSA_WITH_AES_128_CCM:TLS_RSA_WITH_ARIA_128_GCM_SHA256;
		ssl_ecdh_curve secp521r1:secp384r1;
		ssl_prefer_server_ciphers on;
		ssl_protocols TLSv1.2 TLSv1.3;
	}

	{%- endif %}

	{%- if GLOBALS.is_manager %}

	server {
		listen 7788;
		server_name {{ GLOBALS.url_base }};
		root /nsm/rules;
		location / {
			allow all;
			sendfile on;
			sendfile_max_chunk 1m;
			autoindex on;
			autoindex_exact_size off;
			autoindex_format html;
			autoindex_localtime on;
		}
	}
	{%-   if NGINXMERGED.external_suricata %}
    server {
        listen 7789 ssl;
		http2 on;
        server_name {{ GLOBALS.url_base }};
        root /surirules;

		add_header 	Content-Security-Policy     "default-src 'self' 'unsafe-inline' 'unsafe-eval' https: data: blob: wss:; frame-ancestors 'self'";
		add_header 	X-Frame-Options             SAMEORIGIN;
		add_header 	X-XSS-Protection            "1; mode=block";
		add_header 	X-Content-Type-Options      nosniff;
		add_header 	Strict-Transport-Security   "max-age=31536000; includeSubDomains";
		add_header 	referrer-Policy             no-referrer;

		ssl_certificate "/etc/pki/nginx/server.crt";
		ssl_certificate_key "/etc/pki/nginx/server.key";
		ssl_session_cache shared:SSL:1m;
		ssl_session_timeout  10m;
		ssl_ciphers TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384:TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256:TLS_ECDHE_RSA_WITH_ARIA_256_GCM_SHA384:TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256:TLS_ECDHE_RSA_WITH_ARIA_128_GCM_SHA256:TLS_RSA_WITH_AES_256_GCM_SHA384:TLS_RSA_WITH_AES_256_CCM:TLS_RSA_WITH_ARIA_256_GCM_SHA384:TLS_RSA_WITH_AES_128_GCM_SHA256:TLS_RSA_WITH_AES_128_CCM:TLS_RSA_WITH_ARIA_128_GCM_SHA256;
		ssl_ecdh_curve secp521r1:secp384r1;
		ssl_prefer_server_ciphers on;
		ssl_protocols TLSv1.2 TLSv1.3;
        location / {
        	allow all;
        	sendfile on;
        	sendfile_max_chunk 1m;
        	autoindex on;
        	autoindex_exact_size off;
        	autoindex_format html;
        	autoindex_localtime on;
        }
    }
    {%-   endif %}

	server {
		listen       443 ssl;
		http2 on;
		server_name  {{ GLOBALS.url_base }};
		root         /opt/socore/html;
		index        index.html;

		add_header 	Content-Security-Policy     "default-src 'self' 'unsafe-inline' 'unsafe-eval' https: data: blob: wss:; frame-ancestors 'self'";
		add_header 	X-Frame-Options             SAMEORIGIN;
		add_header 	X-XSS-Protection            "1; mode=block";
		add_header 	X-Content-Type-Options      nosniff;
		add_header 	Strict-Transport-Security   "max-age=31536000; includeSubDomains";
		add_header 	referrer-Policy             no-referrer;

		ssl_certificate "/etc/pki/nginx/server.crt";
		ssl_certificate_key "/etc/pki/nginx/server.key";
		ssl_session_cache shared:SSL:1m;
		ssl_session_timeout  10m;
		ssl_ciphers TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384:TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256:TLS_ECDHE_RSA_WITH_ARIA_256_GCM_SHA384:TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256:TLS_ECDHE_RSA_WITH_ARIA_128_GCM_SHA256:TLS_RSA_WITH_AES_256_GCM_SHA384:TLS_RSA_WITH_AES_256_CCM:TLS_RSA_WITH_ARIA_256_GCM_SHA384:TLS_RSA_WITH_AES_128_GCM_SHA256:TLS_RSA_WITH_AES_128_CCM:TLS_RSA_WITH_ARIA_128_GCM_SHA256;
		ssl_ecdh_curve secp521r1:secp384r1;
		ssl_prefer_server_ciphers on;
		ssl_protocols TLSv1.2 TLSv1.3;

		location ~* (^/login/.*|^/js/.*|^/css/.*|^/images/.*) {
			proxy_pass            http://{{ GLOBALS.manager }}:9822;
			proxy_read_timeout    90;
			proxy_connect_timeout 90;
			proxy_set_header      x-user-id "";
			proxy_set_header      Host $host;
			proxy_set_header      X-Real-IP $remote_addr;
			proxy_set_header      X-Forwarded-For $proxy_add_x_forwarded_for;
			proxy_set_header      Proxy "";
			proxy_set_header      Upgrade $http_upgrade;
			proxy_set_header      Connection "Upgrade";
			proxy_set_header      X-Forwarded-Proto $scheme;
		}

		location / {
			auth_request            /auth/sessions/whoami;
			auth_request_set        $userid $upstream_http_x_kratos_authenticated_identity_id;
			proxy_set_header        x-user-id $userid;
			proxy_pass              http://{{ GLOBALS.manager }}:9822/;
			proxy_read_timeout      300;
			proxy_connect_timeout   300;
			proxy_set_header        Host $host;
			proxy_set_header        X-Real-IP $remote_addr;
			proxy_set_header        X-Forwarded-For $proxy_add_x_forwarded_for;
			proxy_set_header        Proxy "";
			proxy_set_header        Upgrade $http_upgrade;
			proxy_set_header        Connection "Upgrade";
			proxy_set_header        X-Forwarded-Proto $scheme;

			proxy_buffering         off;
			proxy_cache             off;
			proxy_request_buffering off;
		}

		location ~ ^/auth/.*?(login|oidc/callback) {
			rewrite               /auth/(.*) /$1 break;
			limit_req             zone=auth_throttle burst={{ NGINXMERGED.config.throttle_login_burst }} nodelay;
			limit_req_status      429;
			proxy_pass            http://{{ GLOBALS.manager }}:4433;
			proxy_read_timeout    90;
			proxy_connect_timeout 90;
			proxy_set_header      Host $host;
			proxy_set_header      X-Real-IP $remote_addr;
			proxy_set_header      X-Forwarded-For $proxy_add_x_forwarded_for;
			proxy_set_header      Proxy "";
			proxy_set_header      X-Forwarded-Proto $scheme;
		}

		location ~ ^/auth/.*?(whoami|logout|settings|errors|webauthn.js) {
			rewrite               /auth/(.*) /$1 break;
			proxy_pass            http://{{ GLOBALS.manager }}:4433;
			proxy_read_timeout    90;
			proxy_connect_timeout 90;
			proxy_set_header      Host $host;
			proxy_set_header      X-Real-IP $remote_addr;
			proxy_set_header      X-Forwarded-For $proxy_add_x_forwarded_for;
			proxy_set_header      Proxy "";
			proxy_set_header      X-Forwarded-Proto $scheme;
		}

{%  if 'api' in salt['pillar.get']('features', []) %}
		location ~* (^/oauth2/token.*|^.well-known/jwks.json|^.well-known/openid-configuration) {
			limit_req             zone=auth_throttle burst={{ NGINXMERGED.config.throttle_login_burst }} nodelay;
			limit_req_status      429;
			proxy_pass            http://{{ GLOBALS.manager }}:4444;
			proxy_read_timeout    90;
			proxy_connect_timeout 90;
			proxy_set_header      Host $host;
			proxy_set_header      X-Real-IP $remote_addr;
			proxy_set_header      X-Forwarded-For $proxy_add_x_forwarded_for;
			proxy_set_header      Proxy "";
			proxy_set_header      X-Forwarded-Proto $scheme;
		}

		location /connect/ {
			if ($http_authorization !~ "Bearer .*") {
				return 401;
			}
			rewrite               /connect/(.*) /api/$1 break;
			proxy_pass            http://{{ GLOBALS.manager }}:9822/;
			proxy_read_timeout    300;
			proxy_connect_timeout 300;
			proxy_set_header      x-user-id "";
			proxy_set_header      Host $host;
			proxy_set_header      X-Real-IP $remote_addr;
			proxy_set_header      X-Forwarded-For $proxy_add_x_forwarded_for;
			proxy_set_header      Proxy "";
			proxy_set_header      X-Forwarded-Proto $scheme;
		}
{%-  endif %}

		location /cyberchef/ {
			auth_request          /auth/sessions/whoami;
			proxy_read_timeout    90;
			proxy_connect_timeout 90;
			proxy_set_header      Host $host;
			proxy_set_header      X-Real-IP $remote_addr;
			proxy_set_header      X-Forwarded-For $proxy_add_x_forwarded_for;
			proxy_set_header      Proxy "";
			proxy_set_header      X-Forwarded-Proto $scheme;
		}

		location /navigator/ {
			auth_request          /auth/sessions/whoami;
			proxy_read_timeout    90;
			proxy_connect_timeout 90;
			proxy_set_header      Host $host;
			proxy_set_header      X-Real-IP $remote_addr;
			proxy_set_header      X-Forwarded-For $proxy_add_x_forwarded_for;
			proxy_set_header      Proxy "";
			proxy_set_header      X-Forwarded-Proto $scheme;
		}

		location /packages/ {
			try_files $uri =206;
			auth_request          /auth/sessions/whoami;
			proxy_read_timeout    90;
			proxy_connect_timeout 90;
			proxy_set_header      Host $host;
			proxy_set_header      X-Real-IP $remote_addr;
			proxy_set_header      X-Forwarded-For $proxy_add_x_forwarded_for;
			proxy_set_header      Proxy "";
			proxy_set_header      X-Forwarded-Proto $scheme;
		}

		location /repo/ {
			allow all;
			sendfile on;
			sendfile_max_chunk 1m;
			autoindex on;
			autoindex_exact_size off;
			autoindex_format html;
			autoindex_localtime on;
		}

		location /influxdb/ {
			auth_request          /auth/sessions/whoami;
			rewrite               /influxdb/api/(.*) /api/$1 break;
			proxy_pass            https://{{ GLOBALS.manager }}:8086/;
			proxy_read_timeout    300;
			proxy_connect_timeout 90;
			proxy_set_header      Host $host;
			proxy_set_header      X-Real-IP $remote_addr;
			proxy_set_header      X-Forwarded-For $proxy_add_x_forwarded_for;
			proxy_set_header      Proxy "";
			proxy_set_header      X-Forwarded-Proto $scheme;
			proxy_cookie_path     /api/ /influxdb/api/;
		}

        location /app/dashboards/ {
            auth_request          /auth/sessions/whoami;
            rewrite               /app/dashboards/(.*) /app/dashboards/$1 break;
            proxy_pass            http://{{ GLOBALS.manager }}:5601/app/;
            proxy_read_timeout    300;
            proxy_connect_timeout 300;
            proxy_set_header      Host $host;
            proxy_set_header      X-Real-IP $remote_addr;
            proxy_set_header      X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header      Proxy "";
            proxy_set_header      X-Forwarded-Proto $scheme;
        } 
               
        location /kibana/ {
			auth_request          /auth/sessions/whoami;
			rewrite               /kibana/(.*) /$1 break;
			proxy_pass            http://{{ GLOBALS.manager }}:5601/;
			proxy_read_timeout    300;
			proxy_connect_timeout 300;
			proxy_set_header      Host $host;
			proxy_set_header      X-Real-IP $remote_addr;
			proxy_set_header      X-Forwarded-For $proxy_add_x_forwarded_for;
			proxy_set_header      Proxy "";
			proxy_set_header      X-Forwarded-Proto $scheme;
		}


		location /kibana/app/soc/ {
			rewrite ^/kibana/app/soc/(.*) /soc/$1 permanent;
		}


		location /sensoroniagents/ {
			if ($http_authorization = "") {
				return 403;
			}
			proxy_pass            http://{{ GLOBALS.manager }}:9822/;
			proxy_read_timeout    90;
			proxy_connect_timeout 90;
			proxy_set_header      x-user-id "";
			proxy_set_header      Host $host;
			proxy_set_header      X-Real-IP $remote_addr;
			proxy_set_header      X-Forwarded-For $proxy_add_x_forwarded_for;
			proxy_set_header      Proxy "";
			proxy_set_header      X-Forwarded-Proto $scheme;
		}

		error_page 401 = @error401;
		error_page 403 = @error403;
		error_page 429 = @error429;

		location @error401 {
			if ($request_uri ~* (^/connect/.*|^/oauth2/.*)) {
				return	  401;
			}
			if ($request_uri ~* ^/(?!(^/api/.*))) {
				add_header    Set-Cookie "AUTH_REDIRECT=$request_uri;Path=/;Max-Age=14400";
				add_header    Strict-Transport-Security   "max-age=31536000; includeSubDomains";
			}
			return        302 /auth/self-service/login/browser;
		}

		location @error403 {
			if ($request_uri ~* (^/connect/.*|^/oauth2/.*)) {
				return	  403;
			}
			add_header    Set-Cookie "ory_kratos_session=;Path=/;Max-Age=0;expires=Thu, 01 Jan 1970 00:00:00 GMT;";
			add_header    Strict-Transport-Security   "max-age=31536000; includeSubDomains";
			return        302 /auth/self-service/login/browser;
		}

		location @error429 {
			return        302 /login/?thr={{ (120 / NGINXMERGED.config.throttle_login_rate) | round | int }};
		}

		error_page 500 502 503 504 /50x.html;
				location = /usr/share/nginx/html/50x.html {
		}
	}
	{%- endif %}
}
