16 Commits
Author SHA1 Message Date
socat-proxy-ci fc06ff4886 Bump build version to 1.1.1 [skip ci] 2026-08-26 14:38:43 +00:00
Djeex 93fe213c18 Fix flaky unit test on merge-triggered CI runs (#7)
CI / build-and-scan (push) Successful in 2m24s
- entrypoint.sh: bound the target connectivity check with `-w 2` (the only unbounded step in the startup path)
- tests/entrypoint.bats: widen wait_for_log's budget from 5s to 10s

Merge-triggered runs land on a colder runner (Docker cache evicted by other repos' scheduled jobs since the PR was last tested) than PR-check runs, and the first backgrounded entrypoint.sh in the suite was occasionally landing just past the old 5s window — always passed on rerun once warm.
2026-08-26 16:36:39 +02:00
Djeex 348d39192b CI/CD hardening: lint, secret scan, coverage gate, auto CVE-fix PRs, GHCR + GitHub mirror publishing (#6) [skip ci]
- release changelog: commits rendered as description (link), divider lines dropped
- gitleaks secret scan and hadolint on every push/PR
- ruff lint/format gate (Python repos) with a pytest --cov-fail-under gate
- scheduled CRITICAL Trivy failures attempt an apk upgrade rebuild and open a follow-up PR if it clears the finding, instead of just failing red
- images also published to ghcr.io/djeex/<repo>
- a matching GitHub Release is created on the GitHub mirror, with a notice pointing back to this repo as the source of truth
2026-08-26 16:30:56 +02:00
Djeex 71ba8a73fc Merge pull request 'Release notes: list commits instead of changed files' (#5) from dev-v1.1 into main
Reviewed-on: #5
2026-08-23 23:35:40 +02:00
Djeex e196e61941 Link each commit in the release changelog to its own commit page
COMMIT_LIST only rendered the bare subject line per commit, with no
way to jump to that specific commit — only the triggering commit
(Source:) had a link. Each line now reads
"- [<short-sha>](<repo>/commit/<sha>) <subject>", matching the same
link style already used for Source.
2026-08-23 23:22:44 +02:00
Djeex 6e923d3f32 Release notes: list commits instead of changed files 2026-08-23 23:22:44 +02:00
Djeex f8fd388ade Merge pull request 'Run as non-root by default via PUID/PGID' (#4) from dev-v1.1 into main
Reviewed-on: #4
2026-08-23 15:18:11 +02:00
Djeex 0cc1b3cb37 Run as non-root by default via PUID/PGID 2026-08-23 15:10:17 +02:00
socat-proxy-ci a8ce9a5d1a Bump build version to 1.0.1 [skip ci] 2026-08-22 22:13:27 +00:00
Djeex 7e614803aa Merge pull request 'Update alpine Docker tag to v3.24.1' (#2) from renovate/alpine-3.x into main
Reviewed-on: #2
2026-08-23 00:08:24 +02:00
Djeex 09fb0c0b43 Update alpine Docker tag to v3.24.1 2026-08-22 22:05:22 +00:00
Djeex c6d525fec8 Merge pull request 'Dev ci' (#1) from dev-ci into main
Reviewed-on: #1
2026-08-23 00:04:45 +02:00
Djeex cf45734fc0 Add Renovate config
Same policy as adguard-cidre: patch-level Dockerfile bumps automerge,
minor/major get a labeled PR, vulnerability alerts labeled bug. No
pip_requirements rule — this repo has no Python dependencies to manage.

Still needed on the Gitea/Renovate side (manual, not done here):
uncomment socat-proxy in the shared ~/renovate/config.js repositories
array on stockeex, and create the bot/major/minor/bug labels in this
repo's Issues → Labels (Renovate silently drops labels that don't
already exist).
2026-08-23 00:02:11 +02:00
Djeex 387c551c41 Add Gitea Actions CI workflow
Adapted from adguard-cidre's pipeline: build, syntax smoke-test, bats
unit tests, shellcheck lint, Trivy critical/high scans, then on push to
main a versioned publish (VERSION auto-bump, :latest/:X.Y/:X.Y.Z tags
retagged from the already-scanned image, and a categorized Gitea
Release). Requires the REGISTRY_TOKEN and CI_PUSH_TOKEN repo secrets
and branch protection on main (not yet configured on the Gitea side).
2026-08-22 23:50:47 +02:00
Djeex 56daf61290 Multi-stage Dockerfile: pin base image, add test/lint stages
Pin alpine:latest to the full patch-level tag alpine:3.22.1 so Renovate
can classify patch/minor/major bumps on it. Add a `test` stage (bats)
and a `lint` stage (shellcheck, severity=error) that build from `base`
before ENTRYPOINT is set, so CI can run them without an --entrypoint
override. A trailing `FROM base` keeps the lean prod image as the
default `docker build .` target despite the extra stages.
2026-08-22 23:50:40 +02:00
Djeex 59be656047 Add bats test suite for entrypoint.sh
Covers env-var validation, socket path preparation, target connectivity
messaging, DEBUG_LEVEL to socat-flag mapping, and graceful shutdown vs.
crash detection — run against the real socat/nc binaries rather than
mocks, since UNIX-LISTEN binds without needing the TCP target reachable.
2026-08-22 23:50:32 +02:00
8 changed files with 295 additions and 77 deletions
+2
View File
@@ -1,3 +1,5 @@
PUID=1000 # User id the process runs as
PGID=1000 # Group id the process runs as
TARGET_HOST= # Target hostname/IP to proxy to TARGET_HOST= # Target hostname/IP to proxy to
TARGET_PORT= # Target port to proxy to TARGET_PORT= # Target port to proxy to
UNIX_SOCKET_NAME= # Name of the socket file UNIX_SOCKET_NAME= # Name of the socket file
+102 -6
View File
@@ -18,6 +18,21 @@ jobs:
fetch-depth: 0 fetch-depth: 0
persist-credentials: false persist-credentials: false
- name: Scan for secrets
run: |
# docker cp, not a build COPY: a repo's own .dockerignore (e.g. one that
# excludes .git for prod builds) would otherwise silently give an empty,
# falsely-clean scan.
CID=$(docker create zricethezav/gitleaks:v8.30.1 detect --source=/repo --no-banner -v)
docker cp . "$CID:/repo"
docker start -a "$CID"
STATUS=$?
docker rm "$CID" > /dev/null
exit $STATUS
- name: Lint Dockerfile with hadolint
run: docker run --rm -i hadolint/hadolint:v2.15.1-alpine hadolint --failure-threshold error - < Dockerfile
- name: Build Docker image - name: Build Docker image
run: docker build -t socat-proxy:ci . run: docker build -t socat-proxy:ci .
@@ -33,12 +48,53 @@ jobs:
run: docker build --target lint -t socat-proxy:lint . run: docker build --target lint -t socat-proxy:lint .
- name: Scan with Trivy (critical - blocking) - name: Scan with Trivy (critical - blocking)
id: trivy_critical
continue-on-error: true
run: | run: |
docker run --rm \ docker run --rm \
-e DOCKER_HOST=tcp://dockerhost:2375 \ -e DOCKER_HOST=tcp://dockerhost:2375 \
--add-host=dockerhost:host-gateway \ --add-host=dockerhost:host-gateway \
aquasec/trivy:0.74.0 image --exit-code 1 --severity CRITICAL socat-proxy:ci aquasec/trivy:0.74.0 image --exit-code 1 --severity CRITICAL socat-proxy:ci
- name: Handle CRITICAL findings
if: steps.trivy_critical.outcome == 'failure'
run: |
if [ "${{ github.event_name }}" != "schedule" ]; then
echo "::error::CRITICAL vulnerabilities found, failing the build."
exit 1
fi
echo "Scheduled scan found CRITICAL vulnerabilities — attempting an automatic apk upgrade + rescan."
sed -i '/^FROM .* AS base$/a RUN apk upgrade --no-cache' Dockerfile
docker build -t socat-proxy:remediated .
if docker run --rm \
-e DOCKER_HOST=tcp://dockerhost:2375 \
--add-host=dockerhost:host-gateway \
aquasec/trivy:0.74.0 image --exit-code 1 --severity CRITICAL socat-proxy:remediated; then
echo "apk upgrade clears the CRITICAL finding(s) — opening a PR for review."
BRANCH="auto/cve-fix-$(date +%Y%m%d)-$(echo "${{ github.sha }}" | cut -c1-7)"
git config user.name "socat-proxy-ci"
git config user.email "[email protected]"
git checkout -b "$BRANCH"
git add Dockerfile
git commit -m "Auto-remediate CRITICAL CVE via apk upgrade"
git config --unset-all http.https://git.djeex.fr/.extraheader || true
git push "https://Djeex:${{ secrets.CI_PUSH_TOKEN }}@git.djeex.fr/Djeex/socat-proxy.git" "HEAD:$BRANCH"
PR_JSON=$(curl -s -X POST \
-H "Authorization: token ${{ secrets.CI_PUSH_TOKEN }}" \
-H "Content-Type: application/json" \
-d "$(jq -n --arg head "$BRANCH" '{title: "🔒 Auto: remediate CRITICAL CVE via apk upgrade", head: $head, base: "main", body: "Opened automatically by the scheduled CVE scan. An `apk upgrade --no-cache` cleared the CRITICAL Trivy finding(s) in a rebuild — review the diff and merge to publish the fix."}')" \
"https://git.djeex.fr/api/v1/repos/Djeex/socat-proxy/pulls")
echo "PR API response: $(echo "$PR_JSON" | jq -r '.html_url // .message // "unknown"')"
else
echo "::error::apk upgrade does not clear the CRITICAL finding(s) — no automatic fix available, needs manual review."
exit 1
fi
- name: Scan with Trivy (high - informative) - name: Scan with Trivy (high - informative)
run: | run: |
docker run --rm \ docker run --rm \
@@ -51,10 +107,11 @@ jobs:
run: | run: |
BEFORE="${{ github.event.before }}" BEFORE="${{ github.event.before }}"
if [ -n "$BEFORE" ] && [ "$BEFORE" != "0000000000000000000000000000000000000000" ] && git cat-file -e "$BEFORE" 2>/dev/null; then if [ -n "$BEFORE" ] && [ "$BEFORE" != "0000000000000000000000000000000000000000" ] && git cat-file -e "$BEFORE" 2>/dev/null; then
CHANGED=$(git diff --name-only "$BEFORE" "${{ github.sha }}") BASE_REF="$BEFORE"
else else
CHANGED=$(git diff --name-only HEAD~1 HEAD) BASE_REF="HEAD~1"
fi fi
CHANGED=$(git diff --name-only "$BASE_REF" "${{ github.sha }}")
echo "Changed files:" echo "Changed files:"
echo "$CHANGED" echo "$CHANGED"
@@ -102,6 +159,16 @@ jobs:
docker push "$IMAGE:$MINOR_TAG" docker push "$IMAGE:$MINOR_TAG"
docker push "$IMAGE:$VERSION" docker push "$IMAGE:$VERSION"
GHCR_IMAGE=ghcr.io/djeex/socat-proxy
echo "${{ secrets.GH_TOKEN }}" | docker login ghcr.io -u Djeex --password-stdin
docker tag socat-proxy:ci "$GHCR_IMAGE:latest"
docker tag socat-proxy:ci "$GHCR_IMAGE:$MINOR_TAG"
docker tag socat-proxy:ci "$GHCR_IMAGE:$VERSION"
docker push "$GHCR_IMAGE:latest"
docker push "$GHCR_IMAGE:$MINOR_TAG"
docker push "$GHCR_IMAGE:$VERSION"
TRIGGER_MSG=$(git log -1 --format=%s "${{ github.sha }}") TRIGGER_MSG=$(git log -1 --format=%s "${{ github.sha }}")
PR_NUM=$(echo "$TRIGGER_MSG" | grep -oE '#[0-9]+' | head -1 | tr -d '#' || true) PR_NUM=$(echo "$TRIGGER_MSG" | grep -oE '#[0-9]+' | head -1 | tr -d '#' || true)
@@ -127,9 +194,9 @@ jobs:
fi fi
fi fi
CHANGED_LIST=$(echo "$CHANGED" | sed 's/^/- /')
REPO_URL="https://git.djeex.fr/Djeex/socat-proxy" REPO_URL="https://git.djeex.fr/Djeex/socat-proxy"
COMMIT_LIST=$(git log --no-merges --format="- %s ([%h](${REPO_URL}/commit/%H))" "$BASE_REF".."${{ github.sha }}")
SHORT_SHA=$(echo "${{ github.sha }}" | cut -c1-7) SHORT_SHA=$(echo "${{ github.sha }}" | cut -c1-7)
SOURCE_LINE="[${SHORT_SHA}](${REPO_URL}/commit/${{ github.sha }})" SOURCE_LINE="[${SHORT_SHA}](${REPO_URL}/commit/${{ github.sha }})"
if [ -n "$PR_NUM" ]; then if [ -n "$PR_NUM" ]; then
@@ -145,8 +212,8 @@ jobs:
**Source:** ${SOURCE_LINE} **Source:** ${SOURCE_LINE}
**Image:** \`${IMAGE}:${VERSION}\` **Image:** \`${IMAGE}:${VERSION}\`
**Changed files:** **Commits:**
${CHANGED_LIST} ${COMMIT_LIST}
EOF EOF
) )
@@ -161,3 +228,32 @@ jobs:
-H "Content-Type: application/json" \ -H "Content-Type: application/json" \
-d "$JSON_PAYLOAD" \ -d "$JSON_PAYLOAD" \
"https://git.djeex.fr/api/v1/repos/Djeex/socat-proxy/releases" "https://git.djeex.fr/api/v1/repos/Djeex/socat-proxy/releases"
MIRROR_NOTICE="_This github repo is a mirror of https://git.djeex.fr/Djeex/socat-proxy. You'll find full package, PR, history and release note there._"
GH_BODY=$(printf '%s\n\n%s' "$MIRROR_NOTICE" "$BODY")
GH_JSON_PAYLOAD=$(jq -n \
--arg tag "$VERSION" \
--arg name "$VERSION" \
--arg body "$GH_BODY" \
--arg sha "${{ github.sha }}" \
'{tag_name: $tag, name: $name, target_commitish: $sha, body: $body}')
GH_STATUS=0
for i in 1 2 3 4 5; do
GH_STATUS=$(curl -s -o /tmp/gh_release.json -w "%{http_code}" -X POST \
-H "Authorization: Bearer ${{ secrets.GH_TOKEN }}" \
-H "Accept: application/vnd.github+json" \
-H "Content-Type: application/json" \
-d "$GH_JSON_PAYLOAD" \
"https://api.github.com/repos/Djeex/socat-proxy/releases")
if [ "$GH_STATUS" = "201" ]; then
break
fi
echo "GitHub Release attempt $i failed (HTTP $GH_STATUS) — mirror may not have synced this commit yet, retrying in 15s..."
sleep 15
done
echo "GitHub Release API response: $GH_STATUS"
if [ "$GH_STATUS" != "201" ]; then
cat /tmp/gh_release.json 2>/dev/null || true
fi
+1 -1
View File
@@ -1,6 +1,6 @@
FROM alpine:3.24.1 AS base FROM alpine:3.24.1 AS base
RUN apk add --no-cache socat netcat-openbsd \ RUN apk add --no-cache socat netcat-openbsd su-exec \
&& rm -rf /var/cache/apk/* /tmp/* && rm -rf /var/cache/apk/* /tmp/*
COPY entrypoint.sh VERSION / COPY entrypoint.sh VERSION /
+8
View File
@@ -46,6 +46,8 @@ Proxy Docker socket from a docker proxy to a container in host mode without dire
| Variable | Default | Description | Example | | Variable | Default | Description | Example |
|----------|---------|-------------|---------| |----------|---------|-------------|---------|
| `PUID` | `911` | User ID the process runs as (drops root at startup) | `1000` |
| `PGID` | `911` | Group ID the process runs as | `1000` |
| `TARGET_HOST` | - | Target hostname/IP to proxy to | `socket-proxy-beszel` | | `TARGET_HOST` | - | Target hostname/IP to proxy to | `socket-proxy-beszel` |
| `TARGET_PORT` | - | Target port to proxy to | `2375` | | `TARGET_PORT` | - | Target port to proxy to | `2375` |
| `UNIX_SOCKET_NAME` | - | Name of the socket file | `docker.sock` | | `UNIX_SOCKET_NAME` | - | Name of the socket file | `docker.sock` |
@@ -59,6 +61,8 @@ Proxy Docker socket from a docker proxy to a container in host mode without dire
1. Create a `.env` file with your configuration: 1. Create a `.env` file with your configuration:
```bash ```bash
PUID=1000 #user id the process runs as
PGID=1000 #group id the process runs as
TARGET_HOST= #your target host TARGET_HOST= #your target host
TARGET_PORT= #your target host port TARGET_PORT= #your target host port
UNIX_SOCKET_NAME= #your socket file name UNIX_SOCKET_NAME= #your socket file name
@@ -73,6 +77,8 @@ services:
socat-proxy: socat-proxy:
image: git.djeex.fr/djeex/socat-proxy:latest image: git.djeex.fr/djeex/socat-proxy:latest
environment: environment:
- PUID=${PUID}
- PGID=${PGID}
- TARGET_HOST=${TARGET_HOST} - TARGET_HOST=${TARGET_HOST}
- TARGET_PORT=${TARGET_PORT} - TARGET_PORT=${TARGET_PORT}
- UNIX_SOCKET_NAME=${UNIX_SOCKET_NAME} - UNIX_SOCKET_NAME=${UNIX_SOCKET_NAME}
@@ -94,6 +100,8 @@ docker compose up -d
```bash ```bash
docker run -d \ docker run -d \
--name socat-proxy \ --name socat-proxy \
-e PUID=1000 #user id the process runs as \
-e PGID=1000 #group id the process runs as \
-e TARGET_HOST= #your target host \ -e TARGET_HOST= #your target host \
-e TARGET_PORT= #your target host port \ -e TARGET_PORT= #your target host port \
-e UNIX_SOCKET_NAME= #your socket file name \ -e UNIX_SOCKET_NAME= #your socket file name \
+1 -1
View File
@@ -1 +1 @@
1.0.1 1.1.1
+2
View File
@@ -3,6 +3,8 @@ services:
socat-proxy: socat-proxy:
build: . build: .
environment: environment:
- PUID=${PUID}
- PGID=${PGID}
- TARGET_HOST=${TARGET_HOST} - TARGET_HOST=${TARGET_HOST}
- TARGET_PORT=${TARGET_PORT} - TARGET_PORT=${TARGET_PORT}
- UNIX_SOCKET_NAME=${UNIX_SOCKET_NAME} - UNIX_SOCKET_NAME=${UNIX_SOCKET_NAME}
+125 -67
View File
@@ -4,6 +4,52 @@ set -e
CYAN="\033[1;36m" CYAN="\033[1;36m"
NC="\033[0m" NC="\033[0m"
log() { echo "$(date '+%Y-%m-%d %H:%M:%S') $*"; }
fail() { echo "$(date '+%Y-%m-%d %H:%M:%S') [!] $*" >&2; exit 1; }
print_banner() {
version=$(cat VERSION 2>/dev/null || echo "unknown")
title="Socat Proxy - Version ${version}"
lines="Source: https://git.djeex.fr/Djeex/socat-proxy
Mirror: https://github.com/Djeex/socat-proxy"
width=${#title}
old_ifs=$IFS
IFS='
'
for l in $lines; do
[ ${#l} -gt "$width" ] && width=${#l}
done
IFS=$old_ifs
width=$((width + 2))
border=""
i=0
while [ "$i" -lt "$width" ]; do
border="${border}"
i=$((i + 1))
done
printf "${CYAN}╭%s╮${NC}\n" "$border"
total_pad=$((width - ${#title}))
left=$((total_pad / 2))
right=$((total_pad - left))
printf "${CYAN}${NC}%*s%s%*s${CYAN}${NC}\n" "$left" "" "$title" "$right" ""
printf "${CYAN}├%s┤${NC}\n" "$border"
IFS='
'
for l in $lines; do
printf "${CYAN}${NC} %-*s${CYAN}${NC}\n" "$((width - 1))" "$l"
done
IFS=$old_ifs
printf "${CYAN}╰%s╯${NC}\n" "$border"
}
print_banner
DEBUG_LEVEL=${DEBUG_LEVEL:-1} DEBUG_LEVEL=${DEBUG_LEVEL:-1}
UNIX_SOCKET_PATH=${UNIX_SOCKET_PATH%/} UNIX_SOCKET_PATH=${UNIX_SOCKET_PATH%/}
HOST_SOCKET_PATH=${HOST_SOCKET_PATH%/} HOST_SOCKET_PATH=${HOST_SOCKET_PATH%/}
@@ -11,107 +57,116 @@ HOST_SOCKET_PATH=${HOST_SOCKET_PATH%/}
FULL_HOST_SOCKET_PATH="$HOST_SOCKET_PATH/$UNIX_SOCKET_NAME" FULL_HOST_SOCKET_PATH="$HOST_SOCKET_PATH/$UNIX_SOCKET_NAME"
FULL_UNIX_SOCKET_PATH="$UNIX_SOCKET_PATH/$UNIX_SOCKET_NAME" FULL_UNIX_SOCKET_PATH="$UNIX_SOCKET_PATH/$UNIX_SOCKET_NAME"
VERSION=$(cat VERSION)
echo -e "${CYAN}╭────────────────────────────────────────────────╮${NC}"
echo -e "${CYAN}${NC} Socat-proxy - Version ${VERSION}${NC} ${CYAN}${NC}"
echo -e "${CYAN}├────────────────────────────────────────────────┤${NC}"
echo -e "${CYAN}${NC} Source: https://git.djeex.fr/Djeex/socat-proxy ${CYAN}${NC}"
echo -e "${CYAN}${NC} Mirror: https://github.com/Djeex/socat-proxy ${CYAN}${NC}"
echo -e "${CYAN}╰────────────────────────────────────────────────╯${NC}"
# Validate required environment variables # Validate required environment variables
if [ -z "$TARGET_HOST" ]; then [ -n "$TARGET_HOST" ] || fail "TARGET_HOST environment variable is required"
echo "[✗] TARGET_HOST environment variable is required" [ -n "$TARGET_PORT" ] || fail "TARGET_PORT environment variable is required"
exit 1 [ -n "$UNIX_SOCKET_NAME" ] || fail "UNIX_SOCKET_NAME environment variable is required"
fi [ -n "$UNIX_SOCKET_PATH" ] || fail "UNIX_SOCKET_PATH environment variable is required"
[ -n "$HOST_SOCKET_PATH" ] || fail "HOST_SOCKET_PATH environment variable is required"
if [ -z "$TARGET_PORT" ]; then PUID=${PUID:-911}
echo "[✗] TARGET_PORT environment variable is required" PGID=${PGID:-911}
exit 1
fi
if [ -z "$UNIX_SOCKET_NAME" ]; then case "$PGID" in
echo "[✗] UNIX_SOCKET_NAME environment variable is required" ''|*[!0-9]*) fail "PGID '$PGID' is not a valid numeric group id." ;;
exit 1 esac
fi case "$PUID" in
''|*[!0-9]*) fail "PUID '$PUID' is not a valid numeric user id." ;;
esac
if [ -z "$UNIX_SOCKET_PATH" ]; then log "[i] Requested PUID=$PUID, PGID=$PGID"
echo "[✗] UNIX_SOCKET_PATH environment variable is required"
exit 1
fi
if [ -z "$HOST_SOCKET_PATH" ]; then log "[~] Checking group for GID $PGID..."
echo "[✗] HOST_SOCKET_PATH environment variable is required" GROUP_NAME=$(getent group "$PGID" | cut -d: -f1 || true)
exit 1 if [ -z "$GROUP_NAME" ]; then
log "[→] No existing group with GID $PGID, creating 'appgroup'."
addgroup -g "$PGID" appgroup || fail "Failed to create group with GID $PGID (addgroup exited $?)."
GROUP_NAME=appgroup
else
log "[i] Reusing existing group '$GROUP_NAME' (GID $PGID)."
fi fi
log "[✓] Group ready: $GROUP_NAME"
echo "[~] Starting socat proxy..." log "[~] Checking user for UID $PUID..."
echo "[i] TCP target: $TARGET_HOST:$TARGET_PORT" USER_NAME=$(getent passwd "$PUID" | cut -d: -f1 || true)
echo "[i] HOST path: $HOST_SOCKET_PATH" if [ -z "$USER_NAME" ]; then
echo "[i] Full host socket path: $FULL_HOST_SOCKET_PATH" log "[] No existing user with UID $PUID, creating 'appuser'."
echo "[i] Full socket path: $FULL_UNIX_SOCKET_PATH" adduser -D -u "$PUID" -G "$GROUP_NAME" appuser || fail "Failed to create user with UID $PUID (adduser exited $?)."
USER_NAME=appuser
else
log "[i] Reusing existing user '$USER_NAME' (UID $PUID)."
fi
log "[✓] User ready: $USER_NAME"
log "[~] Starting socat proxy..."
log "[i] TCP target: $TARGET_HOST:$TARGET_PORT"
log "[i] HOST path: $HOST_SOCKET_PATH"
log "[i] Full host socket path: $FULL_HOST_SOCKET_PATH"
log "[i] Full socket path: $FULL_UNIX_SOCKET_PATH"
# Check if socket file/folder exists and handle it # Check if socket file/folder exists and handle it
if [ -e "$FULL_UNIX_SOCKET_PATH" ]; then if [ -e "$FULL_UNIX_SOCKET_PATH" ]; then
echo "[~] Socket file/folder $FULL_UNIX_SOCKET_PATH exists, removing it..." log "[~] Socket file/folder $FULL_UNIX_SOCKET_PATH exists, removing it..."
if rm -rf "$FULL_UNIX_SOCKET_PATH"; then if rm -rf "$FULL_UNIX_SOCKET_PATH"; then
echo "[✓] Removed existing socket $FULL_UNIX_SOCKET_PATH" log "[✓] Removed existing socket $FULL_UNIX_SOCKET_PATH"
else else
echo "[✗] Failed to remove existing socket $FULL_UNIX_SOCKET_PATH" fail "Failed to remove existing socket $FULL_UNIX_SOCKET_PATH"
exit 1
fi fi
fi fi
echo "[~] Creating socket directory structure..." log "[~] Creating socket directory structure..."
# Create directory if needed # Create directory if needed
if mkdir -p "$UNIX_SOCKET_PATH"; then if mkdir -p "$UNIX_SOCKET_PATH"; then
echo "[✓] Created directory $UNIX_SOCKET_PATH" log "[✓] Created directory $UNIX_SOCKET_PATH"
else else
echo "[✗] Failed to create directory $UNIX_SOCKET_PATH" fail "Failed to create directory $UNIX_SOCKET_PATH"
exit 1
fi fi
echo "[~] Creating socket with netcat..." # Grant the target user write access to the socket directory so the
# su-exec'd socat process below can create the socket file in it.
log "[~] Setting ownership of $UNIX_SOCKET_PATH to $USER_NAME:$GROUP_NAME..."
chown "$USER_NAME:$GROUP_NAME" "$UNIX_SOCKET_PATH" || fail "chown on $UNIX_SOCKET_PATH failed — check that the host directory permissions allow it."
log "[✓] Ownership set on $UNIX_SOCKET_PATH"
log "[~] Preparing socket path..."
# Create socket file by touching it, then remove it (this creates the path but leaves it clean for socat) # Create socket file by touching it, then remove it (this creates the path but leaves it clean for socat)
touch "$FULL_UNIX_SOCKET_PATH" touch "$FULL_UNIX_SOCKET_PATH"
rm "$FULL_UNIX_SOCKET_PATH" rm "$FULL_UNIX_SOCKET_PATH"
echo "[✓] Socket path prepared at $FULL_UNIX_SOCKET_PATH" log "[✓] Socket path prepared at $FULL_UNIX_SOCKET_PATH"
# Debug: Check if socket file exists and its permissions # Debug: Check if socket file exists and its permissions
if [ -S "$FULL_UNIX_SOCKET_PATH" ]; then if [ -S "$FULL_UNIX_SOCKET_PATH" ]; then
echo "[✓] Socket file exists and is a socket" log "[✓] Socket file exists and is a socket"
ls -la "$FULL_UNIX_SOCKET_PATH" ls -la "$FULL_UNIX_SOCKET_PATH"
else else
echo "[!] Socket file does not exist or is not a socket" log "[!] Socket file does not exist or is not a socket"
ls -la "$UNIX_SOCKET_PATH" ls -la "$UNIX_SOCKET_PATH"
fi fi
echo "[~] Testing connection to target..." log "[~] Testing connection to target..."
# Test if we can reach the target before starting socat # Test if we can reach the target before starting socat
if ! nc -z "$TARGET_HOST" "$TARGET_PORT" 2>/dev/null; then if ! nc -z -w 2 "$TARGET_HOST" "$TARGET_PORT" 2>/dev/null; then
echo "[!] Cannot connect to $TARGET_HOST:$TARGET_PORT - socat will retry automatically" log "[!] Cannot connect to $TARGET_HOST:$TARGET_PORT - socat will retry automatically"
else else
echo "[✓] Connection to $TARGET_HOST:$TARGET_PORT is working" log "[✓] Connection to $TARGET_HOST:$TARGET_PORT is working"
fi fi
# Signal handler for graceful shutdown # Signal handler for graceful shutdown
cleanup() { cleanup() {
echo "[!] Received SIGTERM, shutting down gracefully..." log "[!] Received SIGTERM, shutting down gracefully..."
if [ ! -z "$SOCAT_PID" ]; then if [ -n "$SOCAT_PID" ]; then
echo "[~] Stopping socat process (PID: $SOCAT_PID)..." log "[~] Stopping socat process (PID: $SOCAT_PID)..."
kill "$SOCAT_PID" 2>/dev/null || true kill "$SOCAT_PID" 2>/dev/null || true
wait "$SOCAT_PID" 2>/dev/null || true wait "$SOCAT_PID" 2>/dev/null || true
fi fi
echo "[~] Cleanup completed, exiting..." log "[~] Cleanup completed, exiting..."
exit 0 exit 0
} }
# Set up signal trap # Set up signal trap
trap cleanup SIGTERM SIGINT trap cleanup SIGTERM SIGINT
echo "[~] Starting socat proxy..." log "[~] Starting socat proxy..."
# Start socat with configurable verbosity # Start socat with configurable verbosity
DEBUG_FLAGS="" DEBUG_FLAGS=""
if [ "$DEBUG_LEVEL" -eq 1 ]; then if [ "$DEBUG_LEVEL" -eq 1 ]; then
@@ -122,25 +177,29 @@ elif [ "$DEBUG_LEVEL" -eq 3 ]; then
DEBUG_FLAGS="-d -d -d" DEBUG_FLAGS="-d -d -d"
fi fi
echo "[i] Using debug level: $DEBUG_LEVEL ($DEBUG_FLAGS)" log "[i] Using debug level: $DEBUG_LEVEL ($DEBUG_FLAGS)"
if socat $DEBUG_FLAGS UNIX-LISTEN:$FULL_UNIX_SOCKET_PATH,fork,unlink-early TCP:$TARGET_HOST:$TARGET_PORT & then # mode=666 keeps the socket connectable from another container's UID
# regardless of PUID/PGID here — see project notes on the socket
# permission trade-off (this proxy's own threat model is the host/network
# boundary, not multi-tenant isolation between containers on the same host).
log "[→] Dropping privileges to $USER_NAME:$GROUP_NAME and starting socat"
if su-exec "$USER_NAME:$GROUP_NAME" socat $DEBUG_FLAGS UNIX-LISTEN:$FULL_UNIX_SOCKET_PATH,fork,unlink-early,mode=666 TCP:$TARGET_HOST:$TARGET_PORT & then
SOCAT_PID=$! SOCAT_PID=$!
echo "[✓] Socat started with PID: $SOCAT_PID" log "[✓] Socat started with PID: $SOCAT_PID"
echo "[i] Socat command: socat -d -d UNIX-LISTEN:$FULL_UNIX_SOCKET_PATH,fork,unlink-early TCP:$TARGET_HOST:$TARGET_PORT" log "[i] Socat command: socat $DEBUG_FLAGS UNIX-LISTEN:$FULL_UNIX_SOCKET_PATH,fork,unlink-early,mode=666 TCP:$TARGET_HOST:$TARGET_PORT"
echo "[~] Container is ready and running..." log "[~] Container is ready and running..."
# Debug: Check socket after socat starts # Debug: Check socket after socat starts
sleep 2 sleep 2
if [ -S "$FULL_UNIX_SOCKET_PATH" ]; then if [ -S "$FULL_UNIX_SOCKET_PATH" ]; then
echo "[✓] Socat socket is active" log "[✓] Socat socket is active"
ls -la "$FULL_UNIX_SOCKET_PATH" ls -la "$FULL_UNIX_SOCKET_PATH"
else else
echo "[!] Socat socket not found" log "[!] Socat socket not found"
fi fi
else else
echo "[✗] Failed to start socat proxy" fail "Failed to start socat proxy"
exit 1
fi fi
# Keep the script alive and wait for socat process # Keep the script alive and wait for socat process
@@ -148,5 +207,4 @@ while kill -0 "$SOCAT_PID" 2>/dev/null; do
sleep 1 sleep 1
done done
echo "[✗] Socat process has stopped" fail "Socat process has stopped"
exit 1
+54 -2
View File
@@ -15,6 +15,11 @@
setup() { setup() {
TEST_DIR="$(mktemp -d)" TEST_DIR="$(mktemp -d)"
# mktemp defaults to 700 (root-only traversal); a real bind-mounted host
# directory is typically world-traversable, so match that here — otherwise
# the non-root user entrypoint.sh drops to can't even reach its own
# (correctly chowned) socket subdirectory.
chmod 755 "$TEST_DIR"
cp "$BATS_TEST_DIRNAME/../entrypoint.sh" "$TEST_DIR/" cp "$BATS_TEST_DIRNAME/../entrypoint.sh" "$TEST_DIR/"
cp "$BATS_TEST_DIRNAME/../VERSION" "$TEST_DIR/" cp "$BATS_TEST_DIRNAME/../VERSION" "$TEST_DIR/"
chmod +x "$TEST_DIR/entrypoint.sh" chmod +x "$TEST_DIR/entrypoint.sh"
@@ -36,7 +41,9 @@ teardown() {
run_entrypoint_bg() { run_entrypoint_bg() {
LOG="$TEST_DIR/out.log" LOG="$TEST_DIR/out.log"
( cd "$TEST_DIR" && exec ./entrypoint.sh >"$LOG" 2>&1 ) & # Invoked via the absolute path (not a bare `./entrypoint.sh`) so its
# /proc cmdline actually contains $TEST_DIR for entrypoint_pid() to match.
( cd "$TEST_DIR" && exec "$TEST_DIR/entrypoint.sh" >"$LOG" 2>&1 ) &
disown 2>/dev/null || true disown 2>/dev/null || true
} }
@@ -51,7 +58,11 @@ socat_pid() {
wait_for_log() { wait_for_log() {
pattern="$1" pattern="$1"
tries=0 tries=0
while [ "$tries" -lt 20 ]; do # 40 * 0.25s = 10s — merge-triggered runs can land on a cold runner
# (evicted Docker cache, first container start), pushing the very first
# backgrounded entrypoint.sh past a tighter budget even though nothing's
# actually wrong; a rerun on a warm runner always passes.
while [ "$tries" -lt 40 ]; do
grep -qE "$pattern" "$LOG" 2>/dev/null && return 0 grep -qE "$pattern" "$LOG" 2>/dev/null && return 0
tries=$((tries + 1)) tries=$((tries + 1))
sleep 0.25 sleep 0.25
@@ -106,6 +117,47 @@ wait_for_pid_gone() {
[[ "$output" == *"HOST_SOCKET_PATH environment variable is required"* ]] [[ "$output" == *"HOST_SOCKET_PATH environment variable is required"* ]]
} }
# ---- PUID/PGID privilege dropping ------------------------------------------
@test "fails when PUID is not numeric" {
export PUID=abc
run "$TEST_DIR/entrypoint.sh"
[ "$status" -eq 1 ]
[[ "$output" == *"PUID 'abc' is not a valid numeric user id."* ]]
}
@test "fails when PGID is not numeric" {
export PGID=abc
run "$TEST_DIR/entrypoint.sh"
[ "$status" -eq 1 ]
[[ "$output" == *"PGID 'abc' is not a valid numeric group id."* ]]
}
@test "creates appuser/appgroup at the default 911 PUID/PGID and owns the socket dir" {
run_entrypoint_bg
wait_for_log "Socat socket is active|Socat socket not found"
grep -q "No existing group with GID 911, creating 'appgroup'" "$LOG"
grep -q "No existing user with UID 911, creating 'appuser'" "$LOG"
owner="$(stat -c '%U:%G' "$UNIX_SOCKET_PATH")"
[ "$owner" = "appuser:appgroup" ]
}
@test "reuses an existing user/group instead of creating one" {
export PUID=0
export PGID=0
run_entrypoint_bg
wait_for_log "Socat socket is active|Socat socket not found"
grep -q "Reusing existing group 'root' (GID 0)" "$LOG"
grep -q "Reusing existing user 'root' (UID 0)" "$LOG"
}
@test "creates the socket with mode 666 so other-UID consumers can connect" {
run_entrypoint_bg
wait_for_log "Socat socket is active|Socat socket not found"
mode="$(stat -c '%a' "$UNIX_SOCKET_PATH/$UNIX_SOCKET_NAME")"
[ "$mode" = "666" ]
}
@test "prints the version banner from the VERSION file" { @test "prints the version banner from the VERSION file" {
echo "9.9.9" > "$TEST_DIR/VERSION" echo "9.9.9" > "$TEST_DIR/VERSION"
run_entrypoint_bg run_entrypoint_bg