Skip to content

Commit f9185e3

Browse files
committed
Nginx: add support for a CSP defaults config file
1 parent 4e6786b commit f9185e3

File tree

2 files changed

+27
-3
lines changed

2 files changed

+27
-3
lines changed

README.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,8 @@ You can control the CSP behaviour with the `NGINX_CSP_MODE` key:
1818
- `enforce` (default): Configure the `Content-Security-Policy` header.
1919
- `report-only`: Instead configure the `Content-Security-Policy-Report-Only` header.
2020

21+
Note: the following fetch & navigation CSP keys can also be set via an embedded file located at `/etc/csp-generator/default`.
22+
2123
Fetch:
2224

2325
| Environment Key | Applied | Description | Default |

common/scripts/startup/50-env-configure-nginx-csp.sh

Lines changed: 25 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,16 @@
22

33
set -euo pipefail
44

5-
# Configure nginx security based on ENV vars.
5+
# Configure nginx security based on ENV vars, and if available the defaults
6+
# located at `/etc/csp-generator/default`.
7+
#
8+
# The defaults file should be a list of variable declarations, such as
9+
# `CHILD_SRC="…"`. Essentially 1 variable for each option that exists. Be
10+
# careful about using quotes though! Keywords such as `none` need to be
11+
# surrounded by single `'` quotes, so the value would be `"'none'"`.
12+
#
13+
# Equivalent settings can be set via ENV, just prefix the variables with
14+
# `NGINX_CSP_…`, like `NGINX_CSP_CHILD_SRC`.
615
#
716
# Inputs (aside from all the individual CSP settings):
817
# - NGINX_CSP_MODE: defaults to 'enforce'
@@ -41,6 +50,17 @@ map "" \$$1 {
4150
EOF
4251
}
4352

53+
# Load embedded CSP values from file (if it exists)
54+
EMBEDDED_CSP_PATH=/etc/csp-generator/default
55+
if [ -f "${EMBEDDED_CSP_PATH}" ]; then
56+
echo "Nginx: found CSP defaults at '$EMBEDDED_CSP_PATH', processing…"
57+
PROCESSED_CSP_PATH=$(mktemp)
58+
sed 's/[^=]\+=/EMBEDDED_CSP_&/' "${EMBEDDED_CSP_PATH}" > "${PROCESSED_CSP_PATH}"
59+
cat $PROCESSED_CSP_PATH
60+
source "${PROCESSED_CSP_PATH}"
61+
rm "${PROCESSED_CSP_PATH}"
62+
fi
63+
4464
# nginx frame options header
4565
if [ "${NGINX_FRAME_OPTIONS}" = 'disable' ]; then
4666
echo "Nginx: configuring frame options as disabled…"
@@ -54,12 +74,14 @@ fi
5474
csp_item() {
5575
item="$1"
5676

57-
# Lookup values if needed, checking `NGINX_CSP_…`
77+
# Lookup values if needed, checking `EMBEDDED_CSP_…` and `NGINX_CSP_…`
5878
if [ -n "${2:-}" ]; then
5979
value="$2"
6080
else
6181
uc_item=$(echo "$item" | tr '[:lower:]-' '[:upper:]_')
62-
value=$(printenv "NGINX_CSP_${uc_item}" || true)
82+
embedded_val=$(printenv "EMBEDDED_CSP_${uc_item}" || true)
83+
nginx_val=$(printenv "NGINX_CSP_${uc_item}" || true)
84+
value="${embedded_val}${embedded_val:+ }${nginx_val}"
6385
fi
6486

6587
# Only output if we have a value

0 commit comments

Comments
 (0)