From e118a0bf9539e8b851f8c7c50f155a6227f7380c Mon Sep 17 00:00:00 2001 From: Joe Corall Date: Mon, 8 Apr 2024 11:17:58 -0400 Subject: [PATCH] Add a test to ensure client IP is logged --- .../ServiceLogsClientIp/build.gradle.kts | 26 +++++++++++++++++++ .../ServiceLogsClientIp/docker-compose.yml | 20 ++++++++++++++ nginx/tests/ServiceLogsClientIp/test.sh | 13 ++++++++++ 3 files changed, 59 insertions(+) create mode 100644 nginx/tests/ServiceLogsClientIp/build.gradle.kts create mode 100644 nginx/tests/ServiceLogsClientIp/docker-compose.yml create mode 100755 nginx/tests/ServiceLogsClientIp/test.sh diff --git a/nginx/tests/ServiceLogsClientIp/build.gradle.kts b/nginx/tests/ServiceLogsClientIp/build.gradle.kts new file mode 100644 index 00000000..2018ffb7 --- /dev/null +++ b/nginx/tests/ServiceLogsClientIp/build.gradle.kts @@ -0,0 +1,26 @@ +import plugins.TestsPlugin.DockerComposeUp +import java.io.ByteArrayOutputStream + +tasks.named("test") { + doLast { + // get the docker logs from our nginx service + val outputStream = ByteArrayOutputStream() + project.exec { + commandLine = baseArguments + listOf("logs") + standardOutput = outputStream + workingDir = project.projectDir + } + val output = outputStream.toString() + + // see if the log has a match for the IP we set in the test.sh cURL -H command + val pattern = "nginx-1 | 1.2.3.4" + val matchingLines = output.lines().filter { line -> + line.startsWith(pattern) + } + + // fail the test if we didn't find any logs with the IP + if (matchingLines.isEmpty()) { + throw GradleException("No lines found starting with '$pattern'") + } + } +} diff --git a/nginx/tests/ServiceLogsClientIp/docker-compose.yml b/nginx/tests/ServiceLogsClientIp/docker-compose.yml new file mode 100644 index 00000000..8c7f8e15 --- /dev/null +++ b/nginx/tests/ServiceLogsClientIp/docker-compose.yml @@ -0,0 +1,20 @@ +--- +version: "3.8" + +# Common to all services +x-common: &common + restart: "no" + +name: nginx-servicelogsclientip +services: + nginx: + <<: *common + image: ${NGINX:-islandora/nginx:local} + # Set realip as trusting only localhost + environment: + - NGINX_REAL_IP_HEADER=X-Forwarded-For + - NGINX_SET_REAL_IP_FROM=127.0.0.1/32 + volumes: + - ./test.sh:/test.sh + command: + - /test.sh diff --git a/nginx/tests/ServiceLogsClientIp/test.sh b/nginx/tests/ServiceLogsClientIp/test.sh new file mode 100755 index 00000000..7cc62486 --- /dev/null +++ b/nginx/tests/ServiceLogsClientIp/test.sh @@ -0,0 +1,13 @@ +#!/command/with-contenv bash +# shellcheck shell=bash + +set -eou pipefail + +# Wait for Nginx to be ready. +s6-svwait -U /run/service/nginx + +# hit localhost nginx with the proper header so that IP is logged +curl -s -o /dev/null -H "X-Forwarded-For: 1.2.3.4" http://localhost:80/ + +# Service must start for us to get to this point. +exit 0