Aller au contenu

Déployer Etherpad-lite multi-instance sur Ubuntu 22.04 (prêt pour la production)

Monter un Etherpad-lite durci sur Ubuntu 22.04 — backend PostgreSQL, SSO OAuth via ep_openid_connect, nginx + Let's Encrypt, données de pads persistantes.

Vous montez Etherpad-lite parce que l’équipe support veut un bloc-notes partagé pendant les incidents et que l’équipe docs veut une surface publique de brouillon pour les commentaires de RFC. Le quickstart Docker fonctionne, le premier pad s’ouvre, trois personnes commencent à taper. Six mois plus tard, la base SQLite livrée avec la config par défaut est dans un seul fichier monté dans le conteneur, le fichier a grossi à 2,4 Go, chaque sauvegarde flushe tout le journal, l’API d’import accepte toujours des PUT anonymes depuis l’internet public, les padIDs sont des chaînes devinables comme meeting, notes et roadmap, et il n’y a pas de SSO — chaque compte est un nom local avec un mot de passe partagé sur Slack au jour un. L’instance est en ligne, les données ne sont privées que parce que personne n’a encore essayé de deviner /p/roadmap.

Ce qui se passe

Le backend SQLite par défaut d’Etherpad-lite (dirty.db) convient pour une démo et pas pour la production — la contention en écriture sérialise chaque frappe dans un journal unique, et il n’existe pas de primitive de sauvegarde cohérente autre que l’arrêt du service. Le backend de production supporté est PostgreSQL via le driver ueberdb2 ; pads, révisions, chat et lignes d’autorisation vivent tous dans une table clé-valeur unique que le driver gère. Les identifiants de pad font partie de l’URL par conception ; sans requireAuthentication: true plus un plugin SSO, /p/<n'importe quoi> est un vrai pad que tout le monde peut lire. L’API HTTP a besoin d’un apikey.txt généré au premier démarrage et qui doit être persisté entre les redéploiements — le faire tourner invalide chaque pad embarqué. Le multi-tenant vient des sessions d’auteur et des group pads, pas de processus séparés ; une seule instance Etherpad peut héberger toutes les équipes si le plugin d’auth les scope correctement. Le plugin ep_openid_connect câble le SSO OIDC ; combinez-le avec requireAuthentication: true et l’autorisation se fait avant la création du pad.

Comment vérifier

La machine ne doit exposer que :443 et :22 :

ss -lntp | grep -E ':(80|443|9001|5432)\b'
# 0.0.0.0:443  nginx
# 127.0.0.1:9001  etherpad

PostgreSQL sur 5432 ne doit pas apparaître sur l’hôte. La création anonyme de pad doit échouer :

curl -sS -o /dev/null -w '%{http_code}\n' https://pad.example.com/p/random-test-pad
# 401 (avec requireAuthentication actif, avant SSO)

Les endpoints API doivent rejeter les appels sans la clé d’amorçage :

curl -sS https://pad.example.com/api/1.2.13/createPad?padID=test | jq .code
# 4 (apikey absente ou invalide)

Si /p/quoi-que-ce-soit retourne l’éditeur sans authentification, requireAuthentication est désactivé — activez-le avant que plus de pads ne soient créés.

Le correctif

Enregistrez le script ci-dessous sous /root/setup-etherpad-ubuntu22.sh, puis exécutez-le. Il installe Etherpad-lite sur une VM Ubuntu 22.04 propre sous un compte de service non-root, PostgreSQL 16 lié à localhost, les plugins ep_openid_connect et ep_set_title_on_pad, nginx terminant TLS avec les en-têtes d’upgrade websocket en place, certbot lié à un hook de rechargement, et une unité systemd avec des options de sandbox durcies.

#!/usr/bin/env bash
set -euo pipefail

### Ubuntu 22.04 Etherpad-lite clean VM installer
### PostgreSQL backend bound to 127.0.0.1
### OAuth SSO via ep_openid_connect
### Multi-pad config with requireAuthentication
### Persistent pad data in PostgreSQL; no SQLite
### No local backups; assumes pg_dump in VM-level backup window

if [[ "$(id -u)" -ne 0 ]]; then
  echo "Run as root."
  exit 1
fi

