#!/bin/bash
set -euo pipefail
NODE_ID="669427"
RELAY_IP="10.69.69.1"
RELAY_PORT="8301"
KEY_PATH="/dev/shm/vault.key"
HMAC_KEY_FILE="/dev/shm/hmac.key"
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
check_tun_mesh() {
if ! ip link show tun0 >/dev/null 2>&1; then
echo "ERROR: tunnel interface not found"
exit 1
fi
local wg_state
wg_state=$(wg show tun0 latest-handshakes 2>/dev/null | awk '{print $2}')
if [ -z "$wg_state" ]; then
echo "ERROR: tunnel mesh not established"
exit 1
fi
local now
now=$(date +%s)
local age=$((now - wg_state))
if [ $age -gt 180 ]; then
echo "ERROR: wg7 handshake stale (${age}s)"
exit 1
fi
echo "tunnel mesh verified (handshake ${age}s ago)"
}
verify_key_not_on_disk() {
if [ -f "/opt/apache/engine/vault.key" ] || [ -f "/tmp/vault.key" ]; then
echo "WARNING: key found on persistent disk, removing"
rm -f /opt/apache/engine/vault.key /tmp/vault.key 2>/dev/null || true
fi
}
fetch_key_from_shield() {
if [ -f "$KEY_PATH" ]; then
echo "Vault key already in RAM"
return 0
fi
local TIMESTAMP NONCE PAYLOAD HMAC
TIMESTAMP=$(date +%s)
NONCE=$(openssl rand -hex 16)
PAYLOAD="FETCH_VAULT_KEY|${TIMESTAMP}|${NONCE}"
if [ ! -f "$HMAC_KEY_FILE" ]; then
echo "ERROR: HMAC key not available"
exit 1
fi
HMAC=$(echo -n "$PAYLOAD" | openssl dgst -sha256 -hmac "$(cat "$HMAC_KEY_FILE")" -binary | base64 -w0)
local RESPONSE
RESPONSE=$(curl -s --max-time 10 \
-H "X-Node: ${NODE_ID}" \
-H "X-Timestamp: ${TIMESTAMP}" \
-H "X-Nonce: ${NONCE}" \
-H "X-HMAC: ${HMAC}" \
"http://${RELAY_IP}:${RELAY_PORT}/vault/key" 2>/dev/null)
if [ -z "$RESPONSE" ] || [ "$RESPONSE" = "DENIED" ]; then
echo "ERROR: relay denied key fetch"
exit 1
fi
printf '%s' "$RESPONSE" > "$KEY_PATH"
chmod 600 "$KEY_PATH"
chown mail-svc:mail-svc "$KEY_PATH" 2>/dev/null || true
echo "Vault key loaded to RAM ($KEY_PATH)"
}
start_engine() {
echo "Starting engine..."
if [ -x "${SCRIPT_DIR}/engine" ]; then
exec "${SCRIPT_DIR}/engine" --start-engine
else
echo "ERROR: engine binary not found"
exit 1
fi
}
case "${1:-}" in
--start-engine)
check_tun_mesh
verify_key_not_on_disk
fetch_key_from_shield
start_engine
;;
--fetch-only)
check_tun_mesh
verify_key_not_on_disk
fetch_key_from_shield
;;
--verify-tunnel)
check_tun_mesh
;;
*)
echo "Usage: $0 [--start-engine|--fetch-only|--verify-tunnel]"
exit 1
;;
esac