195 lines
9.2 KiB
Bash
Executable File
195 lines
9.2 KiB
Bash
Executable File
#!/bin/sh
|
|
set -eu
|
|
umask 077
|
|
|
|
# This file lives in the persistent /app mount, not inside the downloaded checkout.
|
|
export FAM_START_SCRIPT="$(python3 -c 'from pathlib import Path; import sys; print(Path(sys.argv[1]).resolve())' "$0")"
|
|
export FAM_APP_DIR="$(dirname "$FAM_START_SCRIPT")"
|
|
export FAM_RUNTIME_DIR="${FAM_RUNTIME_DIR:-$FAM_APP_DIR/runtime}"
|
|
export FAM_DATA_DIR="${FAM_DATA_DIR:-/data}"
|
|
export PUID="${PUID:-99}"
|
|
export PGID="${PGID:-100}"
|
|
export GIT_REPO_URL="${GIT_REPO_URL:-https://git.casaderoll.de/michael/Fil-A-Management.git}"
|
|
export GIT_REVISION="${GIT_REVISION:-main}"
|
|
export GITEA_TOKEN_FILE="${GITEA_TOKEN_FILE:-/run/secrets/gitea_token}"
|
|
export GITEA_SSH_KEY_FILE="${GITEA_SSH_KEY_FILE:-/run/secrets/gitea_ssh_key}"
|
|
export GITEA_KNOWN_HOSTS_FILE="${GITEA_KNOWN_HOSTS_FILE:-/run/secrets/gitea_known_hosts}"
|
|
|
|
# Fail before touching files; credentials must never be embedded in a remote URL.
|
|
python3 - <<'PY'
|
|
import os
|
|
import sys
|
|
from pathlib import Path
|
|
from urllib.parse import urlsplit
|
|
|
|
try:
|
|
for name in ("PUID", "PGID"):
|
|
value = os.environ[name]
|
|
if not value.isascii() or not value.isdecimal() or len(value) > 10 or not 1 <= int(value) <= 4294967294:
|
|
raise ValueError(f"{name} muss eine positive numerische, nicht privilegierte ID sein.")
|
|
if os.geteuid() != 0 and (os.geteuid() != int(os.environ["PUID"]) or os.getegid() != int(os.environ["PGID"])):
|
|
raise ValueError("Laufende UID/GID stimmen nicht mit PUID/PGID überein.")
|
|
url = urlsplit(os.environ["GIT_REPO_URL"])
|
|
local = url.scheme == "file" and not url.netloc and os.environ.get("FAM_ALLOW_LOCAL_GIT") == "1"
|
|
if not local and (url.scheme not in {"https", "ssh"} or not url.hostname):
|
|
raise ValueError("GIT_REPO_URL muss eine HTTPS- oder SSH-URL sein.")
|
|
if url.password or (url.username and url.scheme != "ssh") or url.query or url.fragment:
|
|
raise ValueError("Zugangsdaten in URLs sind verboten. Bitte Secret-Dateien verwenden.")
|
|
if url.scheme == "ssh" and url.username not in {None, "git"}:
|
|
raise ValueError("SSH-Zugriff verwendet den technischen Benutzer git.")
|
|
revision = os.environ["GIT_REVISION"]
|
|
if not revision or revision.startswith("-") or any(c.isspace() for c in revision):
|
|
raise ValueError("Ungültige Git-Revision.")
|
|
runtime = Path(os.environ["FAM_RUNTIME_DIR"]).resolve()
|
|
data = Path(os.environ["FAM_DATA_DIR"]).resolve()
|
|
script = Path(os.environ["FAM_START_SCRIPT"])
|
|
app = script.parent
|
|
if app == Path(app.anchor):
|
|
raise ValueError("Das persistente App-Verzeichnis darf nicht das Wurzelverzeichnis sein.")
|
|
if any(script.is_relative_to(runtime / folder) for folder in ("app", "venv", "bootstrap")):
|
|
raise ValueError("Die persistente start.sh darf nicht im austauschbaren Programmverzeichnis liegen.")
|
|
if app.is_relative_to(runtime) or app.is_relative_to(data):
|
|
raise ValueError("Daten- und Programmverzeichnis dürfen das persistente App-Verzeichnis nicht enthalten.")
|
|
if runtime.is_relative_to(data) or data.is_relative_to(runtime):
|
|
raise ValueError("Daten- und Programmverzeichnis müssen vollständig getrennt sein.")
|
|
except ValueError as error:
|
|
sys.exit(str(error))
|
|
PY
|
|
|
|
# Stock python:3.12-alpine has no Git/su-exec. Install them at runtime, not in a build.
|
|
# Root is only the bootstrap identity; Git, pip, migrations and Gunicorn run as PUID:PGID.
|
|
if [ "$(id -u)" = "0" ]; then
|
|
# Protect both the script and its parent before external package work. A writable
|
|
# parent would let the runtime identity replace even a root-owned start.sh.
|
|
chown 0:0 "$FAM_APP_DIR" "$FAM_START_SCRIPT"
|
|
chmod 755 "$FAM_APP_DIR"
|
|
chmod 644 "$FAM_START_SCRIPT"
|
|
command -v apk >/dev/null 2>&1 || { printf '%s\n' 'Root-Bootstrap benötigt das Alpine-Python-Image mit apk.' >&2; exit 1; }
|
|
apk add --no-cache git openssh-client ca-certificates su-exec tzdata
|
|
mkdir -p "$FAM_RUNTIME_DIR" "$FAM_DATA_DIR"
|
|
chmod 700 "$FAM_DATA_DIR"
|
|
chown "$PUID:$PGID" "$FAM_RUNTIME_DIR" "$FAM_DATA_DIR"
|
|
# /run is root-owned in the stock image. Never touch credentials inside the
|
|
# writable runtime tree, including an obsolete credentials symlink.
|
|
credential_dir=/run/fil-a-management
|
|
mkdir -p "$credential_dir"
|
|
chown 0:0 "$credential_dir"
|
|
chmod 711 "$credential_dir"
|
|
copy_secret() {
|
|
# Unlink first: cp/chmod/chown must never follow an old destination link.
|
|
rm -f "$credential_dir/$2"
|
|
if [ -f "$1" ]; then
|
|
cp "$1" "$credential_dir/$2"
|
|
chmod 600 "$credential_dir/$2"
|
|
chown "$PUID:$PGID" "$credential_dir/$2"
|
|
fi
|
|
}
|
|
copy_secret "$GITEA_TOKEN_FILE" token
|
|
copy_secret "$GITEA_SSH_KEY_FILE" ssh-key
|
|
copy_secret "$GITEA_KNOWN_HOSTS_FILE" known-hosts
|
|
export GITEA_TOKEN_FILE="$credential_dir/token"
|
|
export GITEA_SSH_KEY_FILE="$credential_dir/ssh-key"
|
|
export GITEA_KNOWN_HOSTS_FILE="$credential_dir/known-hosts"
|
|
exec su-exec "$PUID:$PGID" /bin/sh "$FAM_START_SCRIPT" "$@"
|
|
fi
|
|
|
|
# Test-only file URLs must become local paths: Git treats file:// as an
|
|
# upload-pack repository transport and cannot read a bundle through that URL.
|
|
if [ "${FAM_ALLOW_LOCAL_GIT:-0}" = "1" ]; then
|
|
GIT_REPO_URL=$(python3 -c 'import os; from urllib.parse import urlsplit; from urllib.request import url2pathname; value=os.environ["GIT_REPO_URL"]; parsed=urlsplit(value); print(url2pathname(parsed.path) if parsed.scheme == "file" else value)')
|
|
export GIT_REPO_URL
|
|
fi
|
|
mkdir -p "$FAM_RUNTIME_DIR/app" "$FAM_DATA_DIR"
|
|
export HOME="$FAM_RUNTIME_DIR"
|
|
export GIT_TERMINAL_PROMPT=0 GIT_CONFIG_NOSYSTEM=1 GIT_CONFIG_GLOBAL=/dev/null
|
|
for tool in git ssh; do
|
|
command -v "$tool" >/dev/null 2>&1 || {
|
|
printf '%s\n' "Systemwerkzeug $tool fehlt. Container als root starten; start.sh senkt danach die Rechte." >&2
|
|
exit 1
|
|
}
|
|
done
|
|
# Keep start.sh self-contained: these helpers must exist before private Git can be fetched.
|
|
mkdir -p "$FAM_RUNTIME_DIR/bootstrap"
|
|
cat > "$FAM_RUNTIME_DIR/bootstrap/git-askpass" <<'ASKPASS'
|
|
#!/bin/sh
|
|
set -eu
|
|
case "$1" in
|
|
*Username*|*username*) printf '%s\n' "${GITEA_USERNAME:-git}" ;;
|
|
*Password*|*password*)
|
|
test -r "$GITEA_TOKEN_FILE" || { printf '%s\n' 'Gitea-Token-Datei fehlt oder ist nicht lesbar.' >&2; exit 1; }
|
|
cat "$GITEA_TOKEN_FILE" ;;
|
|
*) exit 1 ;;
|
|
esac
|
|
ASKPASS
|
|
cat > "$FAM_RUNTIME_DIR/bootstrap/git-ssh" <<'SSH'
|
|
#!/bin/sh
|
|
set -eu
|
|
test -r "$GITEA_SSH_KEY_FILE" && test -r "$GITEA_KNOWN_HOSTS_FILE" || {
|
|
printf '%s\n' 'SSH-Key und verifizierte known_hosts-Datei müssen als Secrets vorliegen.' >&2
|
|
exit 1
|
|
}
|
|
exec ssh -F /dev/null -i "$GITEA_SSH_KEY_FILE" -o IdentitiesOnly=yes -o StrictHostKeyChecking=yes \
|
|
-o "UserKnownHostsFile=$GITEA_KNOWN_HOSTS_FILE" "$@"
|
|
SSH
|
|
chmod 700 "$FAM_RUNTIME_DIR/bootstrap/git-askpass" "$FAM_RUNTIME_DIR/bootstrap/git-ssh"
|
|
export GIT_ASKPASS="$FAM_RUNTIME_DIR/bootstrap/git-askpass"
|
|
export GIT_SSH="$FAM_RUNTIME_DIR/bootstrap/git-ssh"
|
|
export GIT_SSH_VARIANT=ssh
|
|
if [ ! -d "$FAM_RUNTIME_DIR/app/.git" ]; then
|
|
git init --quiet "$FAM_RUNTIME_DIR/app"
|
|
git -C "$FAM_RUNTIME_DIR/app" remote add origin "$GIT_REPO_URL"
|
|
else
|
|
git -C "$FAM_RUNTIME_DIR/app" remote set-url origin "$GIT_REPO_URL"
|
|
fi
|
|
cd "$FAM_RUNTIME_DIR/app"
|
|
git -c credential.helper= fetch --quiet --force --prune origin '+refs/heads/*:refs/remotes/origin/*' '+refs/tags/*:refs/tags/*'
|
|
case "$GIT_REVISION" in
|
|
refs/heads/*) target="refs/remotes/origin/${GIT_REVISION#refs/heads/}" ;;
|
|
refs/tags/*) target="$GIT_REVISION" ;;
|
|
*)
|
|
if git show-ref --verify --quiet "refs/remotes/origin/$GIT_REVISION"; then
|
|
target="refs/remotes/origin/$GIT_REVISION"
|
|
elif git show-ref --verify --quiet "refs/tags/$GIT_REVISION"; then
|
|
target="refs/tags/$GIT_REVISION"
|
|
else
|
|
python3 -c 'import os,re,sys; sys.exit(0 if re.fullmatch(r"[0-9a-fA-F]{40}",os.environ["GIT_REVISION"]) else "Git-Revision nicht gefunden.")'
|
|
target="$GIT_REVISION"
|
|
fi ;;
|
|
esac
|
|
commit=$(git rev-parse --verify "$target^{commit}")
|
|
git checkout --quiet --detach --force "$commit"
|
|
# Only the disposable runtime clone is cleaned. /data can never be inside it.
|
|
git clean -fdx --quiet
|
|
printf 'Fil-A-Management: starte Revision %s\n' "$commit"
|
|
|
|
python3 -m venv --clear "$FAM_RUNTIME_DIR/venv"
|
|
export PATH="$FAM_RUNTIME_DIR/venv/bin:$PATH"
|
|
python -m pip --isolated install --disable-pip-version-check --no-cache-dir --require-hashes -r requirements.txt
|
|
python - <<'PY'
|
|
import os
|
|
import secrets
|
|
from pathlib import Path
|
|
|
|
path = Path(os.environ["FAM_DATA_DIR"]) / "secret.key"
|
|
if not os.environ.get("DJANGO_SECRET_KEY") and not os.environ.get("DJANGO_SECRET_KEY_FILE"):
|
|
try:
|
|
fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
|
|
except FileExistsError:
|
|
pass
|
|
else:
|
|
with os.fdopen(fd, "w") as handle:
|
|
handle.write(secrets.token_urlsafe(64))
|
|
PY
|
|
python manage.py check
|
|
python manage.py migrate --noinput
|
|
if [ "${SEED_CATALOG:-0}" = "1" ]; then
|
|
python manage.py seed_catalog
|
|
fi
|
|
python manage.py collectstatic --noinput --verbosity 0
|
|
if [ "$#" -gt 0 ]; then
|
|
exec "$@"
|
|
fi
|
|
exec gunicorn config.wsgi:application --bind "${FAM_BIND:-0.0.0.0:8000}" \
|
|
--workers 1 --worker-class gthread --threads 2 --timeout 60 \
|
|
--forwarded-allow-ips='' --no-control-socket --access-logfile - --error-logfile -
|