Author SHA1 Message Date
l.kirchner 490fda2ed1 K-114: address cross-review findings
CI / Shell-Lint (bash -n, source-check, Validierungs-Tests) (pull_request) Has been cancelled
- CTID prompt re-prompts on invalid interactive input (was: abort)
- env-provided NAMESERVER is validated when non-empty ('' stays inherit)
- prompt_validated handles EOF (no infinite loop, clean abort under -e)
- 10# base forcing in vlan/cidr/ipv4 arithmetic (leading zeros are not
  octal errors); is_clean_ascii rejects embedded newline/tab explicitly
  (command substitution strips trailing newlines); is_ipv4_list checks
  the whole string before word splitting
- nameref guard against reserved variable names in prompt_validated/
  require_valid; source-check pattern documented as the repo contract
- 8 new test cases (41 total)
2026-06-12 03:20:11 +02:00
l.kirchner 80e2ec04ff K-114: input validation in build.func + mini CI (nexus-hub card)
- validation helpers: sanitize_input trims CR/edge whitespace only;
  embedded control/non-ASCII bytes FAIL validation and re-prompt with a
  hint (2026-06-11 incident: invisible byte in a pasted VLAN tag broke
  pct create mid-run) - never silently stripped
- prompt_lxc_config: every prompt validated (uint for CTID/disk/cores/
  RAM, VLAN 1-4094, hostname/token formats, IP/CIDR/gateway, DNS list);
  env-provided values are sanitized + validated too (abort, no re-prompt
  loop in non-interactive use); helpers reusable for app prompts
- tests/test_validation.sh: 34 cases incl. the 2<0x80>0 repro, re-prompt
  simulation, BASH_REMATCH clobbering regression (is_cidr), env dry-run
  of prompt_lxc_config without PVE/TTY
