#!/bin/sh validate_secret_file() { secret_path=$1 secret_name=$2 if [ -L "$secret_path" ] || [ ! -f "$secret_path" ] || [ ! -r "$secret_path" ] || [ ! -s "$secret_path" ]; then echo "$secret_name must be a readable, non-empty regular file" >&2 return 2 fi if LC_ALL=C grep -q '[[:space:]]' "$secret_path"; then echo "$secret_name must contain no whitespace" >&2 return 2 fi mode=$(stat -c '%a' "$secret_path" 2>/dev/null || stat -f '%Lp' "$secret_path" 2>/dev/null) || return 2 case "$secret_path:$mode" in /run/secrets/*:444|/run/secrets/*:400|/run/secrets/*:600|*:600|*:400) ;; *) echo "$secret_name must have mode 0600 or stricter (Docker secrets may be 0444)" >&2; return 2 ;; esac } read_secret_file() { validate_secret_file "$1" "$2" || return cat "$1" } # Read one value from the deployment bundle without putting the bundle itself in # a service environment. The parser is deliberately strict: one KEY=VALUE per # line, no duplicate keys, no unknown syntax, and no whitespace in credentials. read_bundle_secret() { bundle_path=$1 bundle_key=$2 if [ -L "$bundle_path" ] || [ ! -f "$bundle_path" ] || [ ! -r "$bundle_path" ] || [ ! -s "$bundle_path" ]; then echo "secret bundle must be a readable, non-empty regular file" >&2 return 2 fi mode=$(stat -c '%a' "$bundle_path" 2>/dev/null || stat -f '%Lp' "$bundle_path" 2>/dev/null) || return 2 case "$bundle_path:$mode" in /run/secrets/*:444|/run/secrets/*:400|/run/secrets/*:600|*:600|*:400) ;; *) echo "secret bundle must have mode 0600 or stricter (Docker secrets may be 0444)" >&2; return 2 ;; esac case "$bundle_key" in THT_[A-Z0-9_]*|PI_PROVIDER_API_KEY) ;; *) echo "invalid secret bundle key" >&2; return 2 ;; esac value=$(awk -v wanted="$bundle_key" ' /^[[:space:]]*$/ || /^[[:space:]]*#/ { next } /^[A-Z][A-Z0-9_]*=/ { key=$0; sub(/=.*/, "", key) val=$0; sub(/^[^=]*=/, "", val) if (key !~ /^(THT_MODEL_API_KEY|THT_DWH_API_KEY|THT_VEC_API_KEY|THT_VEC_WRITE_API_KEY|THT_CA|THT_SSL_CA|THT_VECTOR_BOOTSTRAP_PASSWORD|THT_VECTOR_MIGRATOR_PASSWORD|THT_VECTOR_READER_PASSWORD|THT_VECTOR_WRITER_PASSWORD|PI_PROVIDER_API_KEY)$/) exit 6 if (val == "") exit 7 if (++seen[key] > 1) exit 8 if (key == wanted) { if (found) exit 3 found=1; print val } next } { exit 4 } END { if (!found) exit 5 } ' "$bundle_path") || { echo "$bundle_key is unavailable in secret bundle" >&2 return 2 } if [ -z "$value" ] || printf '%s' "$value" | LC_ALL=C grep -q '[[:space:]]'; then echo "$bundle_key must contain no whitespace" >&2 return 2 fi printf '%s' "$value" }