: "${ETHERPAD_DOMAIN:?Set ETHERPAD_DOMAIN=pad.example.com}"
: "${ETHERPAD_EMAIL:?Set ETHERPAD_EMAIL=ops@example.com for Let's Encrypt}"
: "${OIDC_ISSUER:?Set OIDC_ISSUER=https://idp.example.com}"
: "${OIDC_CLIENT_ID:?Set OIDC_CLIENT_ID=etherpad}"
: "${OIDC_CLIENT_SECRET:?Set OIDC_CLIENT_SECRET=...}"
ETHERPAD_VERSION="${ETHERPAD_VERSION:-2.2.6}"
ETHERPAD_USER="${ETHERPAD_USER:-etherpad}"
ETHERPAD_HOME="${ETHERPAD_HOME:-/opt/etherpad}"
PG_PASSWORD="${PG_PASSWORD:-$(openssl rand -hex 24)}"
ETHERPAD_APIKEY="${ETHERPAD_APIKEY:-$(openssl rand -hex 32)}"
ETHERPAD_SESSIONKEY="${ETHERPAD_SESSIONKEY:-$(openssl rand -hex 32)}"

echo
echo "========================================"
echo "Etherpad-lite Ubuntu 22.04 Setup"
echo "========================================"
echo "Domain: ${ETHERPAD_DOMAIN}"
echo "OIDC issuer: ${OIDC_ISSUER}"
echo

echo "==> Updating base OS"
export DEBIAN_FRONTEND=noninteractive
apt-get update
apt-get -y upgrade

echo "==> Installing base packages"
apt-get -y install \
  vim curl wget ca-certificates gnupg2 git \
  chrony fail2ban unattended-upgrades \
  ufw lsof tcpdump dnsutils tar gzip \
  iproute2 net-tools openssl jq build-essential \
  libtool automake software-properties-common

echo "==> Enabling time sync"
systemctl enable --now chrony

echo "==> Applying kernel/network tuning"
cat > /etc/sysctl.d/99-etherpad.conf <<'SYSCTL'
net.core.default_qdisc = fq
net.ipv4.tcp_congestion_control = bbr

net.core.somaxconn = 4096
net.core.netdev_max_backlog = 250000
net.ipv4.tcp_max_syn_backlog = 8192
net.ipv4.tcp_syncookies = 1
net.ipv4.tcp_fin_timeout = 15
net.ipv4.ip_local_port_range = 10240 65535

kernel.dmesg_restrict = 1
kernel.kptr_restrict = 2
fs.file-max = 2097152
vm.max_map_count = 262144
SYSCTL

modprobe tcp_bbr || true
echo tcp_bbr > /etc/modules-load.d/bbr.conf
sysctl --system

echo "==> Configuring UFW"
ufw --force reset
ufw default deny incoming
ufw default allow outgoing
ufw allow 22/tcp
ufw allow 80/tcp
ufw allow 443/tcp
ufw --force enable

echo "==> Hardening SSH while keeping root SSH key login enabled"
cp /etc/ssh/sshd_config /etc/ssh/sshd_config.bak.$(date +%F-%H%M%S)

set_sshd_option() {
  local key="$1" value="$2"
  if grep -qE "^[#[:space:]]*${key}[[:space:]]+" /etc/ssh/sshd_config; then
    sed -i "s|^[#[:space:]]*${key}[[:space:]].*|${key} ${value}|" /etc/ssh/sshd_config
  else
    echo "${key} ${value}" >> /etc/ssh/sshd_config
  fi
}

set_sshd_option PermitRootLogin prohibit-password
set_sshd_option PasswordAuthentication no
set_sshd_option PubkeyAuthentication yes
set_sshd_option X11Forwarding no
set_sshd_option ClientAliveInterval 300
set_sshd_option ClientAliveCountMax 2
set_sshd_option MaxAuthTries 4

sshd -t
systemctl restart ssh

echo "==> Configuring fail2ban"
mkdir -p /etc/fail2ban/jail.d
cat > /etc/fail2ban/jail.d/sshd.local <<'FAIL2BAN'
[sshd]
enabled = true
port = ssh
backend = systemd
maxretry = 4
findtime = 10m
bantime = 1h
FAIL2BAN
systemctl enable --now fail2ban