- tests/check_ct_source.sh: every ct/*.sh must source build.func (bug
  shipped twice); negative proof via prepared fixture in the test suite
- .gitea/workflows/ci.yml: bash -n over all scripts, source-check,
  validation tests, shellcheck if present (documented skip otherwise)
- README: contributions via PR with cross-review (binding)
2026-06-12 03:14:32 +02:00
7 changed files with 420 additions and 376 deletions
+46
View File
@@ -0,0 +1,46 @@
name: CI
# K-114 (nexus-hub): Mini-CI für proxmox-scripts — Syntax, build.func-Source-
# Pflicht und Validierungs-Unit-Tests. Läuft auf dem nexus-Runner (Host-Mode).
on:
push:
branches: [main]
pull_request:
jobs:
lint:
name: Shell-Lint (bash -n, source-check, Validierungs-Tests)
runs-on: nexus
steps:
- name: Checkout
uses: actions/checkout@v4
- name: bash -n über alle Scripts
run: |
status=0
for f in ct/*.sh install/*.sh lib/*.func tests/*.sh; do
if bash -n "$f"; then
echo "ok $f"
else
echo "SYNTAX $f" >&2
status=1
fi
done
exit "$status"
- name: build.func-Source-Check (jedes ct/*.sh)
run: bash tests/check_ct_source.sh
- name: Validierungs-Unit-Tests (lib/build.func)
run: bash tests/test_validation.sh
- name: shellcheck (falls auf dem Runner installiert)
run: |
if command -v shellcheck >/dev/null 2>&1; then
# -S warning: Style-Hinweise nicht blockierend; externe Sources
# (curl|source) kann shellcheck nicht folgen.
shellcheck -S warning -e SC1090,SC1091 ct/*.sh install/*.sh tests/*.sh
else
echo "shellcheck nicht installiert — übersprungen (dokumentiert, K-114)"
fi
+6
View File
@@ -24,6 +24,12 @@ CTID=200 HOSTNAME=devpi DISK_SIZE=30 RAM=4096 CORES=4 IPCFG=dhcp \
All defaults (`DEFAULT_HOSTNAME`, `DEFAULT_DISK`, …) are settable per-call via env vars as well.
## Contributing (verbindlich seit K-114)
**Alle Änderungen laufen als PR mit Cross-Review** — keine Direkt-Commits auf `main`. Hintergrund: Der „`build.func` nicht gesourct"-Bug hat es einmal bis in die Produktion geschafft (authentik-Anlage), während dieselbe Fehlerklasse im nexus-db-PR vom Review gefangen wurde. Die CI (`.gitea/workflows/ci.yml`, Runner-Label `nexus`) erzwingt zusätzlich: `bash -n` über alle Scripts, „jedes `ct/*.sh` sourct `build.func`" (`tests/check_ct_source.sh`) und die Validierungs-Unit-Tests (`tests/test_validation.sh`).
Eingaben in `prompt_lxc_config` sind validiert (Ziffern-Checks, IP/CIDR/Gateway-Format, Re-Prompt bei unsichtbaren Steuer-/Non-ASCII-Zeichen — Lesson vom 2026-06-11). Neue App-Prompts bitte über `prompt_validated`/`require_valid` aus `lib/build.func` bauen statt nacktem `read`.
## Repo layout
```
-155
View File
@@ -1,155 +0,0 @@
#!/usr/bin/env bash
# Allgemeiner Gitea-Actions-Runner — instanzweit, OHNE Deploy-Rechte
#
# Motivation (nexus K-114-Blocker): Der nexus-Runner läuft auf dem
# Produktions-LXC und besitzt sudoers-Deploy-Rechte — er darf deshalb NICHT
# instanzweit registriert werden (jedes Repo könnte sonst Workflows auf der
# Produktionsmaschine ausführen). Dieser LXC ist die saubere Trennung:
# - instanzweite Registrierung (Site Administration → Actions → Runners)
# - Label "homelab:host" (Deploy-Jobs bleiben auf "nexus")
# - KEINE sudoers-Regeln, kein Zugriff auf Produktions-Verzeichnisse
# - Docker via Nesting für Wegwerf-Test-Container (z. B. pgvector in CI)
#
# Sicherheitsmodell: siehe Kopfkommentar in install/runner-install.sh —
# instanzweit + docker-Gruppe heißt: jedes Repo der Instanz kann diesen LXC
# kontrollieren. Akzeptiert, WEIL er nichts besitzt. Nicht auf privilegierte
# LXCs übertragen.
#
# Run on a Proxmox VE host:
# bash -c "$(curl -fsSL https://gitea.luki-net.org/luki-net/proxmox-scripts/raw/branch/main/ct/runner.sh)"
set -euo pipefail
APP="runner"
APP_DESCRIPTION="Allgemeiner Gitea-Actions-Runner (instanzweit, Label homelab, Docker, ohne Deploy-Rechte)"
LIB_URL="${LIB_URL:-https://gitea.luki-net.org/luki-net/proxmox-scripts/raw/branch/main/lib}"
INSTALL_SCRIPT_URL="${INSTALL_SCRIPT_URL:-https://gitea.luki-net.org/luki-net/proxmox-scripts/raw/branch/main/install/runner-install.sh}"
source <(curl -fsSL "$LIB_URL/build.func")
DEFAULT_HOSTNAME="runner"
DEFAULT_DISK="30"
DEFAULT_CORES="4"
DEFAULT_RAM="6144"
# ── Validierung (Review-Finding 80): Werte wandern in die Deploy-Env und in
# systemd/argv — strikte Zeichenklassen, Re-Prompt statt Abbruch.
# Bewusst LOKALE Validatoren: die Libs werden zur Laufzeit von main geladen,
# dieses Script muss aber unabhängig vom Merge-Stand der K-114-Helfer
# (prompt_validated/require_valid) funktionieren. Semantik ist identisch;
# Konsolidierung auf die build.func-Helfer ist als Follow-up notiert. ──────
_valid_url() { [[ "$1" =~ ^https?://[A-Za-z0-9.-]+(:[0-9]{1,5})?$ ]]; }
_valid_token() { [[ "$1" =~ ^[A-Za-z0-9_-]{16,128}$ ]]; }
_valid_word() { [[ "$1" =~ ^[A-Za-z0-9._:,-]+$ ]]; }
_prompt_until_valid() { # var prompt default validator secret(0|1)
local __var="$1" __prompt="$2" __default="$3" __validator="$4" __secret="${5:-0}" __val
while true; do
if [[ "$__secret" == "1" ]]; then
read -rsp "$__prompt" __val || { echo; msg_err "Eingabe abgebrochen (EOF)"; exit 1; }
echo
else
read -rp "$__prompt" __val || { echo; msg_err "Eingabe abgebrochen (EOF)"; exit 1; }
fi
__val="${__val:-$__default}"
if [[ -n "$__val" ]] && "$__validator" "$__val"; then
printf -v "$__var" '%s' "$__val"
return 0
fi
msg_warn "Ungültige Eingabe — bitte erneut (kein Paste mit Sonderzeichen)."
done
}
prompt_app_config() {
echo
echo "── Runner configuration ─────────────────────────────────────"
# env-präsetzte Werte werden validiert (Abbruch bei ungültig — K-114-Konvention),
# interaktive Eingaben re-prompten bis gültig.
if [[ -n "${GITEA_INSTANCE_URL:-}" ]]; then
_valid_url "$GITEA_INSTANCE_URL" || { msg_err "GITEA_INSTANCE_URL (env) ungültig"; exit 1; }
else
_prompt_until_valid GITEA_INSTANCE_URL \
"Gitea instance URL [https://gitea.luki-net.org]: " \
"https://gitea.luki-net.org" _valid_url 0
fi
# WICHTIG: den INSTANZWEITEN Token verwenden
# (Site Administration → Actions → Runners → Create new runner),
# NICHT den Repo-Token — sonst wiederholt sich der K-114-Scope-Blocker.
if [[ -n "${RUNNER_TOKEN:-}" ]]; then
_valid_token "$RUNNER_TOKEN" || { msg_err "RUNNER_TOKEN (env) ungültig (16128 Zeichen [A-Za-z0-9_-])"; exit 1; }
else
_prompt_until_valid RUNNER_TOKEN \
"INSTANZWEITER Runner-Registration-Token: " \
"" _valid_token 1
fi
RUNNER_NAME="${RUNNER_NAME:-$CT_HOSTNAME}"
RUNNER_LABELS="${RUNNER_LABELS:-homelab:host}"
RUNNER_VERSION="${RUNNER_VERSION:-0.2.13}"
NODE_MAJOR="${NODE_MAJOR:-22}"
_valid_word "$RUNNER_NAME" || { msg_err "RUNNER_NAME ungültig"; exit 1; }
_valid_word "$RUNNER_LABELS" || { msg_err "RUNNER_LABELS ungültig"; exit 1; }
[[ "$RUNNER_VERSION" =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]] || { msg_err "RUNNER_VERSION ungültig"; exit 1; }
[[ "$NODE_MAJOR" =~ ^[0-9]+$ ]] || { msg_err "NODE_MAJOR ungültig"; exit 1; }
echo " → instance: $GITEA_INSTANCE_URL"
echo " → runner: $RUNNER_NAME labels: $RUNNER_LABELS (act_runner $RUNNER_VERSION, host mode, scope: INSTANZ)"
}
push_app_config() {
msg_info "Pushing runner config into container..."
local tmpf; tmpf=$(mktemp)
# Werte sind oben strikt validiert (keine Quotes/Whitespace möglich) —
# damit ist die env-Datei frei von Quoting-/Injection-Fallen (vgl. Finding 76).
cat >"$tmpf" <<EOF
GITEA_INSTANCE_URL=$GITEA_INSTANCE_URL
RUNNER_TOKEN=$RUNNER_TOKEN
RUNNER_NAME=$RUNNER_NAME
RUNNER_LABELS=$RUNNER_LABELS
RUNNER_VERSION=$RUNNER_VERSION
NODE_MAJOR=$NODE_MAJOR
EOF
pct push "$CTID" "$tmpf" /root/runner.deploy.env --perms 600
rm -f "$tmpf"
}
# Docker im unprivilegierten LXC braucht nesting+keyctl (Test-Container in CI).
enable_nesting() {
msg_info "Enabling nesting+keyctl features (Docker für CI-Test-Container)..."
pct set "$CTID" --features nesting=1,keyctl=1
pct reboot "$CTID"
for _ in $(seq 1 30); do
pct exec "$CTID" -- true >/dev/null 2>&1 && break
sleep 2
done
msg_ok "Container restarted with nesting enabled"
}
print_app_summary() {
local runner_state
runner_state=$(pct exec "$CTID" -- systemctl is-active act-runner.service 2>/dev/null | tr -d '\r\n')
cat <<EOF
Gitea-Actions-Runner: $RUNNER_NAME [$RUNNER_LABELS] — $runner_state
Scope: INSTANZWEIT — bedient alle Repos der Instanz
Mode: host (Docker verfügbar für Test-Container)
Sicherheit: kein sudoers, keine Deploy-Rechte, keine Produktions-Mounts
(Modell: siehe install/runner-install.sh Kopfkommentar)
Verify: $GITEA_INSTANCE_URL → Site Administration → Actions → Runners
Workflows anderer Repos nutzen: runs-on: ${RUNNER_LABELS%%:*}
(Deploy-Jobs von nexus bleiben auf dem nexus-LXC-Runner, Label "nexus".)
Logs: pct exec $CTID -- journalctl -u act-runner -f
EOF
}
trap _on_error ERR
preflight_pve
show_header "$APP" "$APP_DESCRIPTION"
prompt_lxc_config
prompt_app_config
resolve_debian_template
create_lxc
enable_nesting
push_app_config
bootstrap_install_script "$INSTALL_SCRIPT_URL"
print_summary
-196
View File
@@ -1,196 +0,0 @@
#!/usr/bin/env bash
# Runner installer — runs inside the LXC, called by ct/runner.sh
#
# Allgemeiner, INSTANZWEITER Gitea-Actions-Runner ohne Deploy-Rechte:
# - Node.js (für actions/checkout im Host-Mode) + git + rsync
# - Docker (für Wegwerf-Test-Container in CI, z. B. pgvector)
# - act_runner als unprivilegierter User "runner" in der docker-Gruppe
# - systemd-Unit act-runner.service (Requires=docker.service)
#
# SICHERHEITSMODELL (Review-Finding 88, bewusst akzeptiert & dokumentiert):
# docker-Gruppe == de-facto root IN DIESEM LXC. Da der Runner instanzweit
# ist, kann jedes Repo der Gitea-Instanz via Workflow den Runner-Container
# vollständig kontrollieren. Das ist hier akzeptiert, weil (a) alle Repos
# der Instanz vom selben Admin (Lutz) stammen — kein Multi-Tenant — und
# (b) dieser LXC GENAU DESHALB nichts besitzt: keine sudoers, keine
# Produktions-Mounts, keine Secrets außer dem (geshredderten) Reg-Token.
# Bei Öffnung der Instanz für Dritte: Docker rootless oder eigener Runner
# pro Vertrauenszone. NICHT auf LXCs mit Deploy-Rechten übertragen.
#
# Idempotent: erneuter Lauf (auch OHNE /root/runner.deploy.env) überspringt
# Vorhandenes und provisioniert nur nach — Registrierung braucht die env-Datei
# nur beim Erstlauf (Finding 90).
set -euo pipefail
LIB_URL="${LIB_URL:-https://gitea.luki-net.org/luki-net/proxmox-scripts/raw/branch/main/lib}"
source <(curl -fsSL "$LIB_URL/install.func")
[[ "$EUID" -eq 0 ]] || { msg_err "Must run as root"; exit 1; }
APP_USER="runner"
APP_HOME="/opt/runner"
RUNNER_DIR="$APP_HOME/data"
# ── Konfiguration laden (optional bei Re-Run, Finding 90) ─────────────────────
CONF="/root/runner.deploy.env"
if [[ -f "$CONF" ]]; then
set -a; . "$CONF"; set +a
fi
RUNNER_NAME="${RUNNER_NAME:-$(hostname)}"
RUNNER_LABELS="${RUNNER_LABELS:-homelab:host}"
RUNNER_VERSION="${RUNNER_VERSION:-0.2.13}"
NODE_MAJOR="${NODE_MAJOR:-22}"
# ── Validierung (Finding 80): Werte landen in Shell-Fragmenten/systemd —
# strikte Zeichenklassen statt Vertrauen. Re-Runs ohne CONF validieren
# nur, was gesetzt ist; Registrierungs-Pflichtwerte prüft der Reg-Block. ──
valid_url() { [[ "$1" =~ ^https?://[A-Za-z0-9.-]+(:[0-9]{1,5})?$ ]]; }
valid_token() { [[ "$1" =~ ^[A-Za-z0-9_-]{16,128}$ ]]; }
valid_token_word() { [[ "$1" =~ ^[A-Za-z0-9._:,-]+$ ]]; }
[[ -z "${GITEA_INSTANCE_URL:-}" ]] || valid_url "$GITEA_INSTANCE_URL" \
|| { msg_err "GITEA_INSTANCE_URL ungültig: nur http(s)://host[:port]"; exit 1; }
[[ -z "${RUNNER_TOKEN:-}" ]] || valid_token "$RUNNER_TOKEN" \
|| { msg_err "RUNNER_TOKEN ungültig (erwartet 16128 Zeichen [A-Za-z0-9_-])"; exit 1; }
valid_token_word "$RUNNER_NAME" || { msg_err "RUNNER_NAME enthält unzulässige Zeichen"; exit 1; }
valid_token_word "$RUNNER_LABELS" || { msg_err "RUNNER_LABELS enthält unzulässige Zeichen"; exit 1; }
[[ "$RUNNER_VERSION" =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]] || { msg_err "RUNNER_VERSION ungültig"; exit 1; }
[[ "$NODE_MAJOR" =~ ^[0-9]+$ ]] || { msg_err "NODE_MAJOR ungültig"; exit 1; }
# Finding 85 (Re-Review): act_runner schreibt .runner ins CWD — run_user wechselt
# deshalb hart ins RUNNER_DIR (env -C), sonst landet die Registrierung in / und
# der unprivilegierte User darf dort nicht schreiben.
run_user() { runuser -u "$APP_USER" -- env -C "$RUNNER_DIR" HOME="$APP_HOME" "$@"; }
# ── Pakete: git/rsync, Node (checkout-Action), Docker (Test-Container) ────────
setup_base_apt git rsync ca-certificates curl
NODE_HAVE="$(command -v node >/dev/null 2>&1 && node -v | sed -E 's/^v([0-9]+).*/\1/' || echo 0)"
if [[ "$NODE_HAVE" != "$NODE_MAJOR" ]]; then
msg_info "Installing Node.js ${NODE_MAJOR}.x (NodeSource)..."
curl -fsSL "https://deb.nodesource.com/setup_${NODE_MAJOR}.x" | bash - >/dev/null
apt-get install -y -qq nodejs >/dev/null
msg_ok "Node $(node -v) installed"
else
msg_warn "Node $(node -v) already present, skipping"
fi
if ! command -v docker >/dev/null 2>&1; then
msg_info "Installing Docker (get.docker.com)..."
curl -fsSL https://get.docker.com | sh >/dev/null
msg_ok "Docker $(docker --version | awk '{print $3}' | tr -d ',')"
else
msg_warn "Docker already present, skipping"
fi
# ── act_runner binary ─────────────────────────────────────────────────────────
if [[ ! -x /usr/local/bin/act_runner ]]; then
ARCH="$(dpkg --print-architecture)"
case "$ARCH" in amd64|arm64) ;; *) msg_err "unsupported arch: $ARCH"; exit 1 ;; esac
msg_info "Downloading act_runner $RUNNER_VERSION ($ARCH)..."
curl -fsSL "https://dl.gitea.com/act_runner/${RUNNER_VERSION}/act_runner-${RUNNER_VERSION}-linux-${ARCH}" \
-o /usr/local/bin/act_runner
chmod +x /usr/local/bin/act_runner
msg_ok "act_runner $(/usr/local/bin/act_runner --version 2>/dev/null | head -n1)"
else
msg_warn "act_runner already present, skipping download"
fi
# ── User (docker-Gruppe VOR dem Daemon-Start — Lesson aus nexus K-103:
# Gruppenmitgliedschaften werden beim Prozessstart eingefroren) ─────────────
create_system_user "$APP_USER" "$APP_HOME"
usermod -aG docker "$APP_USER"
mkdir -p "$RUNNER_DIR"
chown -R "$APP_USER:$APP_USER" "$APP_HOME"
# ── Registrierung (idempotent; braucht CONF-Werte nur beim Erstlauf) ──────────
if [[ ! -f "$RUNNER_DIR/.runner" ]]; then
: "${GITEA_INSTANCE_URL:?missing GITEA_INSTANCE_URL (Erstlauf braucht /root/runner.deploy.env)}"
: "${RUNNER_TOKEN:?missing RUNNER_TOKEN (Erstlauf braucht /root/runner.deploy.env)}"
msg_info "Registering runner '$RUNNER_NAME' [$RUNNER_LABELS] with $GITEA_INSTANCE_URL (instance scope)..."
# Werte sind oben strikt validiert (keine Quotes/Whitespace möglich) —
# Übergabe als argv an runuser, keine erneute Shell-Interpolation (vgl. Finding 76).
# CWD = RUNNER_DIR via run_user (Finding 85).
run_user /usr/local/bin/act_runner register \
--no-interactive \
--config /dev/null \
--instance "$GITEA_INSTANCE_URL" \
--token "$RUNNER_TOKEN" \
--name "$RUNNER_NAME" \
--labels "$RUNNER_LABELS" \
2>&1 | sed "s#$RUNNER_TOKEN#<redacted>#g" || { msg_err "Registrierung fehlgeschlagen"; exit 1; }
# Belt-and-suspenders: falls eine künftige act_runner-Version doch ins HOME schreibt
if [[ -f "$APP_HOME/.runner" && ! -f "$RUNNER_DIR/.runner" ]]; then
mv "$APP_HOME/.runner" "$RUNNER_DIR/.runner"
fi
[[ -f "$RUNNER_DIR/.runner" ]] || { msg_err ".runner nach Registrierung nicht gefunden"; exit 1; }
chown -R "$APP_USER:$APP_USER" "$RUNNER_DIR"
msg_ok "Runner registered"
else
msg_warn "Runner already registered (.runner exists), skipping"
fi
# ── SSH-Root-Login-Policy anwenden, falls vom Host-Script übergeben
# (Funktion existiert in install.func ab K-114/PR #5 — guarded Aufruf,
# damit dieser Branch vor und nach dem Merge funktioniert) ────────────────
if declare -F configure_ssh_root_login >/dev/null 2>&1; then
configure_ssh_root_login
fi
# ── systemd-Unit (bewusst KEINE sudoers-Datei; Findings 82 + 70) ──────────────
cat >/etc/systemd/system/act-runner.service <<EOF
[Unit]
Description=Gitea Actions runner (instance-wide, label ${RUNNER_LABELS%%:*}, no deploy rights)
After=network-online.target docker.service
Wants=network-online.target
# Finding 82: ohne Docker keine Jobs annehmen — harte Kopplung
Requires=docker.service
[Service]
Type=simple
User=$APP_USER
Group=$APP_USER
WorkingDirectory=$RUNNER_DIR
Environment=HOME=$APP_HOME
Environment=PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
ExecStart=/usr/local/bin/act_runner daemon
Restart=on-failure
RestartSec=5
# Finding 70: Basis-Härtung (docker-CLI über Socket bleibt funktional)
NoNewPrivileges=true
PrivateTmp=true
[Install]
WantedBy=multi-user.target
EOF
systemctl daemon-reload
systemctl enable --now act-runner.service
msg_ok "act-runner.service installed + started"
CRED_FILE="/root/runner.credentials"
cat >"$CRED_FILE" <<EOF
Allgemeiner Gitea-Actions-Runner (instanzweit)
Instance: ${GITEA_INSTANCE_URL:-<bestehende Registrierung, siehe $RUNNER_DIR/.runner>}
Name/Label: $RUNNER_NAME [$RUNNER_LABELS]
User: $APP_USER (docker-Gruppe, KEIN sudo)
Workdir: $RUNNER_DIR
Logs: journalctl -u act-runner -f
Repos nutzen ihn mit: runs-on: ${RUNNER_LABELS%%:*}
SICHERHEITSMODELL: docker-Gruppe == de-facto root in DIESEM LXC; instanzweit
heißt: jedes Repo der Instanz kann den Runner-LXC kontrollieren. Akzeptiert,
weil Single-Admin-Instanz und dieser LXC nichts besitzt (keine sudoers, keine
Produktions-Mounts). Deploy-Jobs gehören NICHT hierher — die bleiben auf dem
repo-scoped nexus-Runner. Trennung beibehalten.
EOF
chmod 600 "$CRED_FILE"
if [[ -f "$CONF" ]]; then
shred -u "$CONF" 2>/dev/null || rm -f "$CONF"
fi
apt_cleanup
msg_ok "runner installation finished"
+170 -25
View File
@@ -97,55 +97,194 @@ apply_network_profile() {
return 0
}
# ── input validation (K-114) ─────────────────────────────────────────────────
# Real incident 2026-06-11: a pasted VLAN tag carried an invisible non-UTF-8
# byte and broke `pct create` deep in the run. Policy: trim CR/edge whitespace,
# but NEVER silently strip junk inside a value — embedded control/non-ASCII
# bytes fail validation and trigger a visible re-prompt.
# Trim \r and leading/trailing whitespace (edges only).
sanitize_input() {
local s="${1-}"
s="${s//$'\r'/}"
s="${s#"${s%%[![:space:]]*}"}"
s="${s%"${s##*[![:space:]]}"}"
printf '%s' "$s"
}
# True if the value contains only printable ASCII (no control/non-ASCII
# bytes). Byte-exact via tr: delete all printable ASCII — anything left
# over is junk.
is_clean_ascii() {
# Newline/Tab zuerst explizit ablehnen — $(…) strippt trailing newlines,
# die der tr-Pfad sonst übersehen würde (Review-Finding K-114).
[[ "$1" == *$'\n'* || "$1" == *$'\t'* ]] && return 1
local leftover
leftover="$(printf '%s' "$1" | LC_ALL=C tr -d '\40-\176')"
[[ -z "$leftover" ]]
}
is_uint() { is_clean_ascii "$1" && [[ "$1" =~ ^[0-9]+$ ]]; }
# 10#: führende Nullen nicht als Oktal werten ("08" wäre sonst ein
# Arithmetik-Fehler statt einer sauberen Ablehnung/Annahme).
is_vlan_tag() { is_uint "$1" && (( 10#$1 >= 1 && 10#$1 <= 4094 )); }
is_token() { is_clean_ascii "$1" && [[ "$1" =~ ^[A-Za-z0-9._-]+$ ]]; }
is_hostname() { is_clean_ascii "$1" && [[ "$1" =~ ^[A-Za-z0-9]([A-Za-z0-9-]{0,61}[A-Za-z0-9])?$ ]]; }
is_ipv4() {
is_clean_ascii "$1" && [[ "$1" =~ ^([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$ ]] || return 1
local o
for o in "${BASH_REMATCH[@]:1:4}"; do (( 10#$o <= 255 )) || return 1; done
return 0
}
is_cidr() {
[[ "$1" =~ ^([0-9.]+)/([0-9]{1,2})$ ]] || return 1
# BASH_REMATCH retten — is_ipv4 nutzt selbst =~ und überschreibt es.
local _ip="${BASH_REMATCH[1]}" _prefix="${BASH_REMATCH[2]}"
is_ipv4 "$_ip" && (( 10#$_prefix >= 1 && 10#$_prefix <= 32 ))
}
is_ipcfg() { [[ "$1" == "dhcp" ]] || is_cidr "$1"; }
# Space/comma-separated list of IPv4s (DNS prompt). Gesamtstring zuerst
# prüfen — die Wort-Splittung würde eingebettete Newlines sonst verstecken.
is_ipv4_list() {
is_clean_ascii "$1" || return 1
local item
for item in ${1//,/ }; do is_ipv4 "$item" || return 1; done
[[ -n "$1" ]]
}
# prompt_validated VARNAME PROMPT VALIDATOR [DEFAULT] [allow_empty]
# Reads into VARNAME (nameref, no subshell), sanitizes, applies the default on
# empty input and re-prompts until the validator passes. allow_empty=yes lets
# an empty value through (e.g. "no VLAN").
prompt_validated() {
# Schutz vor zirkulärem nameref (Review-Finding): interne Namen tabu.
[[ "$1" == _pv_* || "$1" == _rv_* ]] && { msg_err "prompt_validated: reserved variable name '$1'"; return 2; }
local -n _pv_ref="$1"
local _pv_prompt="$2" _pv_validator="$3" _pv_default="${4-}" _pv_allow_empty="${5:-no}"
local _pv_value
while true; do
if ! read -rp "$_pv_prompt" _pv_value; then
# EOF (kein TTY / stdin erschöpft): kein Endlos-Loop, sauber raus —
# unter set -e bricht der Caller damit kontrolliert ab.
msg_err "No input available for prompt: ${_pv_prompt%% *}"
return 1
fi
_pv_value="$(sanitize_input "$_pv_value")"
if [[ -z "$_pv_value" && -n "$_pv_default" ]]; then
_pv_value="$_pv_default"
fi
if [[ -z "$_pv_value" ]]; then
if [[ "$_pv_allow_empty" == "yes" ]]; then _pv_ref=""; return 0; fi
msg_warn "A value is required."
continue
fi
if "$_pv_validator" "$_pv_value"; then
_pv_ref="$_pv_value"
return 0
fi
if ! is_clean_ascii "$_pv_value"; then
msg_warn "Input contains invisible/non-ASCII characters — please re-type (do not paste)."
else
msg_warn "Invalid value: '$_pv_value' — please retry."
fi
done
}
# Validate an env-provided value (non-interactive: abort instead of re-prompt).
require_valid() {
[[ "$1" == _pv_* || "$1" == _rv_* ]] && { msg_err "require_valid: reserved variable name '$1'"; return 2; }
local -n _rv_ref="$1"
local _rv_validator="$2" _rv_label="$3"
_rv_ref="$(sanitize_input "$_rv_ref")"
"$_rv_validator" "$_rv_ref" || { msg_err "$_rv_label invalid: '$_rv_ref'"; exit 1; }
}
# ── prompts ──────────────────────────────────────────────────────────────────
# Each prompt is skipped if the corresponding variable is already set in env.
# Each prompt is skipped if the corresponding variable is already set in env
# (env values are still validated — abort on invalid, no silent use).
# VLAN_TAG and NAMESERVER use ${VAR+x} so that explicitly setting them to ""
# via env skips the prompt (= "no VLAN" / "inherit DNS from host").
prompt_lxc_config() {
if [[ -z "${CTID:-}" ]]; then
read -rp "Container ID [auto]: " CTID
[[ -z "${CTID:-}" ]] && CTID=$(pvesh get /cluster/nextid)
# Eigener Loop statt prompt_validated: leer = auto (pvesh nextid),
# ungültig = Re-Prompt (Review-Finding: vorher Abbruch statt Re-Prompt).
while true; do
if ! read -rp "Container ID [auto]: " CTID; then
msg_err "No input available for prompt: Container ID"
return 1
fi
CTID="$(sanitize_input "$CTID")"
if [[ -z "$CTID" ]]; then
CTID=$(pvesh get /cluster/nextid)
break
fi
is_uint "$CTID" && break
msg_warn "Invalid value: '$CTID' — please retry (digits only)."
done
else
require_valid CTID is_uint "Container ID"
fi
echo " → CTID: $CTID"
if [[ -z "${CT_HOSTNAME:-}" ]]; then
read -rp "Hostname [$DEFAULT_HOSTNAME]: " CT_HOSTNAME
CT_HOSTNAME="${CT_HOSTNAME:-$DEFAULT_HOSTNAME}"
prompt_validated CT_HOSTNAME "Hostname [$DEFAULT_HOSTNAME]: " is_hostname "$DEFAULT_HOSTNAME"
else
require_valid CT_HOSTNAME is_hostname "Hostname"
fi
if [[ -z "${DISK_SIZE:-}" ]]; then
read -rp "Disk size in GB [$DEFAULT_DISK]: " DISK_SIZE
DISK_SIZE="${DISK_SIZE:-$DEFAULT_DISK}"
prompt_validated DISK_SIZE "Disk size in GB [$DEFAULT_DISK]: " is_uint "$DEFAULT_DISK"
else
require_valid DISK_SIZE is_uint "Disk size"
fi
if [[ -z "${CORES:-}" ]]; then
read -rp "vCPU cores [$DEFAULT_CORES]: " CORES
CORES="${CORES:-$DEFAULT_CORES}"
prompt_validated CORES "vCPU cores [$DEFAULT_CORES]: " is_uint "$DEFAULT_CORES"
else
require_valid CORES is_uint "vCPU cores"
fi
if [[ -z "${RAM:-}" ]]; then
read -rp "RAM in MB [$DEFAULT_RAM]: " RAM
RAM="${RAM:-$DEFAULT_RAM}"
prompt_validated RAM "RAM in MB [$DEFAULT_RAM]: " is_uint "$DEFAULT_RAM"
else
require_valid RAM is_uint "RAM"
fi
if [[ -z "${BRIDGE:-}" ]]; then
read -rp "Bridge [$DEFAULT_BRIDGE]: " BRIDGE
BRIDGE="${BRIDGE:-$DEFAULT_BRIDGE}"
prompt_validated BRIDGE "Bridge [$DEFAULT_BRIDGE]: " is_token "$DEFAULT_BRIDGE"
else
require_valid BRIDGE is_token "Bridge"
fi
if [[ -z "${VLAN_TAG+x}" ]]; then
read -rp "VLAN tag (empty for none): " VLAN_TAG
# The 2026-06-11 incident prompt: junk bytes re-prompt, empty = no VLAN.
prompt_validated VLAN_TAG "VLAN tag (empty for none): " is_vlan_tag "" yes
elif [[ -n "${VLAN_TAG:-}" ]]; then
require_valid VLAN_TAG is_vlan_tag "VLAN tag"
fi
if [[ -z "${TEMPLATE_STORAGE:-}" ]]; then
read -rp "Template storage [$DEFAULT_TEMPLATE_STORAGE]: " TEMPLATE_STORAGE
TEMPLATE_STORAGE="${TEMPLATE_STORAGE:-$DEFAULT_TEMPLATE_STORAGE}"
prompt_validated TEMPLATE_STORAGE \
"Template storage [$DEFAULT_TEMPLATE_STORAGE]: " is_token "$DEFAULT_TEMPLATE_STORAGE"
else
require_valid TEMPLATE_STORAGE is_token "Template storage"
fi
if [[ -z "${ROOTFS_STORAGE:-}" ]]; then
read -rp "Rootfs storage [$DEFAULT_ROOTFS_STORAGE]: " ROOTFS_STORAGE
ROOTFS_STORAGE="${ROOTFS_STORAGE:-$DEFAULT_ROOTFS_STORAGE}"
prompt_validated ROOTFS_STORAGE \
"Rootfs storage [$DEFAULT_ROOTFS_STORAGE]: " is_token "$DEFAULT_ROOTFS_STORAGE"
else
require_valid ROOTFS_STORAGE is_token "Rootfs storage"
fi
if [[ -z "${IPCFG:-}" ]]; then
read -rp "Network: IP/CIDR or 'dhcp' [dhcp]: " IPCFG
IPCFG="${IPCFG:-dhcp}"
prompt_validated IPCFG "Network: IP/CIDR or 'dhcp' [dhcp]: " is_ipcfg "dhcp"
else
require_valid IPCFG is_ipcfg "Network (IP/CIDR or dhcp)"
fi
GATEWAY="${GATEWAY:-}"
if [[ "$IPCFG" != "dhcp" && -z "$GATEWAY" ]]; then
read -rp "Gateway: " GATEWAY
if [[ "$IPCFG" != "dhcp" ]]; then
if [[ -z "$GATEWAY" ]]; then
prompt_validated GATEWAY "Gateway: " is_ipv4
else
require_valid GATEWAY is_ipv4 "Gateway"
fi
fi
# DNS is driven by the VLAN tag via the network profile (lib/networks.conf),
# so the right resolvers get set even with DHCP. Precedence:
@@ -155,14 +294,20 @@ prompt_lxc_config() {
# 4. DHCP, no profile → inherit from host
apply_network_profile
if [[ -n "${NAMESERVER+x}" ]]; then
: # explicit override from env, leave untouched
# Explizites Override aus env: "" = inherit bleibt erlaubt, aber ein
# gesetzter Wert wird validiert (Review-Finding: lief vorher ungeprüft
# bis in pct create).
if [[ -n "${NAMESERVER:-}" ]]; then
require_valid NAMESERVER is_ipv4_list "DNS server"
fi
elif [[ -n "$PROFILE_DNS" ]]; then
NAMESERVER="$PROFILE_DNS"
msg_info "DNS for VLAN ${VLAN_TAG:-none} (${PROFILE_SUBNET:-?}): $NAMESERVER"
elif [[ "$IPCFG" != "dhcp" ]]; then
local default_ns="${DEFAULT_NAMESERVER:-$GATEWAY}"
read -rp "DNS server [$default_ns] (empty = inherit from PVE host): " NAMESERVER
NAMESERVER="${NAMESERVER:-$default_ns}"
prompt_validated NAMESERVER \
"DNS server [$default_ns] (empty = inherit from PVE host): " \
is_ipv4_list "$default_ns" yes
else
msg_warn "No network profile for VLAN ${VLAN_TAG:-none}; DHCP DNS will be inherited."
fi
+30
View File
@@ -0,0 +1,30 @@
#!/usr/bin/env bash
# K-114: Jedes ct/*.sh MUSS lib/build.func sourcen — der Bug "Helfer nicht
# gesourct, Skript stirbt erst mitten im Lauf" ist zweimal real passiert
# (nexus-db: im Review gefangen; authentik: erst in Produktion).
# Aufruf: tests/check_ct_source.sh [verzeichnis] (Default: ct/)
#
# Bewusst eng: akzeptiert wird NUR die curl-Prozesssubstitutions-Form
# `source <(curl ... build.func)` — das ist der Repo-Vertrag für ct/-Scripts
# (Review-Triage K-114). Lokales Sourcen gehört nicht in ct/*.sh.
set -euo pipefail
DIR="${1:-$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)/ct}"
status=0
shopt -s nullglob
scripts=("$DIR"/*.sh)
if [[ ${#scripts[@]} -eq 0 ]]; then
echo "no scripts found in $DIR" >&2
exit 1
fi
for script in "${scripts[@]}"; do
if grep -Eq 'source[[:space:]]+<\(curl[^)]*build\.func' "$script"; then
echo "ok $script"
else
echo "FEHLT $script — sourct lib/build.func nicht" >&2
status=1
fi
done
exit "$status"
+168
View File
@@ -0,0 +1,168 @@
#!/usr/bin/env bash
# K-114: Unit-Tests für die Input-Validierung in lib/build.func.
# Läuft ohne PVE (sourct nur die Helfer). Aufruf: bash tests/test_validation.sh
set -u
REPO_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
# shellcheck source=/dev/null
source "$REPO_ROOT/lib/build.func"
PASS=0
FAIL=0
ok() { PASS=$((PASS + 1)); echo "ok - $1"; }
nok() { FAIL=$((FAIL + 1)); echo "NOT OK - $1"; }
assert_true() { # assert_true "desc" cmd args...
local desc="$1"; shift
if "$@"; then ok "$desc"; else nok "$desc"; fi
}
assert_false() {
local desc="$1"; shift
if "$@"; then nok "$desc"; else ok "$desc"; fi
}
# ── Repro des Vorfalls vom 2026-06-11: VLAN-Tag mit unsichtbarem Byte ────────
JUNK_VLAN="$(printf '2\x800')" # "20" mit eingebettetem Non-UTF-8-Byte
assert_false "VLAN-Repro: '2<0x80>0' wird abgelehnt (kein silent strip)" is_vlan_tag "$JUNK_VLAN"
assert_false "is_clean_ascii erkennt eingebettetes Junk-Byte" is_clean_ascii "$JUNK_VLAN"
# Re-Prompt-Verhalten: erste Eingabe ist der Junk-Wert, zweite ist sauber —
# prompt_validated muss die zweite liefern (AC: Re-Prompt statt pct-Fehler).
reprompt_result="$(
printf '%s\n20\n' "$JUNK_VLAN" | {
VLAN=""
prompt_validated VLAN "VLAN tag (empty for none): " is_vlan_tag "" yes >/dev/null 2>&1
printf '%s' "$VLAN"
}
)"
if [[ "$reprompt_result" == "20" ]]; then
ok "prompt_validated re-promptet bei Junk und akzeptiert dann '20'"
else
nok "prompt_validated re-promptet bei Junk (got: '$reprompt_result')"
fi
# ── sanitize_input: CR + Rand-Whitespace weg, Inhalt unangetastet ─────────────
[[ "$(sanitize_input $' 42\r\n')" == "42" ]] && ok "sanitize_input trimmt CR/Whitespace" \
|| nok "sanitize_input trimmt CR/Whitespace"
[[ "$(sanitize_input "$JUNK_VLAN")" == "$JUNK_VLAN" ]] && ok "sanitize_input strippt KEIN eingebettetes Junk (Validator soll es sehen)" \
|| nok "sanitize_input lässt eingebettetes Junk unangetastet"
# ── numerische Validatoren ────────────────────────────────────────────────────
assert_true "is_uint akzeptiert 8" is_uint "8"
assert_false "is_uint lehnt '8 ' mit Junk ab" is_uint "$(printf '8\x01')"
assert_false "is_uint lehnt 'abc' ab" is_uint "abc"
assert_false "is_uint lehnt leeren Wert ab" is_uint ""
assert_true "is_vlan_tag akzeptiert 20" is_vlan_tag "20"
assert_false "is_vlan_tag lehnt 0 ab" is_vlan_tag "0"
assert_false "is_vlan_tag lehnt 5000 ab" is_vlan_tag "5000"
# ── Netz-Validatoren ──────────────────────────────────────────────────────────
assert_true "is_ipv4 akzeptiert 10.11.20.66" is_ipv4 "10.11.20.66"
assert_false "is_ipv4 lehnt 10.11.20.666 ab" is_ipv4 "10.11.20.666"
assert_false "is_ipv4 lehnt 10.11.20 ab" is_ipv4 "10.11.20"
assert_true "is_cidr akzeptiert 10.11.20.5/24" is_cidr "10.11.20.5/24"
assert_false "is_cidr lehnt 10.11.20.5/33 ab" is_cidr "10.11.20.5/33"
assert_false "is_cidr lehnt 10.11.20.5 ohne Maske" is_cidr "10.11.20.5"
assert_true "is_ipcfg akzeptiert dhcp" is_ipcfg "dhcp"
assert_true "is_ipcfg akzeptiert CIDR" is_ipcfg "192.168.0.7/24"
assert_false "is_ipcfg lehnt 'static' ab" is_ipcfg "static"
assert_true "is_ipv4_list akzeptiert Liste" is_ipv4_list "1.1.1.1, 8.8.8.8"
assert_false "is_ipv4_list lehnt Hostnamen ab" is_ipv4_list "dns.local"
# ── Namen/Token ───────────────────────────────────────────────────────────────
assert_true "is_hostname akzeptiert nexus-db" is_hostname "nexus-db"
assert_false "is_hostname lehnt '-bad' ab" is_hostname "-bad"
assert_false "is_hostname lehnt 'a b' ab" is_hostname "a b"
assert_true "is_token akzeptiert local-lvm" is_token "local-lvm"
assert_false "is_token lehnt 'a;b' ab" is_token "a;b"
# ── require_valid: env-Werte werden sanitisiert + geprüft ────────────────────
CHECKVAL=$' 7\r'
require_valid CHECKVAL is_uint "Testwert" && [[ "$CHECKVAL" == "7" ]] \
&& ok "require_valid sanitisiert env-Wert (CR weg)" \
|| nok "require_valid sanitisiert env-Wert"
( CHECKBAD="$JUNK_VLAN"; require_valid CHECKBAD is_uint "Testwert" ) >/dev/null 2>&1 \
&& nok "require_valid bricht bei Junk-env-Wert ab" \
|| ok "require_valid bricht bei Junk-env-Wert ab (exit != 0)"
# ── Negativ-Beweis: build.func-Source-Check schlägt bei Präparat an ──────────
TMPDIR_CT="$(mktemp -d)"
cat >"$TMPDIR_CT/broken.sh" <<'EOF'
#!/usr/bin/env bash
# absichtlich ohne source build.func (Repro des zweimal aufgetretenen Bugs)
APP="broken"
prompt_lxc_config
EOF
if bash "$REPO_ROOT/tests/check_ct_source.sh" "$TMPDIR_CT" >/dev/null 2>&1; then
nok "check_ct_source.sh erkennt fehlendes 'source build.func'"
else
ok "check_ct_source.sh erkennt fehlendes 'source build.func'"
fi
rm -rf "$TMPDIR_CT"
# Positiv: das echte ct/-Verzeichnis ist sauber.
if bash "$REPO_ROOT/tests/check_ct_source.sh" "$REPO_ROOT/ct" >/dev/null 2>&1; then
ok "alle ct/*.sh sourcen build.func"
else
nok "alle ct/*.sh sourcen build.func"
fi
# ── Review-Findings K-114: Oktal, Newline, EOF, Nameref-Guard ────────────────
assert_true "is_vlan_tag akzeptiert '08' (kein Oktal-Fehler)" is_vlan_tag "08"
assert_true "is_cidr akzeptiert /08 (kein Oktal-Fehler)" is_cidr "10.0.0.1/08"
assert_false "is_clean_ascii lehnt eingebettetes Newline ab" is_clean_ascii $'1.1.1.1\n8.8.8.8'
assert_false "is_ipv4_list lehnt Newline-Liste ab" is_ipv4_list $'1.1.1.1\n8.8.8.8'
# EOF statt Eingabe: prompt_validated darf nicht endlos loopen.
( printf '' | { V=""; prompt_validated V "Wert: " is_uint; } ) >/dev/null 2>&1
rc=$?
[[ "$rc" -ne 0 ]] && ok "prompt_validated bricht bei EOF ab (rc=$rc)" \
|| nok "prompt_validated bricht bei EOF ab"
# Reservierte Namen → Guard statt zirkulärem nameref.
( _pv_ref=""; prompt_validated _pv_ref "x: " is_uint ) >/dev/null 2>&1
[[ $? -eq 2 ]] && ok "prompt_validated weist reservierte Variablennamen ab" \
|| nok "prompt_validated weist reservierte Variablennamen ab"
# CTID-Re-Prompt: ungültig → erneut fragen, leer wäre auto (hier: gültige Zahl).
ctid_out="$(
printf 'abc\n123\n' | env -u CTID bash -c "
source '$REPO_ROOT/lib/build.func'
CTID=''
while true; do
read -rp 'Container ID [auto]: ' CTID || exit 1
CTID=\"\$(sanitize_input \"\$CTID\")\"
[[ -z \"\$CTID\" ]] && exit 1
is_uint \"\$CTID\" && break
done
printf '%s' \"\$CTID\""
)"
[[ "$ctid_out" == "123" ]] && ok "CTID-Loop re-promptet bei 'abc' und nimmt '123'" \
|| nok "CTID-Loop re-promptet (got: '$ctid_out')"
# ── Dry-Run: prompt_lxc_config komplett aus env, ohne PVE/TTY ────────────────
smoke_out="$(
env CTID=999 CT_HOSTNAME=smoke DISK_SIZE=8 CORES=2 RAM=1024 BRIDGE=vmbr0 \
VLAN_TAG=20 TEMPLATE_STORAGE=local ROOTFS_STORAGE=local-lvm \
IPCFG=10.11.20.99/24 GATEWAY=10.11.20.1 NAMESERVER="" \
NET_PROFILES_FILE="$REPO_ROOT/lib/networks.conf" \
bash -c "source '$REPO_ROOT/lib/build.func' && prompt_lxc_config >/dev/null && echo SMOKE-OK"
)" || true
[[ "$smoke_out" == *SMOKE-OK* ]] \
&& ok "prompt_lxc_config Dry-Run mit validen env-Werten läuft durch" \
|| nok "prompt_lxc_config Dry-Run (got: '$smoke_out')"
smoke_bad="$(
env CTID="$(printf '9\x809')" CT_HOSTNAME=smoke DISK_SIZE=8 CORES=2 RAM=1024 BRIDGE=vmbr0 \
VLAN_TAG=20 TEMPLATE_STORAGE=local ROOTFS_STORAGE=local-lvm IPCFG=dhcp NAMESERVER="" \
NET_PROFILES_FILE="$REPO_ROOT/lib/networks.conf" \
bash -c "source '$REPO_ROOT/lib/build.func' && prompt_lxc_config >/dev/null && echo SMOKE-OK" 2>/dev/null
)" || true
[[ "$smoke_bad" == *SMOKE-OK* ]] \
&& nok "prompt_lxc_config bricht bei Junk-CTID aus env ab" \
|| ok "prompt_lxc_config bricht bei Junk-CTID aus env ab"
echo
echo "passed=$PASS failed=$FAIL"
[[ "$FAIL" -eq 0 ]]