From 1186bc51776815fb91abab85fec986f47b0dfe38 Mon Sep 17 00:00:00 2001
From: Adar Nimrod <nimrod@shore.co.il>
Date: Sat, 6 Mar 2021 20:24:45 +0200
Subject: [PATCH] Go a different way with running as the right user.

Deduce the uid and gid from the volume owner and run as those. Don't
need to mount /etc/passwd and /etc/group inside the container (didn't
work with --user anyway). No hard-coded uids/ users anymore.
---
 .dockerignore      | 1 +
 Dockerfile         | 7 ++++++-
 docker-compose.yml | 3 ---
 entrypoint         | 9 +++++++++
 4 files changed, 16 insertions(+), 4 deletions(-)
 create mode 100755 entrypoint

diff --git a/.dockerignore b/.dockerignore
index f507923..658ccf7 100644
--- a/.dockerignore
+++ b/.dockerignore
@@ -2,3 +2,4 @@
 !Pipfile*
 !poca.xml
 !crontab
+!entrypoint
diff --git a/Dockerfile b/Dockerfile
index eb18780..38ee10e 100644
--- a/Dockerfile
+++ b/Dockerfile
@@ -3,6 +3,10 @@ FROM registry.shore.co.il/cron as supersonic
 
 FROM registry.hub.docker.com/library/python:3.6-alpine3.13
 COPY --from=supersonic /usr/local/bin/supersonic /usr/local/bin/
+# hadolint ignore=DL3018
+RUN apk add --update --no-cache --repository http://dl-cdn.alpinelinux.org/alpine/edge/testing/ \
+        gosu \
+    ;
 # hadolint ignore=DL3013
 RUN pip install --no-cache-dir pipenv
 WORKDIR /poquita
@@ -16,7 +20,8 @@ RUN apk add --update --no-cache --virtual .lxml-build build-base git libxslt-dev
 RUN mkdir --mode 777 db Podcasts
 COPY --chown=root:root crontab ./
 COPY --chown=root:root poca.xml ./
+COPY --chown=root:root entrypoint /usr/local/sbin/docker-entrypoint
 VOLUME db Podcasts
+ENTRYPOINT ["docker-entrypoint"]
 CMD [ "supersonic", "crontab" ]
-USER nobody
 HEALTHCHECK CMD pgrep supersonic
diff --git a/docker-compose.yml b/docker-compose.yml
index 30900b6..97a545b 100644
--- a/docker-compose.yml
+++ b/docker-compose.yml
@@ -5,10 +5,7 @@ services:
     build:
       context: ./
     restart: on-failure
-    user: nimrod
     volumes:
-      - /etc/group:/etc/group:ro
-      - /etc/passwd:/etc/passwd:ro
       - /srv/library/nimrod/Podcasts:/poquita/Podcasts
       - poquita:/poquita/db
 
diff --git a/entrypoint b/entrypoint
new file mode 100755
index 0000000..59b7d5d
--- /dev/null
+++ b/entrypoint
@@ -0,0 +1,9 @@
+#!/bin/sh
+set -eu
+
+[ "$(id -u)" = "0" ] || { echo "Not running as root, continuing as the current user."; eval exec "$@"; }
+command -v stat > /dev/null || { echo "Can't find stat, exiting."; exit 1; }
+command -v gosu > /dev/null || { echo "Can't find gosu, exiting."; exit 1; }
+uid="$(stat Podcasts -c '%u')"
+gid="$(stat Podcasts -c '%g')"
+eval exec gosu "$uid:$gid" "$@"
-- 
GitLab