cat > /etc/apt/apt.conf.d/20auto-upgrades <<'AUTOUPG'
APT::Periodic::Update-Package-Lists "1";
APT::Periodic::Unattended-Upgrade "1";
APT::Periodic::AutocleanInterval "7";
AUTOUPG

echo "==> Installing Node.js 20 via NodeSource"
curl -fsSL https://deb.nodesource.com/setup_20.x | bash -
apt-get -y install nodejs

echo "==> Installing PostgreSQL 16"
install -m 0755 -d /etc/apt/keyrings
curl -fsSL https://www.postgresql.org/media/keys/ACCC4CF8.asc \
  | gpg --dearmor -o /etc/apt/keyrings/postgresql.gpg
echo "deb [arch=$(dpkg --print-architecture) signed-by=/etc/apt/keyrings/postgresql.gpg] http://apt.postgresql.org/pub/repos/apt jammy-pgdg main" \
  > /etc/apt/sources.list.d/pgdg.list
apt-get update
apt-get -y install postgresql-16

systemctl enable --now postgresql

echo "==> Binding PostgreSQL to localhost only"
PG_CONF="/etc/postgresql/16/main/postgresql.conf"
sed -i "s|^[#[:space:]]*listen_addresses.*|listen_addresses = '127.0.0.1'|" "${PG_CONF}"
systemctl reload postgresql

echo "==> Creating etherpad database + user"
sudo -u postgres psql <<SQL
CREATE USER etherpad WITH PASSWORD '${PG_PASSWORD}';
CREATE DATABASE etherpad OWNER etherpad ENCODING 'UTF8';
GRANT ALL PRIVILEGES ON DATABASE etherpad TO etherpad;
ALTER DATABASE etherpad SET timezone TO 'UTC';
SQL

echo "==> Creating etherpad service user"
if ! id "${ETHERPAD_USER}" >/dev/null 2>&1; then
  useradd --system --home-dir "${ETHERPAD_HOME}" --shell /usr/sbin/nologin "${ETHERPAD_USER}"
fi
mkdir -p "${ETHERPAD_HOME}"
chown "${ETHERPAD_USER}:${ETHERPAD_USER}" "${ETHERPAD_HOME}"

echo "==> Cloning Etherpad-lite ${ETHERPAD_VERSION}"
sudo -u "${ETHERPAD_USER}" git clone https://github.com/ether/etherpad-lite.git "${ETHERPAD_HOME}/src"
cd "${ETHERPAD_HOME}/src"
sudo -u "${ETHERPAD_USER}" git checkout "${ETHERPAD_VERSION}"

echo "==> Installing Etherpad dependencies"
sudo -u "${ETHERPAD_USER}" bin/installDeps.sh

echo "==> Installing plugins: ep_openid_connect, ep_set_title_on_pad"
sudo -u "${ETHERPAD_USER}" pnpm install --filter ep_etherpad-lite ep_openid_connect ep_set_title_on_pad

echo "==> Writing settings.json"
cat > "${ETHERPAD_HOME}/src/settings.json" <<EOF
{
  "title": "Etherpad",
  "favicon": null,
  "ip": "127.0.0.1",
  "port": 9001,
  "showSettingsInAdminPage": false,
  "dbType": "postgres",
  "dbSettings": {
    "user": "etherpad",
    "host": "127.0.0.1",
    "port": 5432,
    "password": "${PG_PASSWORD}",
    "database": "etherpad",
    "charset": "utf8mb4"
  },
  "defaultPadText": "Welcome — sign in via SSO and create a new pad.",
  "padOptions": {
    "noColors": false,
    "showControls": true,
    "showChat": true,
    "showLineNumbers": true,
    "useMonospaceFont": false,
    "userName": false,
    "userColor": false,
    "rtl": false,
    "alwaysShowChat": false,
    "chatAndUsers": false,
    "lang": "en-gb"
  },
  "suppressErrorsInPadText": false,
  "requireSession": true,
  "editOnly": false,
  "minify": true,
  "maxAge": 21600,
  "abiword": null,
  "soffice": null,
  "requireAuthentication": true,
  "requireAuthorization": true,
  "trustProxy": true,
  "cookie": {
    "sameSite": "Lax",
    "secure": true
  },
  "disableIPlogging": false,
  "automaticReconnectionTimeout": 0,
  "scrollWhenFocusLineIsOutOfViewport": {
    "percentage": { "editionAboveViewport": 0, "editionBelowViewport": 0 },
    "duration": 0,
    "scrollWhenCaretIsInTheLastLineOfViewport": false,
    "percentageToScrollWhenUserPressesArrowUp": 0
  },
  "users": {},
  "socketTransportProtocols": ["websocket", "polling"],
  "loadTest": false,
  "indentationOnNewLine": true,
  "logconfig": {
    "appenders": [{ "type": "console" }]
  },
  "customLocaleStrings": {},
  "importExportRateLimiting": {
    "windowMs": 90000,
    "max": 10
  },
  "commitRateLimiting": {
    "duration": 1,
    "points": 10
  },
  "exposeVersion": false,
  "ep_openid_connect": {
    "issuer": "${OIDC_ISSUER}",
    "client_id": "${OIDC_CLIENT_ID}",
    "client_secret": "${OIDC_CLIENT_SECRET}",
    "base_url": "https://${ETHERPAD_DOMAIN}",
    "user_properties": {
      "displayname": { "claim": "name" },
      "is_admin": { "claim": "is_etherpad_admin", "default": false }
    },
    "scope": ["openid", "profile", "email"]
  }
}
EOF

