@@ -5,15 +5,27 @@ set -euo pipefail
55# Configure nginx security based on ENV vars.
66#
77# Inputs (aside from all the individual CSP settings):
8+ # - NGINX_CSP_MODE: defaults to 'enforce'
89# - NGINX_CSP_REPORT_URI: defaults to ''
910# - NGINX_FRAME_OPTIONS: defaults to 'deny', note that setting to `disable` removes the header completely.
1011
1112# Set defaults
1213NGINX_CONFIG_FILE=' /etc/nginx/snippets/vars/csp-and-robots.conf'
1314NGINX_CSP_ITEMS=' child-src connect-src font-src form-action frame-ancestors frame-src img-src manifest-src media-src object-src require-trusted-types-for script-src style-src trusted-types worker-src'
15+ NGINX_CSP_MODE=" ${NGINX_CSP_MODE:- enforce} "
1416NGINX_CSP_REPORT_URI=" ${NGINX_CSP_REPORT_URI:- } "
1517NGINX_FRAME_OPTIONS=" ${NGINX_FRAME_OPTIONS:- deny} "
1618
19+ # Validate input
20+ if [ " ${NGINX_CSP_MODE} " = ' enforce' ]; then
21+ NGINX_CSP_VAR_NAME=' content_security_policy'
22+ elif [ " ${NGINX_CSP_MODE} " = ' report-only' ]; then
23+ NGINX_CSP_VAR_NAME=' content_security_policy_report_only'
24+ else
25+ echo " Nginx: invalid CSP mode ${NGINX_CSP_MODE} "
26+ exit 1
27+ fi
28+
1729# Check nginx structure
1830if [ ! -f " ${NGINX_CONFIG_FILE} " ]; then
1931 echo " Nginx: var-csp-and-robots.conf file is missing, skipping configuring it…"
@@ -60,15 +72,20 @@ csp_item() {
6072nginx_csp_definition () {
6173 name=" $1 "
6274
63- nginx_var_definition " $name " " $(
64- printf " default-src 'self';"
65- for item in $NGINX_CSP_ITEMS ; do
66- csp_item " $item "
67- done
68- csp_item ' report-uri' " $NGINX_CSP_REPORT_URI "
69- ) "
75+ if [ " $name " = " $NGINX_CSP_VAR_NAME " ]; then
76+ nginx_var_definition " $name " " $(
77+ printf " default-src 'self';"
78+ for item in $NGINX_CSP_ITEMS ; do
79+ csp_item " $item "
80+ done
81+ csp_item ' report-uri' " $NGINX_CSP_REPORT_URI "
82+ ) "
83+ else
84+ nginx_var_definition " $name " ' '
85+ fi
7086}
7187
7288# nginx content policy
7389echo " Nginx: configuring content security policy…"
7490nginx_csp_definition content_security_policy >> " ${NGINX_CONFIG_FILE} "
91+ nginx_csp_definition content_security_policy_report_only >> " ${NGINX_CONFIG_FILE} "
0 commit comments