cat > "${ETHERPAD_HOME}/src/APIKEY.txt" <<EOF
${ETHERPAD_APIKEY}
EOF

cat > "${ETHERPAD_HOME}/src/SESSIONKEY.txt" <<EOF
${ETHERPAD_SESSIONKEY}
EOF

chown -R "${ETHERPAD_USER}:${ETHERPAD_USER}" "${ETHERPAD_HOME}/src"
chmod 600 "${ETHERPAD_HOME}/src/settings.json" \
          "${ETHERPAD_HOME}/src/APIKEY.txt" \
          "${ETHERPAD_HOME}/src/SESSIONKEY.txt"

echo "==> systemd unit"
cat > /etc/systemd/system/etherpad.service <<UNIT
[Unit]
Description=Etherpad-lite — collaborative editor
After=network.target postgresql.service
Wants=postgresql.service

[Service]
Type=simple
User=${ETHERPAD_USER}
Group=${ETHERPAD_USER}
WorkingDirectory=${ETHERPAD_HOME}/src
ExecStart=/usr/bin/node ${ETHERPAD_HOME}/src/src/node/server.js
Restart=on-failure
RestartSec=5
LimitNOFILE=64000
NoNewPrivileges=true
PrivateTmp=true
ProtectSystem=full
ProtectHome=true
ReadWritePaths=${ETHERPAD_HOME}
StandardOutput=journal
StandardError=journal

[Install]
WantedBy=multi-user.target
UNIT

systemctl daemon-reload
systemctl enable --now etherpad

echo "==> Waiting for Etherpad on 127.0.0.1:9001"
for i in {1..120}; do
  if ss -lntp | grep -q '127.0.0.1:9001'; then break; fi
  sleep 2
done

if ! ss -lntp | grep -q '127.0.0.1:9001'; then
  echo "Etherpad failed to listen on 127.0.0.1:9001"
  journalctl -u etherpad --no-pager -n 200 || true
  exit 1
fi

echo "==> Installing nginx and certbot"
apt-get -y install nginx certbot python3-certbot-nginx

cat > /etc/nginx/sites-available/etherpad <<NGINX
map \$http_upgrade \$connection_upgrade {
    default upgrade;
    ''      close;
}

upstream etherpad_backend {
    server 127.0.0.1:9001;
    keepalive 32;
}

server {
    listen 80;
    listen [::]:80;
    server_name ${ETHERPAD_DOMAIN};
    return 301 https://\$host\$request_uri;
}

server {
    listen 443 ssl http2;
    listen [::]:443 ssl http2;
    server_name ${ETHERPAD_DOMAIN};

    client_max_body_size 50M;
    proxy_read_timeout   600s;
    proxy_send_timeout   600s;
    proxy_connect_timeout 60s;

    add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
    add_header X-Content-Type-Options nosniff always;
    add_header X-Frame-Options SAMEORIGIN always;
    add_header Referrer-Policy strict-origin-when-cross-origin always;

    location ~ ^/(p/|locales/|locales\\.json|admin/|static/|pluginfw/|javascripts/|socket.io/|ep/|minified/|api/|ro/|error/|jserror/|favicon\\.ico|robots\\.txt|stats\\.json|tests/) {
        proxy_set_header Host \$host;
        proxy_set_header X-Real-IP \$remote_addr;
        proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto \$scheme;
        proxy_http_version 1.1;
        proxy_set_header Upgrade \$http_upgrade;
        proxy_set_header Connection \$connection_upgrade;
        proxy_pass http://etherpad_backend;
        proxy_buffering off;
    }

    location / {
        proxy_set_header Host \$host;
        proxy_set_header X-Real-IP \$remote_addr;
        proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto \$scheme;
        proxy_http_version 1.1;
        proxy_set_header Upgrade \$http_upgrade;
        proxy_set_header Connection \$connection_upgrade;
        proxy_pass http://etherpad_backend;
    }
}
NGINX

ln -sf /etc/nginx/sites-available/etherpad /etc/nginx/sites-enabled/etherpad
rm -f /etc/nginx/sites-enabled/default

nginx -t
systemctl enable --now nginx
systemctl reload nginx

echo "==> Requesting Let's Encrypt certificate"
certbot --nginx --non-interactive --agree-tos \
  -m "${ETHERPAD_EMAIL}" -d "${ETHERPAD_DOMAIN}" --redirect

systemctl enable --now certbot.timer

echo "==> Waiting for HTTPS listener"
for i in {1..30}; do
  if ss -lntp | grep -q ':443'; then break; fi
  sleep 1
done

echo "==> Final package update"
apt-get -y upgrade

echo
echo "========================================"
echo "DONE"
echo "========================================"
echo
echo "Listeners:"
ss -lntp | grep -E ':(80|443|9001|5432)\b' || true

echo
echo "Services:"
systemctl is-active etherpad nginx postgresql fail2ban chrony || true

echo
echo "Auth check (expect 401/302 without SSO session):"
curl -sS -o /dev/null -w '%{http_code}\n' "https://${ETHERPAD_DOMAIN}/p/auth-test" || true

echo
echo "API key written to ${ETHERPAD_HOME}/src/APIKEY.txt (mode 600)."
echo "PERSIST IT — rotating the API key invalidates every embedded pad."
echo
echo "Web UI: https://${ETHERPAD_DOMAIN}/"
echo
echo "First steps:"
echo "1. Configure your IdP client (Authentik / Keycloak / Auth0) — redirect URI: https://${ETHERPAD_DOMAIN}/ep_openid_connect/callback"
echo "2. Sign in via SSO; grant the first user is_etherpad_admin in your IdP."
echo "3. Visit /admin/ and add ep_openid_connect group mappings if needed."
echo "4. Confirm pg_dump etherpad runs nightly into the VM-level backup window."

Rendez-le exécutable et lancez-le :

chmod 700 /root/setup-etherpad-ubuntu22.sh
ETHERPAD_DOMAIN=pad.example.com \
ETHERPAD_EMAIL=ops@example.com \
OIDC_ISSUER=https://idp.example.com \
OIDC_CLIENT_ID=etherpad \
OIDC_CLIENT_SECRET=replace_me \
/root/setup-etherpad-ubuntu22.sh

Une fois le SSO câblé dans votre IdP et le premier utilisateur connecté, marquez-le is_etherpad_admin: true via la claim OIDC — le plugin la mappe directement vers le rôle admin Etherpad sans mot de passe local parallèle. Ne partagez pas la clé d’API dans Slack ; les pads embarqués dans d’autres applications (Mattermost, Confluence) signent leurs jetons d’autorisation avec, donc une rotation invalide chaque embed. Ajoutez pg_dump etherpad -Fc -f /var/backups/etherpad-$(date +%F).pgdump à une tâche systemd nocturne, déposez le fichier dans un répertoire couvert par la sauvegarde VM, et gardez au moins 14 jours de rotation pour qu’un pad « supprimé par accident » ait un chemin de retour.

Faites tourner Etherpad pour votre équipe sur la compute infogérée Stack Harbor avec patching, supervision et escalade Sev-1 incluses : Cloud Compute — ou parlons-en si vous souhaitez planifier le déploiement.