diff --git a/.gitea/workflows/rilascio.yml b/.gitea/workflows/rilascio.yml index 5244be5..a55bdf8 100644 --- a/.gitea/workflows/rilascio.yml +++ b/.gitea/workflows/rilascio.yml @@ -1,16 +1,25 @@ # Rilascio a ogni tag vX.Y.Z (anche vX.Y.Z-qualcosa per un'anteprima): -# 1. controlla che il tag coincida con di Directory.Build.props; -# 2. Windows: pubblica Febe.exe in un file solo e costruisce il programma di installazione NSIS e lo zip portabile -# (installer/costruisci.sh, gira su Linux); -# 3. Docker: costruisce l'immagine (le prove girano dentro la build) e la pubblica sul registro dei container di -# Gitea come //febe:X.Y.Z e :latest (solo per le versioni senza trattino); -# 4. crea la release (o la completa, se esiste già) con installatore, zip portabile, modello Unraid e compose. +# 1. prove: il tag coincide con di Directory.Build.props, la soluzione si compila con gli avvisi come errori +# e tutte le prove passano. Senza prove verdi non si costruisce né si rilascia nulla; +# 2. windows: Febe.exe in un file solo, il programma di installazione NSIS e lo zip portabile (installer/costruisci.sh, +# gira su Linux); +# 3. immagine: l'immagine Docker (le prove girano anche dentro la build), pubblicata sul registro dei container di +# Gitea come //febe:X.Y.Z e :latest (solo per le versioni senza trattino). Il lavoro dice +# se l'ha pubblicata; +# 4. release: solo dopo le prove, l'installatore e l'immagine. Crea la release (o la completa, se esiste già) con +# installatore, zip portabile, modello Unraid e l'archivio per Docker Compose (compose.yml con il profilo seccomp +# accanto); le note dicono dove sta l'immagine, o che non è stata pubblicata. # # Segreto del repository (Impostazioni ▸ Actions ▸ Segreti): REGISTRY_TOKEN, un token dell'utente con i permessi -# «package: read and write». Senza, l'immagine si costruisce ma non si pubblica, e il lavoro lo dice. +# «package: read and write». Senza, l'immagine si costruisce e si prova ma non si pubblica: la release esce lo stesso, +# con l'installatore per Windows, e le sue note dicono che l'immagine di questa versione non c'è. Aggiunto il segreto, +# si rilancia il flusso del tag: l'immagine si pubblica e le note della release si correggono. # Variabile facoltativa (Impostazioni ▸ Actions ▸ Variabili): REGISTRY, il nome del registro come lo raggiunge il -# runner (per esempio 192.168.30.23:3000); se manca si usa l'host dell'indirizzo del server Gitea. -# Il registro in HTTP: buildx lo tratta come insicuro (configurazione qui sotto). +# runner (per esempio 192.168.30.23:3000); se manca si usa l'host dell'indirizzo del server Gitea (il suo ROOT_URL). +# Il registro risponde in HTTP: la pubblicazione passa da buildx con un builder proprio (docker-container) a cui la +# configurazione di buildkit dice che quel registro è in HTTP e insicuro, così non serve che il Docker del runner lo +# abbia fra gli insecure-registries. Le credenziali vanno nella configurazione del client Docker, senza «docker login» +# (che passerebbe dal demone, e il demone proverebbe HTTPS). name: rilascio on: @@ -18,7 +27,7 @@ on: tags: ["v*"] jobs: - windows: + prove: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 @@ -27,7 +36,35 @@ jobs: run: | V=$(sed -n 's:.*\(.*\).*:\1:p' Directory.Build.props | head -n 1) [ "v$V" = "${GITHUB_REF_NAME}" ] || { echo "Il tag ${GITHUB_REF_NAME} non coincide con $V"; exit 1; } - echo "VERSION=$V" >> "$GITHUB_ENV" + + - uses: actions/setup-dotnet@v4 + with: + dotnet-version: "10.0.x" + + - name: Compilazione (avvisi = errori) + run: dotnet build Febe.slnx -c Release -nologo -warnaserror + + - name: Prove + run: >- + dotnet test tests/Febe.Tests -c Release --no-build --nologo + --logger "trx;LogFileName=prove.trx" --results-directory out/prove + + - name: Risultati + if: always() + uses: actions/upload-artifact@v3 + with: + name: risultati-prove + path: out/prove/*.trx + if-no-files-found: ignore + + windows: + runs-on: ubuntu-latest + needs: prove + steps: + - uses: actions/checkout@v4 + + - name: Versione + run: echo "VERSION=${GITHUB_REF_NAME#v}" >> "$GITHUB_ENV" - uses: actions/setup-dotnet@v4 with: @@ -52,48 +89,99 @@ jobs: immagine: runs-on: ubuntu-latest + needs: prove + outputs: + immagine: ${{ steps.nome.outputs.immagine }} + pubblicata: ${{ steps.pubblicazione.outputs.pubblicata }} + motivo: ${{ steps.segreto.outputs.motivo }} steps: - uses: actions/checkout@v4 - name: Versione, registro e nome dell'immagine + id: nome run: | - V=$(sed -n 's:.*\(.*\).*:\1:p' Directory.Build.props | head -n 1) - [ "v$V" = "${GITHUB_REF_NAME}" ] || { echo "Il tag ${GITHUB_REF_NAME} non coincide con $V"; exit 1; } + V="${GITHUB_REF_NAME#v}" REGISTRY="${{ vars.REGISTRY }}" - [ -n "$REGISTRY" ] || REGISTRY=$(echo "${{ gitea.server_url }}" | sed -E 's#^https?://##; s#/$##') + [ -n "$REGISTRY" ] || REGISTRY=$(echo "${{ gitea.server_url }}" | sed -E 's#^https?://##; s#/.*$##') OWNER=$(echo "${{ gitea.repository_owner }}" | tr '[:upper:]' '[:lower:]') echo "VERSION=$V" >> "$GITHUB_ENV" echo "REGISTRY=$REGISTRY" >> "$GITHUB_ENV" echo "IMAGE=$REGISTRY/$OWNER/febe" >> "$GITHUB_ENV" + echo "registro=$REGISTRY" >> "$GITHUB_OUTPUT" + echo "immagine=$REGISTRY/$OWNER/febe" >> "$GITHUB_OUTPUT" + + # Un builder buildx proprio, che sa che il registro di casa risponde in HTTP. + - uses: docker/setup-buildx-action@v3 + with: + driver: docker-container + buildkitd-config-inline: | + [registry."${{ steps.nome.outputs.registro }}"] + http = true + insecure = true - name: Costruzione dell'immagine (le prove girano dentro la build) run: | - docker build -f docker/Dockerfile \ + docker buildx build -f docker/Dockerfile \ --build-arg VERSION="$VERSION" \ --build-arg GIT_COMMIT="${GITHUB_SHA::12}" \ - -t "$IMAGE:$VERSION" . + -t "$IMAGE:$VERSION" --load . docker run --rm --entrypoint /usr/bin/chromium "$IMAGE:$VERSION" --version - - name: Pubblicazione sul registro di Gitea + - name: Segreto per il registro + id: segreto env: TOKEN: ${{ secrets.REGISTRY_TOKEN }} run: | if [ -z "$TOKEN" ]; then - echo "::warning::Manca il segreto REGISTRY_TOKEN: l'immagine è stata costruita ma non pubblicata." - echo "Aggiungi il segreto (token con package: read and write) e rilancia questo lavoro." - exit 1 + echo "::warning::Manca il segreto REGISTRY_TOKEN: l'immagine è stata costruita e provata ma non pubblicata. La release esce lo stesso e lo dice." + echo "Aggiungi il segreto (token con package: read and write) e rilancia il flusso di questo tag." + echo "presente=no" >> "$GITHUB_OUTPUT" + echo "motivo=manca il segreto REGISTRY_TOKEN del repository" >> "$GITHUB_OUTPUT" + else + echo "presente=si" >> "$GITHUB_OUTPUT" fi - echo "$TOKEN" | docker login "$REGISTRY" -u "${{ gitea.actor }}" --password-stdin - docker push "$IMAGE:$VERSION" + + - name: Pubblicazione sul registro di Gitea + id: pubblicazione + if: steps.segreto.outputs.presente == 'si' + env: + TOKEN: ${{ secrets.REGISTRY_TOKEN }} + UTENTE: ${{ gitea.actor }} + run: | + set -eu + # Le credenziali nella configurazione del client: buildx le passa al builder, il demone non c'entra. + CONFIG="${DOCKER_CONFIG:-$HOME/.docker}" + mkdir -p "$CONFIG" + [ -s "$CONFIG/config.json" ] || echo '{}' > "$CONFIG/config.json" + AUTH=$(printf '%s:%s' "$UTENTE" "$TOKEN" | base64 -w0) + jq --arg r "$REGISTRY" --arg a "$AUTH" '.auths[$r].auth = $a' "$CONFIG/config.json" > "$CONFIG/config.json.nuovo" + mv "$CONFIG/config.json.nuovo" "$CONFIG/config.json" + TAGS="-t $IMAGE:$VERSION" case "$VERSION" in *-*) echo "Versione di anteprima: :latest non si sposta." ;; - *) docker tag "$IMAGE:$VERSION" "$IMAGE:latest" && docker push "$IMAGE:latest" ;; + *) TAGS="$TAGS -t $IMAGE:latest" ;; esac - docker logout "$REGISTRY" + # La stessa costruzione di prima (dalla cache del builder), questa volta spinta sul registro. + docker buildx build -f docker/Dockerfile \ + --build-arg VERSION="$VERSION" \ + --build-arg GIT_COMMIT="${GITHUB_SHA::12}" \ + $TAGS --push . + echo "pubblicata=si" >> "$GITHUB_OUTPUT" + + - name: Credenziali tolte + if: always() + run: | + CONFIG="${DOCKER_CONFIG:-$HOME/.docker}/config.json" + if [ -s "$CONFIG" ] && [ -n "${REGISTRY:-}" ]; then + jq --arg r "$REGISTRY" 'if .auths then .auths |= del(.[$r]) else . end' "$CONFIG" > "$CONFIG.nuovo" && mv "$CONFIG.nuovo" "$CONFIG" + fi release: runs-on: ubuntu-latest - needs: windows + # Le prove sono verdi, l'installatore c'è e l'immagine si è costruita: pubblicata, o non pubblicata per la sola + # mancanza del segreto (il lavoro «immagine» lo dice e le note lo riportano). Se la costruzione o la spinta sul + # registro falliscono, non esce nessuna release. + needs: [prove, windows, immagine] steps: - uses: actions/checkout@v4 @@ -102,10 +190,13 @@ jobs: name: windows path: out - - name: Release con installatore, zip portabile, modello Unraid e compose + - name: Release con installatore, zip portabile, modello Unraid e archivio per Compose env: TOKEN: ${{ github.token }} API: ${{ gitea.server_url }}/api/v1/repos/${{ gitea.repository }} + IMMAGINE: ${{ needs.immagine.outputs.immagine }} + PUBBLICATA: ${{ needs.immagine.outputs.pubblicata }} + MOTIVO: ${{ needs.immagine.outputs.motivo }} run: | set -eu TAG="${GITHUB_REF_NAME}" @@ -113,6 +204,17 @@ jobs: case "$VERSION" in *-*|0.*) PRE=true ;; *) PRE=false ;; esac # le versioni 0.x sono anteprime NOTE=$(awk -v v="$VERSION" '/^## /{p=($2==v)} p' CHANGELOG.md || true) [ -n "$NOTE" ] || NOTE="Febe $VERSION" + if [ "$PUBBLICATA" = "si" ]; then + case "$VERSION" in + *-*) DOVE="\`$IMMAGINE:$VERSION\` (anteprima: \`:latest\` resta sulla versione precedente)" ;; + *) DOVE="\`$IMMAGINE:$VERSION\` e \`$IMMAGINE:latest\`" ;; + esac + IMMAGINE_NOTA="Immagine Docker: $DOVE. Il registro risponde in HTTP: il Docker che la scarica deve averlo fra gli \`insecure-registries\`." + else + IMMAGINE_NOTA="**L'immagine Docker di questa versione non è stata pubblicata** (${MOTIVO:-motivo sconosciuto}): \`:latest\` resta sulla versione precedente, e Unraid e Docker Compose continuano a usare quella. Febe per Windows, qui allegato, è provato come sempre. Per pubblicare l'immagine, rilancia il flusso di rilascio di questo tag dopo aver risolto il problema: queste note si aggiornano." + fi + NOTE=$(printf '%s\n\n### Immagine Docker\n\n%s\n' "$NOTE" "$IMMAGINE_NOTA") + ID=$(curl -sf -H "Authorization: token $TOKEN" "$API/releases/tags/$TAG" | jq -r '.id // empty' || true) if [ -z "$ID" ]; then ID=$(jq -n --arg t "$TAG" --arg n "Febe $VERSION" --arg b "$NOTE" --argjson p "$PRE" \ @@ -121,12 +223,24 @@ jobs: --data-binary @- "$API/releases" | jq -r .id) echo "Release $TAG creata (id $ID)" else - echo "Release $TAG già presente (id $ID): aggiungo gli allegati mancanti" + # Le note dicono come è andata questa volta (per esempio: l'immagine ora è pubblicata). + jq -n --arg b "$NOTE" '{body:$b}' \ + | curl -sf -X PATCH -H "Authorization: token $TOKEN" -H "Content-Type: application/json" \ + --data-binary @- "$API/releases/$ID" > /dev/null + echo "Release $TAG già presente (id $ID): note aggiornate, aggiungo gli allegati mancanti" fi + cp docker/unraid/febe.xml "out/febe-unraid-$VERSION.xml" - cp docker/compose.yml "out/febe-compose-$VERSION.yml" + # compose.yml indica il profilo seccomp con un percorso relativo: l'archivio li porta insieme. + COMPOSE="out/febe-compose-$VERSION" + rm -rf "$COMPOSE" + mkdir -p "$COMPOSE/chromium" + cp docker/compose.yml "$COMPOSE/compose.yml" + cp docker/chromium/seccomp.json "$COMPOSE/chromium/seccomp.json" + tar -czf "$COMPOSE.tar.gz" -C out "febe-compose-$VERSION" + ESISTENTI=$(curl -sf -H "Authorization: token $TOKEN" "$API/releases/$ID/assets" | jq -r '.[].name') - for f in out/Febe-Setup-*.exe out/Febe-*-portabile.zip "out/febe-unraid-$VERSION.xml" "out/febe-compose-$VERSION.yml"; do + for f in out/Febe-Setup-*.exe out/Febe-*-portabile.zip "out/febe-unraid-$VERSION.xml" "$COMPOSE.tar.gz"; do n=$(basename "$f") if echo "$ESISTENTI" | grep -qx "$n"; then echo "$n già allegato"; continue; fi curl -sf -X POST -H "Authorization: token $TOKEN" -F "attachment=@$f" "$API/releases/$ID/assets?name=$n" > /dev/null diff --git a/docker/Dockerfile b/docker/Dockerfile index 503522d..52f33d1 100644 --- a/docker/Dockerfile +++ b/docker/Dockerfile @@ -4,7 +4,7 @@ # # docker build -f docker/Dockerfile \ # --build-arg VERSION=0.1.0 --build-arg GIT_COMMIT=$(git rev-parse --short=12 HEAD) \ -# -t gitea.encke-hake.ts.net/alby96/febe:0.1.0 . +# -t 192.168.30.23:3000/alby96/febe:0.1.0 . # # Stadi: # build restore e compilazione di tutta la soluzione con gli avvisi come errori; @@ -89,8 +89,9 @@ RUN apt-get update \ # Criteri di Chromium: niente salvataggio delle password né compilazione automatica (nel profilo resta solo la sessione). COPY docker/chromium/febe.json /etc/chromium/policies/managed/febe.json -# Il profilo seccomp dedicato (quello di Docker più clone/unshare per la sandbox di Chromium): l'avvio lo copia in -# /dati/seccomp.json, così sul server c'è sempre la versione di questa immagine (docs/docker.md, «Sandbox»). +# Il profilo seccomp dedicato (quello di Docker più clone/unshare per la sandbox di Chromium), per leggerlo +# dall'immagine: Docker lo usa dal server, fuori dal volume dei dati (docs/docker.md, «Sandbox»), e l'avvio non lo +# copia in /dati, dove l'utente del contenitore potrebbe cambiarlo. COPY docker/chromium/seccomp.json /usr/share/febe/seccomp.json COPY --from=publish /app /app diff --git a/docker/chromium/LEGGIMI.md b/docker/chromium/LEGGIMI.md index 6c810e7..8bca29d 100644 --- a/docker/chromium/LEGGIMI.md +++ b/docker/chromium/LEGGIMI.md @@ -3,7 +3,7 @@ | File | Dove finisce | A che cosa serve | |---|---|---| | `febe.json` | `/etc/chromium/policies/managed/febe.json` | Criteri del browser: niente salvataggio delle password (`PasswordManagerEnabled`), niente controllo delle password trapelate (`PasswordLeakDetectionEnabled`), niente compilazione automatica di indirizzi e carte (`AutofillAddressEnabled`, `AutofillCreditCardEnabled`). Nel profilo resta solo la sessione (specifica §6.1, §11) | -| `seccomp.json` | `/usr/share/febe/seccomp.json`, copiato a ogni avvio in `/dati/seccomp.json` | Profilo seccomp dedicato da indicare con `--security-opt seccomp=…` (vedi `docs/docker.md`, «Sandbox») | +| `seccomp.json` | `/usr/share/febe/seccomp.json` (solo da leggere); sul server va tenuto **fuori** dal volume `/dati` | Profilo seccomp dedicato da indicare con `--security-opt seccomp=…` (vedi `docs/docker.md`, «Sandbox») | `seccomp.json` è il profilo predefinito di Docker (`moby/profiles`, ramo `main`, `seccomp/default.json`, licenza Apache 2.0) con **una sola regola in più**, in fondo all'elenco: `clone` e `unshare` ammessi anche senza diff --git a/docker/compose.yml b/docker/compose.yml index 3d15739..0659eea 100644 --- a/docker/compose.yml +++ b/docker/compose.yml @@ -3,6 +3,11 @@ # FEBE_PASSWORD='una frase lunga' docker compose -f docker/compose.yml up -d # → http://:8480/ (Impostazioni ▸ Collegamento ▸ «Accedi a Instagram» dalla vista remota) # +# Fuori dal repository usa l'archivio febe-compose-X.Y.Z.tar.gz della release: questo file con accanto +# chromium/seccomp.json, il profilo che «security_opt» indica con un percorso relativo. +# L'immagine sta sul registro di Gitea in HTTP (192.168.30.23:3000): il Docker del server deve averlo fra gli +# «insecure-registries», come per le altre immagini di casa. +# # Per costruire l'immagine in locale invece di scaricarla, togli il commento a «build». # Su Unraid usa invece il modello docker/unraid/febe.xml. # @@ -10,7 +15,7 @@ services: febe: - image: gitea.encke-hake.ts.net/alby96/febe:latest + image: 192.168.30.23:3000/alby96/febe:latest # build: # context: .. # dockerfile: docker/Dockerfile @@ -24,7 +29,8 @@ services: stop_grace_period: 30s # La sandbox di Chromium crea spazi dei nomi utente, che il profilo seccomp predefinito di Docker vieta (provato: # «No usable sandbox»). Questo profilo è quello di Docker più clone/unshare: la sandbox del browser resta attiva - # e il resto del filtro di Docker pure. Vedi docs/docker.md, «Sandbox». + # e il resto del filtro di Docker pure. Il file sta accanto a questo, fuori da /dati: Docker lo legge sul server, + # e l'utente del contenitore non lo può cambiare. Vedi docs/docker.md, «Sandbox». security_opt: - seccomp=./chromium/seccomp.json ports: @@ -45,6 +51,6 @@ services: PGID: "1000" # Facoltative: # FEBE_HOST: "tower.local,192.168.1.10" # nomi con cui raggiungi l'interfaccia (gli altri sono rifiutati) - # FEBE_PROXY_FIDATO: "1" # dietro un proxy con HTTPS che passa X-Forwarded-Host + # FEBE_PROXY_FIDATO: "1" # dietro un proxy con HTTPS che passa X-Forwarded-Host e -Proto # FEBE_SENZA_SANDBOX: "1" # solo se Chromium non parte: vedi docs/docker.md, «Sandbox» # Chromium usa /tmp invece della memoria condivisa (--disable-dev-shm-usage): shm_size non serve. diff --git a/docker/entrypoint.sh b/docker/entrypoint.sh index 78a9270..aa6cd63 100755 --- a/docker/entrypoint.sh +++ b/docker/entrypoint.sh @@ -3,7 +3,7 @@ # # Fa solo tre cose e poi cede il posto al server: # 1. crea, se mancano, il gruppo PGID e l'utente PUID (su Unraid 99 e 100, «nobody:users»); -# 2. rende /dati di quell'utente (la prima volta, o se PUID/PGID sono cambiati) e prepara /dati/home; +# 2. rende /dati di quell'utente (la prima volta, o se PUID/PGID sono cambiati) e gli fa preparare /dati/home; # 3. exec del server con setpriv, come quell'utente: il server avvia e sorveglia da sé Xvfb e Chromium. # Nessun ciclo di sorveglianza qui: è il lavoro di Febe.Server (niente script di shell che facciano da supervisore). # /libreria non si cambia mai ricorsivamente (sono le foto di Alberto); /importa è in sola lettura e non si tocca. @@ -32,20 +32,27 @@ if ! getent passwd "${PUID}" >/dev/null 2>&1; then useradd -o -u "${PUID}" -g "${PGID}" -M -d /dati/home -s /usr/sbin/nologin febe fi +# /dati è dell'utente PUID, che dentro può mettere di tutto, anche collegamenti simbolici verso file del contenitore: +# da root qui dentro non si scrive niente. L'unica cosa fatta da root è il cambio di proprietario, ricorsivo e senza +# seguire i collegamenti (-R senza -H/-L: cambia il collegamento, mai ciò a cui punta). Il resto lo fa l'utente stesso. if mkdir -p /dati 2>/dev/null; then - if [ "$(stat -c '%u:%g' /dati)" != "${PUID}:${PGID}" ]; then + da_assegnare="" + [ "$(stat -c '%u:%g' /dati)" = "${PUID}:${PGID}" ] || da_assegnare=1 + # Una /dati/home di un altro proprietario (un avvio precedente come root): conta solo una cartella vera. + if [ -d /dati/home ] && [ ! -L /dati/home ] && [ "$(stat -c '%u:%g' /dati/home)" != "${PUID}:${PGID}" ]; then + da_assegnare=1 + fi + if [ -n "${da_assegnare}" ]; then echo "Febe: assegno /dati a ${PUID}:${PGID}." chown -R "${PUID}:${PGID}" /dati 2>/dev/null || echo "Febe: non riesco ad assegnare /dati a ${PUID}:${PGID}." >&2 fi chmod 0750 /dati 2>/dev/null || true - if mkdir -p /dati/home 2>/dev/null; then - chown "${PUID}:${PGID}" /dati/home 2>/dev/null || true - chmod 0700 /dati/home 2>/dev/null || true - fi - # Il profilo seccomp della sandbox di Chromium, aggiornato a ogni avvio: è il file che «--security-opt seccomp=» - # indica sul server (su Unraid /mnt/user/appdata/febe/seccomp.json). Docker lo legge alla creazione del contenitore. - if [ -f /usr/share/febe/seccomp.json ]; then - cp /usr/share/febe/seccomp.json /dati/seccomp.json 2>/dev/null && chmod 0644 /dati/seccomp.json 2>/dev/null || true + # La HOME di Chromium la crea e la chiude l'utente, con i suoi permessi. + setpriv --reuid="${PUID}" --regid="${PGID}" --init-groups sh -c 'mkdir -p /dati/home && chmod 0700 /dati/home' 2>/dev/null || true + # Il profilo seccomp non sta più in /dati: Docker lo legge sul server alla creazione del contenitore, e in /dati + # l'utente del contenitore potrebbe allentarlo. Si tiene fuori dal volume dei dati (docs/docker.md, «Sandbox»). + if [ -e /dati/seccomp.json ] || [ -L /dati/seccomp.json ]; then + echo "Febe: /dati/seccomp.json non si aggiorna più. Se --security-opt seccomp= indica quel file, sposta il profilo fuori dalla cartella dei dati (su Unraid /mnt/user/appdata/febe-seccomp.json): vedi docs/docker.md, «Sandbox»." >&2 fi fi diff --git a/docker/unraid/febe.xml b/docker/unraid/febe.xml index bd5e848..31b7577 100644 --- a/docker/unraid/febe.xml +++ b/docker/unraid/febe.xml @@ -1,26 +1,26 @@ Febe - gitea.encke-hake.ts.net/alby96/febe:latest - https://gitea.encke-hake.ts.net/Alby96/-/packages/container/febe + 192.168.30.23:3000/alby96/febe:latest + http://192.168.30.23:3000/Alby96/-/packages/container/febe bridge bash false - https://gitea.encke-hake.ts.net/Alby96/Febe/issues - https://gitea.encke-hake.ts.net/Alby96/Febe + http://192.168.30.23:3000/Alby96/Febe/issues + http://192.168.30.23:3000/Alby96/Febe Febe: archivio personale di foto, video e storie da Instagram. Un browser vero (Chromium su un display virtuale) visita i profili a ritmo umano, con tetti giornalieri, e salva cio' che la pagina riceve in una libreria di file sul server. Si accede una volta sola, a mano, dalla vista remota della pagina Impostazioni, Collegamento: password e codici passano dal server senza essere registrati, quindi l'interfaccia non va mai esposta su Internet senza una VPN o un proxy con HTTPS. La cartella /dati contiene la sessione di Instagram: chi ha /dati, o una sua copia, ha la sessione. Non usare il contenitore e Febe per Windows sullo stesso account. Unica variabile obbligatoria: la password dell'interfaccia. Guida: docs/docker.md nel repository. Backup: MediaApp:Photos http://[IP]:[PORT:8480]/ - https://gitea.encke-hake.ts.net/Alby96/Febe/raw/branch/main/docker/unraid/febe.xml - https://gitea.encke-hake.ts.net/Alby96/Febe/raw/branch/main/docker/unraid/febe.png - --restart=unless-stopped --stop-timeout 30 --security-opt seccomp=/mnt/user/appdata/febe/seccomp.json + http://192.168.30.23:3000/Alby96/Febe/raw/branch/main/docker/unraid/febe.xml + http://192.168.30.23:3000/Alby96/Febe/raw/branch/main/docker/unraid/febe.png + --restart=unless-stopped --stop-timeout 30 --security-opt seccomp=/mnt/user/appdata/febe-seccomp.json - Prima della prima installazione, dal terminale di Unraid: mkdir -p /mnt/user/appdata/febe && wget -O /mnt/user/appdata/febe/seccomp.json https://gitea.encke-hake.ts.net/Alby96/Febe/raw/branch/main/docker/chromium/seccomp.json (profilo seccomp per la sandbox di Chromium, indicato in ExtraParams; poi lo aggiorna il contenitore da solo). Spiegazione in docs/docker.md, «Sandbox». + Il registro 192.168.30.23:3000 e' in HTTP: deve stare fra gli insecure-registries del Docker di Unraid, come per le altre immagini di casa. Prima della prima installazione, dal terminale di Unraid, metti il profilo seccomp della sandbox di Chromium (indicato in ExtraParams) FUORI dalla cartella dei dati: docker run --rm --entrypoint cat 192.168.30.23:3000/alby96/febe:latest /usr/share/febe/seccomp.json > /mnt/user/appdata/febe-seccomp.json. Il contenitore non lo tocca: ripeti il comando solo se le note di una versione lo chiedono. Spiegazione in docs/docker.md, «Sandbox». 8480 /mnt/user/appdata/febe diff --git a/docs/docker.md b/docs/docker.md index c3e8720..521d3b2 100644 --- a/docs/docker.md +++ b/docs/docker.md @@ -25,7 +25,7 @@ display virtuale (Xvfb) e la libreria su disco. Si usa dal browser di casa; il b | Volume | Uso | Dove metterlo | |---|---|---| -| `/dati` | Database (`febe.sqlite`), **profilo del browser con la sessione di Instagram** (`browser/`), miniature, copie giornaliere del database (`copie/`, sette giorni), registro (`registro/`, quattordici giorni), file temporanei, `seccomp.json` | Su un **disco locale** del server. Su Unraid: `/mnt/user/appdata/febe` (la cartella delle applicazioni sul disco di cache). Mai una condivisione di rete: SQLite e il profilo del browser lì si rovinano, e Febe si rifiuta di partire | +| `/dati` | Database (`febe.sqlite`), **profilo del browser con la sessione di Instagram** (`browser/`), miniature, copie giornaliere del database (`copie/`, sette giorni), registro (`registro/`, quattordici giorni), file temporanei | Su un **disco locale** del server. Su Unraid: `/mnt/user/appdata/febe` (la cartella delle applicazioni sul disco di cache). Mai una condivisione di rete: SQLite e il profilo del browser lì si rovinano, e Febe si rifiuta di partire | | `/libreria` | Foto e video, una cartella per account, con `_febe.jsonl` | Dove vuoi, anche su una condivisione. Febe non cancella e non sostituisce mai un file da solo | | `/importa` | Cartelle da importare (pagina Importa) | **Sempre in sola lettura** (`:ro`): Febe copia, gli originali non si toccano | @@ -39,7 +39,7 @@ display virtuale (Xvfb) e la libreria su disco. Si usa dal browser di casa; il b | `LANG` | Lingua del contenitore e quindi del browser | it_IT.UTF-8 | | `PUID`, `PGID` | Utente e gruppo con cui gira Febe e di cui sono i file | 99, 100 (Unraid) | | `FEBE_HOST` | Facoltativa: i nomi con cui raggiungi l'interfaccia, separati da virgole (`tower.local,192.168.1.10`). Se c'è, ogni altro nome è rifiutato (oltre a 127.0.0.1 per il controllo di salute) | qualunque nome | -| `FEBE_PROXY_FIDATO` | `1` se davanti c'è un proxy con HTTPS che passa `X-Forwarded-Host`: il controllo dell'origine usa quel nome | spenta | +| `FEBE_PROXY_FIDATO` | `1` se davanti c'è un proxy con HTTPS che passa `X-Forwarded-Host` e `X-Forwarded-Proto`: il controllo dell'origine usa quel nome, e quando il proxy dice `https` il cookie di sessione è `Secure` (il browser non lo manda mai in chiaro) | spenta | | `FEBE_SENZA_SANDBOX` | `1` avvia Chromium con `--no-sandbox`: è il compromesso descritto sotto, da usare solo se il profilo seccomp non si può usare | spenta | | `FEBE_CHROMIUM`, `FEBE_PORTA_DEBUG`, `FEBE_DISPLAY` | Avanzate: eseguibile di Chromium, porta di debug (sempre su 127.0.0.1), display di Xvfb | `/usr/bin/chromium`, 9222, `:99` | @@ -68,9 +68,16 @@ Esito della prova del 13 ottobre 2026 (dettagli in `docker/chromium/LEGGIMI.md`) `unshare`) la sandbox è completa (`chrome://sandbox`: «You are adequately sandboxed») e il resto del filtro di Docker resta attivo. **È l'impostazione consigliata**, già scritta in `compose.yml` e nel modello di Unraid. -L'avvio del contenitore copia il profilo in `/dati/seccomp.json` a ogni partenza, così sul server c'è sempre la versione -dell'immagine; Docker però lo legge quando **crea** il contenitore, quindi la prima volta il file va messo a mano -(vedi Unraid, sotto). +Docker legge il profilo **sul server**, quando crea il contenitore. Per questo il file sta **fuori dal volume `/dati`**: +`/dati` è dell'utente del contenitore, e un file lì dentro potrebbe essere cambiato da chi riuscisse a far eseguire +qualcosa a quell'utente (per esempio attraverso un difetto del browser), che allenterebbe così il proprio filtro alla +ricreazione successiva. L'immagine contiene il profilo in `/usr/share/febe/seccomp.json`, solo da leggere; lo si +estrae una volta (vedi Unraid, sotto) o si usa quello di `docker/chromium/` accanto a `compose.yml`. Il contenitore non +lo tocca: si ripete l'estrazione solo quando le note di una versione lo chiedono. + +Le prime anteprime copiavano il profilo in `/dati/seccomp.json` a ogni avvio: se «Extra Parameters» indica ancora +quel file, estrai il profilo nel posto nuovo e correggi il percorso (il registro del contenitore lo ricorda a ogni +avvio). Se il profilo dedicato non si può usare, le alternative sono due, in quest'ordine: @@ -94,28 +101,34 @@ Febe non sceglie da solo: se Chromium non parte, il registro dice perché e rima - **Contenitore e Febe per Windows non vanno usati insieme sullo stesso account.** Un account, un motore: due Febe che raccolgono con lo stesso account sommano le visite e raddoppiano il rischio. - La sessione nasce e resta nel browser del contenitore: i cookie non si copiano da un'altra macchina. -- L'interfaccia è protetta da password (cookie di sessione `HttpOnly`, `SameSite=Strict`, blocco dopo tentativi - ripetuti); ogni comando e l'apertura della vista remota controllano che la richiesta arrivi dall'interfaccia stessa. +- L'interfaccia è protetta da password (cookie di sessione `HttpOnly`, `SameSite=Strict`, `Secure` quando arrivi in + HTTPS, anche attraverso il proxy fidato; blocco dopo tentativi ripetuti); ogni comando e l'apertura della vista + remota controllano che la richiesta arrivi dall'interfaccia stessa. Dopo la password, la pagina di accesso torna + solo a una pagina di Febe, mai a un altro sito. ## Installazione su Unraid -1. Dal terminale di Unraid, **una volta sola**, metti il profilo seccomp dove il modello lo cerca: +1. L'immagine è `192.168.30.23:3000/alby96/febe:latest`, sul registro dei container del Gitea di casa (lo stesso su + cui la pubblica il rilascio). Il registro risponde in **HTTP**: il Docker di Unraid deve averlo fra gli + `insecure-registries`, come per le altre immagini di casa (Encelado, Mimante). Se Unraid scarica già quelle, è a + posto; altrimenti aggiungi `"insecure-registries": ["192.168.30.23:3000"]` alla configurazione del demone Docker e + riavvia Docker. Se il pacchetto non è pubblico, accedi dal terminale: `docker login 192.168.30.23:3000`. +2. Dal terminale di Unraid, **una volta sola**, estrai il profilo seccomp dall'immagine e mettilo dove il modello lo + cerca, **fuori** dalla cartella dei dati: ```sh - mkdir -p /mnt/user/appdata/febe - wget -O /mnt/user/appdata/febe/seccomp.json \ - https://gitea.encke-hake.ts.net/Alby96/Febe/raw/branch/main/docker/chromium/seccomp.json + docker run --rm --entrypoint cat 192.168.30.23:3000/alby96/febe:latest \ + /usr/share/febe/seccomp.json > /mnt/user/appdata/febe-seccomp.json ``` -2. Il registro di Gitea dell'immagine è `gitea.encke-hake.ts.net/alby96/febe` (lo stesso host su cui la pubblica il - rilascio). Se Unraid non riesce a scaricarla, accedi al registro dal terminale (`docker login gitea.encke-hake.ts.net`). -3. Docker ▸ Aggiungi contenitore ▸ modello da `docker/unraid/febe.xml` (o dall'indirizzo del modello). Controlla: +3. Docker ▸ Aggiungi contenitore ▸ modello da `docker/unraid/febe.xml` (o dal suo indirizzo, + `http://192.168.30.23:3000/Alby96/Febe/raw/branch/main/docker/unraid/febe.xml`). Controlla: - porta 8480; - `/dati` su `/mnt/user/appdata/febe` (disco di cache); - `/libreria` dove vuoi le foto; `/importa` in sola lettura; - **password dell'interfaccia** (obbligatoria, nascosta); - `TZ`, `PUID` 99, `PGID` 100 tra le impostazioni avanzate; - - in «Extra Parameters»: `--restart=unless-stopped --stop-timeout 30 --security-opt seccomp=/mnt/user/appdata/febe/seccomp.json`. + - in «Extra Parameters»: `--restart=unless-stopped --stop-timeout 30 --security-opt seccomp=/mnt/user/appdata/febe-seccomp.json`. 4. Apri `http://:8480/`, entra con la password, vai in Impostazioni ▸ Collegamento ▸ «Accedi a Instagram»: la vista remota mostra la vera pagina di accesso; scrivi tu nome utente, password ed eventuale codice, poi «Ho finito». Febe comincia qualche minuto dopo, con l'avvio graduale. @@ -124,13 +137,22 @@ Febe non sceglie da solo: se Chromium non parte, il registro dice perché e rima ## Docker Compose `docker/compose.yml` è un esempio pronto: immagine, porta, volumi (con `/importa` in sola lettura), variabili, profilo -seccomp con percorso relativo al file, `restart: unless-stopped`, 30 secondi per fermarsi. `init: true` non serve -(c'è già `tini`) e nemmeno `shm_size` (Chromium usa `/tmp` al posto della memoria condivisa). +seccomp con percorso relativo al file (`chromium/seccomp.json`, fuori da `/dati`), `restart: unless-stopped`, 30 +secondi per fermarsi. `init: true` non serve (c'è già `tini`) e nemmeno `shm_size` (Chromium usa `/tmp` al posto della +memoria condivisa). Anche qui il registro `192.168.30.23:3000` deve stare fra gli `insecure-registries` del Docker. ```sh FEBE_PASSWORD='una frase lunga' docker compose -f docker/compose.yml up -d ``` +Fuori dal repository si usa l'archivio `febe-compose-X.Y.Z.tar.gz` allegato alla release: contiene `compose.yml` e, +accanto, `chromium/seccomp.json`. + +```sh +tar -xzf febe-compose-X.Y.Z.tar.gz && cd febe-compose-X.Y.Z +FEBE_PASSWORD='una frase lunga' docker compose up -d +``` + ## Salute `GET /salute` risponde senza password `{"stato":"ok"}` (200) oppure `{"stato":"problema"}` (503) quando un problema di @@ -145,7 +167,8 @@ c'è curl). Unraid mostra lo stato accanto al contenitore; da terminale: `docker | L'interfaccia mostra solo una pagina «Manca la password dell'interfaccia» | Imposta `FEBE_PASSWORD` e riavvia il contenitore | | «La cartella dei dati è su un disco di rete» o «non può scrivere» | Collega `/dati` a una cartella su un disco locale (su Unraid l'appdata sul disco di cache) e controlla PUID/PGID | | Nel registro: «Il browser non parte… No usable sandbox» | Manca il profilo seccomp: vedi «Sandbox» sopra | -| Unraid non crea il contenitore: «opening seccomp profile … no such file» | Manca `/mnt/user/appdata/febe/seccomp.json`: passo 1 dell'installazione | +| Unraid non crea il contenitore: «opening seccomp profile … no such file» | Manca `/mnt/user/appdata/febe-seccomp.json`: passo 2 dell'installazione | +| Unraid non scarica l'immagine: «http: server gave HTTP response to HTTPS client» | Il registro `192.168.30.23:3000` non è fra gli `insecure-registries`: passo 1 dell'installazione | | La porta è occupata | Cambia la porta pubblicata (o `FEBE_PORTA`) | Il registro di Febe è in `/dati/registro/febe-AAAA-MM-GG.log` e nell'output del contenitore (`docker logs febe`). diff --git a/docs/guida/Installazione-Docker-e-Unraid.md b/docs/guida/Installazione-Docker-e-Unraid.md index 6a17171..7e908a9 100644 --- a/docs/guida/Installazione-Docker-e-Unraid.md +++ b/docs/guida/Installazione-Docker-e-Unraid.md @@ -19,7 +19,7 @@ pagina Impostazioni ▸ Collegamento a Instagram. | Volume | Che cosa contiene | Dove metterlo | |---|---|---| -| `/dati` | Database (`febe.sqlite`), **profilo del browser con la sessione di Instagram** (`browser/`), miniature, copie giornaliere del database (`copie/`, sette giorni), registro (`registro/`, quattordici giorni), file temporanei, `seccomp.json` | Su un **disco locale** del server. Su Unraid `/mnt/user/appdata/febe`. Mai una condivisione di rete: SQLite e il profilo del browser lì si rovinano, e Febe si rifiuta di partire | +| `/dati` | Database (`febe.sqlite`), **profilo del browser con la sessione di Instagram** (`browser/`), miniature, copie giornaliere del database (`copie/`, sette giorni), registro (`registro/`, quattordici giorni), file temporanei | Su un **disco locale** del server. Su Unraid `/mnt/user/appdata/febe`. Mai una condivisione di rete: SQLite e il profilo del browser lì si rovinano, e Febe si rifiuta di partire | | `/libreria` | Foto e video, una cartella per account, ognuna con il suo `_febe.jsonl` | Dove vuoi, anche su una condivisione. Febe non cancella e non sostituisce mai un file da solo | | `/importa` | Cartelle da importare (pagina Importa) | **Sempre in sola lettura** (`:ro`): Febe copia, gli originali non si toccano | @@ -33,7 +33,7 @@ pagina Impostazioni ▸ Collegamento a Instagram. | `LANG` | Lingua del contenitore e quindi del browser | it_IT.UTF-8 | | `PUID`, `PGID` | Utente e gruppo con cui gira Febe e di cui sono i file | 99, 100 (Unraid) | | `FEBE_HOST` | Facoltativa: i nomi con cui raggiungi l'interfaccia, separati da virgole (`tower.local,192.168.1.10`). Se c'è, ogni altro nome è rifiutato | qualunque nome | -| `FEBE_PROXY_FIDATO` | `1` se davanti c'è un proxy con HTTPS che passa `X-Forwarded-Host` | spenta | +| `FEBE_PROXY_FIDATO` | `1` se davanti c'è un proxy con HTTPS che passa `X-Forwarded-Host` e `X-Forwarded-Proto`: allora il cookie di sessione viaggia solo in HTTPS | spenta | | `FEBE_SENZA_SANDBOX` | `1` avvia Chromium senza la sua sandbox: è il compromesso descritto sotto, da usare solo se il profilo seccomp non si può usare | spenta | La password non si passa mai sulla riga di comando e non finisce nei registri. Febe **non gira come root**: con @@ -47,35 +47,47 @@ altrove. ## Installazione su Unraid -1. Dal terminale di Unraid, **una volta sola**, metti il profilo seccomp dove il modello lo cerca: +1. L'immagine è `192.168.30.23:3000/alby96/febe:latest`, sul registro dei container del Gitea di casa. Il registro + risponde in **HTTP**: il Docker di Unraid deve averlo fra gli `insecure-registries`, come per le altre immagini di + casa. Se Unraid scarica già quelle, è a posto; altrimenti aggiungi `"insecure-registries": ["192.168.30.23:3000"]` + alla configurazione del demone Docker e riavvia Docker. Se il pacchetto non è pubblico, accedi dal terminale: + `docker login 192.168.30.23:3000`. +2. Dal terminale di Unraid, **una volta sola**, estrai dall'immagine il profilo seccomp e mettilo dove il modello lo + cerca, **fuori** dalla cartella dei dati: ```sh - mkdir -p /mnt/user/appdata/febe - wget -O /mnt/user/appdata/febe/seccomp.json \ - https://gitea.encke-hake.ts.net/Alby96/Febe/raw/branch/main/docker/chromium/seccomp.json + docker run --rm --entrypoint cat 192.168.30.23:3000/alby96/febe:latest \ + /usr/share/febe/seccomp.json > /mnt/user/appdata/febe-seccomp.json ``` -2. L'immagine è `gitea.encke-hake.ts.net/alby96/febe:latest`, sul registro di Gitea. Se Unraid non riesce a - scaricarla, accedi al registro dal terminale: `docker login gitea.encke-hake.ts.net`. -3. Docker ▸ Aggiungi contenitore ▸ modello da `docker/unraid/febe.xml` (o dal suo indirizzo nel repository). - Controlla: +3. Docker ▸ Aggiungi contenitore ▸ modello da `docker/unraid/febe.xml` (o dal suo indirizzo, + `http://192.168.30.23:3000/Alby96/Febe/raw/branch/main/docker/unraid/febe.xml`). Controlla: - porta 8480; - `/dati` su `/mnt/user/appdata/febe` (disco di cache); - `/libreria` dove vuoi le foto; `/importa` in sola lettura; - **password dell'interfaccia** (obbligatoria, nascosta); - `TZ`, `PUID` 99, `PGID` 100 tra le impostazioni avanzate; - - in «Extra Parameters»: `--restart=unless-stopped --stop-timeout 30 --security-opt seccomp=/mnt/user/appdata/febe/seccomp.json`. + - in «Extra Parameters»: `--restart=unless-stopped --stop-timeout 30 --security-opt seccomp=/mnt/user/appdata/febe-seccomp.json`. 4. Apri `http://:8480/`, entra con la password e segui il [Primo collegamento](Primo-collegamento). ## Docker Compose `docker/compose.yml` nel repository è un esempio pronto: immagine, porta, volumi (con `/importa` in sola lettura), -variabili, profilo seccomp con percorso relativo al file, `restart: unless-stopped`, 30 secondi per fermarsi. +variabili, profilo seccomp con percorso relativo al file, `restart: unless-stopped`, 30 secondi per fermarsi. Anche +qui il registro `192.168.30.23:3000` deve stare fra gli `insecure-registries` del Docker. ```sh FEBE_PASSWORD='una frase lunga' docker compose -f docker/compose.yml up -d ``` +Senza il repository, scarica dalla release l'archivio `febe-compose-X.Y.Z.tar.gz`: dentro c'è `compose.yml` con accanto +`chromium/seccomp.json`, il profilo che il file indica. + +```sh +tar -xzf febe-compose-X.Y.Z.tar.gz && cd febe-compose-X.Y.Z +FEBE_PASSWORD='una frase lunga' docker compose up -d +``` + Le cartelle si cambiano con `FEBE_DATI`, `FEBE_LIBRERIA` e `FEBE_IMPORTA` (predefinite sotto `/srv/febe`). ## La sandbox di Chromium @@ -88,8 +100,11 @@ utente, che il profilo seccomp predefinito di Docker vieta: con le impostazioni Febe (`docker/chromium/seccomp.json`), cioè quello di Docker più `clone` e `unshare`. Con questo profilo la sandbox di Chromium è completa e il resto del filtro di Docker resta attivo. **Così non c'è nessun compromesso sulla sandbox.** -- L'avvio del contenitore copia il profilo in `/dati/seccomp.json` a ogni partenza; Docker però lo legge quando - **crea** il contenitore, quindi la prima volta il file va messo a mano (passo 1 sopra). +- Docker legge il profilo sul server quando **crea** il contenitore, per questo il file sta **fuori** dalla cartella + dei dati (passo 2 sopra): dentro `/dati` lo potrebbe cambiare l'utente del contenitore. Il contenitore non lo + aggiorna da sé; se le note di una versione lo chiedono, ripeti l'estrazione. Nelle prime anteprime il profilo stava in + `/dati/seccomp.json`: se «Extra Parameters» indica ancora quel file, estrai il profilo nel posto nuovo e correggi + il percorso. Se il profilo dedicato non si può usare, ci sono due alternative, in quest'ordine: diff --git a/docs/guida/Problemi-comuni.md b/docs/guida/Problemi-comuni.md index 8fb3dea..38d9fe8 100644 --- a/docs/guida/Problemi-comuni.md +++ b/docs/guida/Problemi-comuni.md @@ -12,11 +12,11 @@ dati. | «La cartella dei dati è su un disco di rete» | Collega `/dati` (su Windows la cartella dei dati) a una cartella su un disco locale: su Unraid l'appdata sul disco di cache. SQLite e il profilo del browser in rete si rovinano | | «La cartella dei dati non è scrivibile» | Controlla `PUID`/`PGID` e i permessi della cartella sul server | | Il contenitore si ferma subito con un messaggio su `PUID=0` | Febe non gira come root: usa un utente normale (su Unraid 99/100) | -| Unraid non crea il contenitore: «opening seccomp profile … no such file» | Manca `/mnt/user/appdata/febe/seccomp.json`: è il passo 1 dell'[installazione](Installazione-Docker-e-Unraid) | +| Unraid non crea il contenitore: «opening seccomp profile … no such file» | Manca `/mnt/user/appdata/febe-seccomp.json`: è il passo 2 dell'[installazione](Installazione-Docker-e-Unraid) | | Nel registro: «Il browser non parte… No usable sandbox» | Il contenitore gira senza il profilo seccomp dedicato: aggiungi `--security-opt seccomp=…` (vedi la sezione sulla sandbox in [Installazione con Docker e Unraid](Installazione-Docker-e-Unraid)) | | La pagina Collegamento dice «Il browser di Febe non è disponibile» | Febe non ha avviato il suo browser: leggi il registro, riavvia; di solito è la sandbox (riga sopra) o la porta di debug occupata | | La porta è occupata | Cambia la porta pubblicata (o `FEBE_PORTA`) | -| Unraid non scarica l'immagine | Accedi al registro di Gitea dal terminale: `docker login gitea.encke-hake.ts.net` | +| Unraid non scarica l'immagine | Il registro `192.168.30.23:3000` è in HTTP: deve stare fra gli `insecure-registries` del Docker di Unraid (vedi l'[installazione](Installazione-Docker-e-Unraid)); se il pacchetto non è pubblico, accedi dal terminale: `docker login 192.168.30.23:3000` | | Il browser rifiuta l'interfaccia con un errore 400 sul nome | `FEBE_HOST` è impostata e il nome con cui apri l'interfaccia non è nell'elenco: aggiungilo | | «Password sbagliata» anche con quella giusta, poi «bloccato» | Dopo 5 errori da uno stesso indirizzo (20 in tutto) l'accesso si blocca per 15 minuti: aspetta, poi riprova | | Su Windows: Febe dice che manca WebView2 | Installa il runtime WebView2 dal collegamento che Febe mostra | diff --git a/docs/guida/Sicurezza-e-riservatezza.md b/docs/guida/Sicurezza-e-riservatezza.md index 0408021..1ee0af0 100644 --- a/docs/guida/Sicurezza-e-riservatezza.md +++ b/docs/guida/Sicurezza-e-riservatezza.md @@ -24,11 +24,13 @@ copia altrove. o attraverso la VPN o il proxy con HTTPS. - L'interfaccia è protetta da password (`FEBE_PASSWORD`), con un cookie di sessione non leggibile dagli script e limitato allo stesso sito (`HttpOnly`, `SameSite=Strict`), valido 30 giorni; dopo 5 tentativi sbagliati da uno - stesso indirizzo, o 20 in tutto in un quarto d'ora, l'accesso si blocca per 15 minuti. + stesso indirizzo, o 20 in tutto in un quarto d'ora, l'accesso si blocca per 15 minuti. Quando arrivi in HTTPS (anche + attraverso il proxy fidato) il cookie è anche `Secure`: il browser non lo manda mai in chiaro. Dopo la password la + pagina di accesso torna solo a una pagina di Febe: un collegamento costruito per portarti su un altro sito non funziona. - Ogni comando, gli eventi dal server e la vista remota controllano che la richiesta arrivi dall'interfaccia stessa (intestazione `Origin`): un'altra pagina aperta nel tuo browser non può comandare Febe né la vista remota. - `FEBE_HOST` limita i nomi con cui si raggiunge l'interfaccia (difesa in più contro il DNS rebinding); - `FEBE_PROXY_FIDATO=1` serve dietro un proxy con HTTPS. + `FEBE_PROXY_FIDATO=1` serve dietro un proxy con HTTPS, che deve passare `X-Forwarded-Host` e `X-Forwarded-Proto`. - Si pubblica solo la porta dell'interfaccia; la porta di debug del browser resta dentro il contenitore, su `127.0.0.1`. ## Windows diff --git a/docs/windows.md b/docs/windows.md index 86a6b02..c02a64f 100644 --- a/docs/windows.md +++ b/docs/windows.md @@ -71,6 +71,9 @@ Windows (ipotesi S3, da confermare: vedi sotto). con lo stesso account sommano le visite e raddoppiano il rischio. Lo dice anche la pagina Collegamento. Per un secondo account serve un secondo Febe con cartelle tutte sue (`Febe.exe --dati D:\FebeSecondo --libreria D:\FotoSecondo`). Febe impedisce due avvii sulla stessa cartella dei dati: un secondo avvio porta in primo piano quello già aperto. +Vale anche subito dopo uno spostamento della cartella dei dati (il Febe che l'ha spostata tiene anche il nome della +nuova) e con due modi di scrivere la stessa cartella (nome corto, `subst`, collegamenti): finché Febe è aperto tiene +il file `febe.lock` nella cartella dei dati, e un secondo Febe che lo trova occupato si ferma e lo dice. ## Area di notifica @@ -99,6 +102,11 @@ Impostazioni ▸ Generali ▸ Avvio ▸ «Avvia Febe all'accensione del computer `--nascosto`: solo l'icona nell'area di notifica, la finestra resta chiusa. Togliendo la spunta il valore sparisce; lo toglie anche la disinstallazione. +Un Febe avviato con `--dati` (un secondo account) ha un valore suo, `Febe-` seguito da sedici cifre esadecimali, con +`--nascosto --dati ""`: all'accensione parte quella cartella, e l'interruttore di un Febe non accende, non +mostra e non toglie l'avvio dell'altro. La disinstallazione toglie anche questi valori, se avviano il Febe.exe +disinstallato. + ## Dove stanno le cose | Che cosa | Dove | Note | @@ -161,7 +169,9 @@ della specifica (§6.6); si sceglie con `--browser` e la scelta resta: Febe passa al browser il mouse e il puntatore della zona della pagina. 3. **`edge`**: Microsoft Edge avviato come processo e pilotato come il Chromium di Docker (`ChromiumProcessHost`, porta di debug fissa 9222 solo su 127.0.0.1), profilo in `Dati\browser\edge`; la sua finestra viene spostata fuori - dallo schermo. Se Edge non c'è, Febe usa la `finestra`. + dallo schermo. Se Edge non c'è, Febe usa la `finestra`. Ogni Edge avviato da Febe sta in un *job object* di Windows + che lo chiude insieme a Febe.exe, anche se Febe si chiude all'improvviso o da Gestione attività: un Edge rimasto + aperto terrebbe la porta 9222 e il browser di Febe non ripartirebbe più. Le prove da fare su un Windows vero, con la procedura esatta, sono in `docs/prove-dal-vivo.md`, **parte C**. In breve: diff --git a/installer/febe.nsi b/installer/febe.nsi index 4bb99f2..b9e0d2a 100644 --- a/installer/febe.nsi +++ b/installer/febe.nsi @@ -182,6 +182,31 @@ Function un.onInit StrCpy $R9 "$PICTURES\Febe" FunctionEnd +; «Avvia con il computer» dei Febe avviati con --dati (un secondo account): valori «Febe-…» che avviano questo Febe.exe. +Function un.TogliAvviiConDati + StrCpy $3 '"$INSTDIR\${ESEGUIBILE}"' + StrLen $4 $3 + StrCpy $0 0 + ciclo: + ClearErrors + EnumRegValue $1 HKCU "${CHIAVE_AVVIO}" $0 + IfErrors fine + StrCmp $1 "" fine + StrCpy $2 $1 5 + ${If} $2 == "Febe-" + ReadRegStr $5 HKCU "${CHIAVE_AVVIO}" $1 + StrCpy $6 $5 $4 + ${If} $6 == $3 + DeleteRegValue HKCU "${CHIAVE_AVVIO}" $1 + ; Il valore successivo prende il posto di quello tolto: stesso indice. + Goto ciclo + ${EndIf} + ${EndIf} + IntOp $0 $0 + 1 + Goto ciclo + fine: +FunctionEnd + Section "Uninstall" Call un.FebeChiuso SetShellVarContext current @@ -193,8 +218,10 @@ Section "Uninstall" Delete "$SMPROGRAMS\Febe.lnk" Delete "$DESKTOP\Febe.lnk" - ; «Avvia Febe all'accensione del computer» punterebbe a un programma che non c'è più. + ; «Avvia Febe all'accensione del computer» punterebbe a un programma che non c'è più: il valore «Febe» e quelli + ; «Febe-…» dei Febe avviati con --dati. DeleteRegValue HKCU "${CHIAVE_AVVIO}" "Febe" + Call un.TogliAvviiConDati DeleteRegKey HKCU "${CHIAVE_DISINSTALLA}" ; Le librerie native che Febe.exe estrae da sé al primo avvio (non sono dati). diff --git a/src/Febe.Browser/Hosting/ChromiumCommandLine.cs b/src/Febe.Browser/Hosting/ChromiumCommandLine.cs index c7546a4..f81aa47 100644 --- a/src/Febe.Browser/Hosting/ChromiumCommandLine.cs +++ b/src/Febe.Browser/Hosting/ChromiumCommandLine.cs @@ -40,6 +40,13 @@ public sealed record ChromiumLaunchOptions /// The Docker image also ships a policy file for the same purpose. /// public bool SeedProfilePreferences { get; init; } = true; + + /// + /// Called with every browser process right after it starts (also after a restart), before it is ready. Windows: Edge + /// is tied to the life of Febe.exe, so that it never outlives a crash of Febe holding the profile and the debugging + /// port. Null: nothing. + /// + public Action? ProcessStarted { get; init; } } /// diff --git a/src/Febe.Browser/Hosting/ChromiumProcessHost.cs b/src/Febe.Browser/Hosting/ChromiumProcessHost.cs index 838afac..680839b 100644 --- a/src/Febe.Browser/Hosting/ChromiumProcessHost.cs +++ b/src/Febe.Browser/Hosting/ChromiumProcessHost.cs @@ -229,6 +229,8 @@ public sealed class ChromiumProcessHost : IBrowserHost private async Task WaitReadyAndConnectAsync(Process process, CancellationToken ct) { + // First of all, as close to the start as possible: the processes the browser opens afterwards follow it. + _launch.ProcessStarted?.Invoke(process); var options = _options ?? throw new InvalidOperationException("Opzioni mancanti."); var port = options.DebugPort; var deadline = _clock.Now + _launch.StartupTimeout; diff --git a/src/Febe.Desktop.Core/Autostart.cs b/src/Febe.Desktop.Core/Autostart.cs index bd331c1..8f426c7 100644 --- a/src/Febe.Desktop.Core/Autostart.cs +++ b/src/Febe.Desktop.Core/Autostart.cs @@ -1,20 +1,34 @@ +using System.Text; + namespace Febe.Desktop.Core; /// -/// «Avvia Febe all'accensione del computer» (spec §12): the value Febe under -/// HKCU\Software\Microsoft\Windows\CurrentVersion\Run, per user, no administrator rights. Febe then starts with -/// --nascosto: only the icon in the notification area, the window stays closed. +/// «Avvia Febe all'accensione del computer» (spec §12): a value under HKCU\Software\Microsoft\Windows\CurrentVersion\Run, +/// per user, no administrator rights. Febe then starts with --nascosto: only the icon in the notification area, +/// the window stays closed. Each Febe has its own value: Febe for the usual one (Data folder recorded or +/// default), Febe-… with --dati for one started on a Data folder of its own (a second account), so the +/// switch of one never starts, shows or removes the other. /// public static class Autostart { /// The registry key, under HKEY_CURRENT_USER. public const string RunKey = @"Software\Microsoft\Windows\CurrentVersion\Run"; - /// The name of the value. + /// The name of the value of the usual Febe. public const string ValueName = "Febe"; - /// The command written in the value: the quoted executable and --nascosto. - public static string Command(string executable) + /// + /// The name of the value: without a Data folder of its own, otherwise «Febe-» and the + /// identity of the folder (the same as the single-instance guard, so the same folder always has the same value). + /// + public static string ValueNameFor(string? fixedDataFolder) => + fixedDataFolder is null ? ValueName : InstanceIdentity.For(fixedDataFolder); + + /// + /// The command written in the value: the quoted executable, --nascosto and, for a Febe started with + /// --dati, the same Data folder. + /// + public static string Command(string executable, string? fixedDataFolder = null) { ArgumentException.ThrowIfNullOrWhiteSpace(executable); if (executable.Contains('"', StringComparison.Ordinal)) @@ -22,43 +36,150 @@ public static class Autostart throw new ArgumentException("Percorso dell'eseguibile non valido.", nameof(executable)); } - return $"\"{executable}\" --nascosto"; + if (fixedDataFolder is null) + { + return $"\"{executable}\" --nascosto"; + } + + if (string.IsNullOrWhiteSpace(fixedDataFolder) || fixedDataFolder.Contains('"', StringComparison.Ordinal)) + { + throw new ArgumentException("Percorso della cartella dei dati non valido.", nameof(fixedDataFolder)); + } + + return $"\"{executable}\" --nascosto --dati {Quote(fixedDataFolder)}"; } - /// True when starts this executable (a value left by another copy of Febe is not ours). - public static bool PointsTo(string? value, string executable) + /// + /// True when starts this executable on this Data folder: + /// for a Febe started with --dati, none for the usual one. A value left by another copy of Febe, or written + /// for another Data folder, is not ours. + /// + public static bool PointsTo(string? value, string executable, string? fixedDataFolder = null) { if (string.IsNullOrWhiteSpace(value) || string.IsNullOrWhiteSpace(executable)) { return false; } - var text = value.Trim(); - string target; - if (text.StartsWith('"')) + var arguments = Split(value.Trim()); + if (arguments is not [var target, .. var rest] || !SamePath(target, executable)) { - var end = text.IndexOf('"', 1); - if (end < 0) + return false; + } + + string? dataFolder = null; + for (var i = 0; i < rest.Count; i++) + { + if (string.Equals(rest[i], "--dati", StringComparison.OrdinalIgnoreCase)) { - return false; + if (i + 1 >= rest.Count) + { + return false; + } + + dataFolder = rest[++i]; + } + } + + return fixedDataFolder is null ? dataFolder is null : dataFolder is not null && SamePath(dataFolder, fixedDataFolder); + } + + /// + /// The words of a command line as Windows programs read them: blanks separate, quotes group, backslashes are plain + /// except before a quote (2n backslashes and a quote: n backslashes and a quote that groups; 2n+1: n and a literal + /// quote). Null for an unfinished quote. + /// + internal static List? Split(string commandLine) + { + var words = new List(); + var word = new StringBuilder(); + var inWord = false; + var quoted = false; + for (var i = 0; i < commandLine.Length; i++) + { + var c = commandLine[i]; + if (c == '\\') + { + var start = i; + while (i < commandLine.Length && commandLine[i] == '\\') + { + i++; + } + + var count = i - start; + if (i < commandLine.Length && commandLine[i] == '"') + { + word.Append('\\', count / 2); + if (count % 2 == 1) + { + word.Append('"'); + } + else + { + quoted = !quoted; + } + } + else + { + word.Append('\\', count); + i--; + } + + inWord = true; + continue; } - target = text[1..end]; - } - else - { - var space = text.IndexOf(' ', StringComparison.Ordinal); - target = space < 0 ? text : text[..space]; + if (c == '"') + { + quoted = !quoted; + inWord = true; + continue; + } + + if (!quoted && char.IsWhiteSpace(c)) + { + if (inWord) + { + words.Add(word.ToString()); + word.Clear(); + inWord = false; + } + + continue; + } + + word.Append(c); + inWord = true; } - return string.Equals(Normalize(target), Normalize(executable), StringComparison.OrdinalIgnoreCase); + if (quoted) + { + return null; + } + + if (inWord) + { + words.Add(word.ToString()); + } + + return words; } + /// A quoted argument: backslashes before the closing quote are doubled ("D:\\" reads back as D:\). + private static string Quote(string argument) + { + var trailing = argument.Length - argument.TrimEnd('\\').Length; + return "\"" + argument + new string('\\', trailing) + "\""; + } + + private static bool SamePath(string a, string b) => + string.Equals(Normalize(a), Normalize(b), StringComparison.OrdinalIgnoreCase); + private static string Normalize(string path) { try { - return Path.GetFullPath(path); + return Path.TrimEndingDirectorySeparator(Path.GetFullPath(path)); } catch (Exception ex) when (ex is ArgumentException or NotSupportedException or PathTooLongException) { diff --git a/src/Febe.Desktop.Core/DataFolderLock.cs b/src/Febe.Desktop.Core/DataFolderLock.cs new file mode 100644 index 0000000..4af8f8e --- /dev/null +++ b/src/Febe.Desktop.Core/DataFolderLock.cs @@ -0,0 +1,89 @@ +namespace Febe.Desktop.Core; + +/// What found. +public enum DataFolderLockOutcome +{ + /// This Febe holds the lock: no other Febe can open the Data folder until it ends. + Acquired, + + /// Another Febe holds it: it is already running on this Data folder. + HeldByAnother, + + /// + /// The lock file cannot be written at all (a folder that is not writable, a file in its place…): the start-up checks + /// explain that problem, and with it Febe starts neither the engine nor the browser. + /// + Unavailable, +} + +/// +/// The second guard of «one Febe at a time on a Data folder» (spec §12, rule 7): the file febe.lock inside the +/// folder, open without sharing for the whole life of the process; Windows closes it when the process ends, even after a +/// crash. The named mutex of is derived from the path, so two spellings of the same folder +/// (a short 8.3 name, a drive letter made with subst, a junction) would get two names; the file is the same one. +/// +public sealed class DataFolderLock : IDisposable +{ + /// The name of the lock file, inside the Data folder. + public const string FileName = "febe.lock"; + + // Windows: ERROR_SHARING_VIOLATION, ERROR_LOCK_VIOLATION. Elsewhere .NET emulates FileShare.None with flock, which + // answers EWOULDBLOCK (11 on Linux, 35 on macOS): only for the tests of this class, Febe.exe runs on Windows. + private const int SharingViolation = 32; + private const int LockViolation = 33; + private const int WouldBlockLinux = 11; + private const int WouldBlockMac = 35; + + private readonly FileStream _file; + + private DataFolderLock(FileStream file, string path) + { + _file = file; + Path = path; + } + + /// The lock file. + public string Path { get; } + + /// + /// Takes the lock of (creating the folder if needed). A file held by someone else is + /// tried again for (an antivirus may look at it for a moment) before it counts as + /// another Febe. + /// + public static DataFolderLockOutcome TryAcquire(string dataFolder, out DataFolderLock? acquired, TimeSpan? patience = null) + { + ArgumentException.ThrowIfNullOrWhiteSpace(dataFolder); + acquired = null; + var path = System.IO.Path.Combine(System.IO.Path.GetFullPath(dataFolder), FileName); + var deadline = DateTime.UtcNow + (patience ?? TimeSpan.FromSeconds(2)); + while (true) + { + try + { + Directory.CreateDirectory(System.IO.Path.GetDirectoryName(path)!); + var file = new FileStream(path, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None, 1, FileOptions.None); + acquired = new DataFolderLock(file, path); + return DataFolderLockOutcome.Acquired; + } + catch (IOException ex) when (IsHeldElsewhere(ex)) + { + if (DateTime.UtcNow >= deadline) + { + return DataFolderLockOutcome.HeldByAnother; + } + + Thread.Sleep(200); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or NotSupportedException or ArgumentException) + { + return DataFolderLockOutcome.Unavailable; + } + } + } + + public void Dispose() => _file.Dispose(); + + private static bool IsHeldElsewhere(IOException ex) => OperatingSystem.IsWindows() + ? (ex.HResult & 0xFFFF) is SharingViolation or LockViolation + : ex.HResult is WouldBlockLinux or WouldBlockMac; +} diff --git a/src/Febe.Desktop.Core/DataFolderMove.cs b/src/Febe.Desktop.Core/DataFolderMove.cs index b88abbb..9f2e49b 100644 --- a/src/Febe.Desktop.Core/DataFolderMove.cs +++ b/src/Febe.Desktop.Core/DataFolderMove.cs @@ -39,7 +39,15 @@ public enum DataFolderMoveOutcome } /// Outcome of , with an Italian message for the log and a notification. -public sealed record DataFolderMoveResult(DataFolderMoveOutcome Outcome, string DataFolder, string? Message); +public sealed record DataFolderMoveResult(DataFolderMoveOutcome Outcome, string DataFolder, string? Message) +{ + /// + /// After a move, the single-instance guard of the new folder, taken before anything was written there: from now on + /// every launch finds the new folder recorded, and must find this Febe holding it. Null when no move happened or no + /// guard was asked for. The caller keeps it for the life of the process. + /// + public IDisposable? TargetGuard { get; init; } +} /// Progress of the copy: files and bytes. public sealed record DataFolderMoveProgress(int FilesDone, int FilesTotal, long BytesDone, long BytesTotal); @@ -107,7 +115,17 @@ public static class DataFolderMove /// /// Applies the move asked from Impostazioni, if any. Call it before anything opens . /// - public static DataFolderMoveResult ApplyPending(IDataFolderLocationStore store, string current, IProgress? progress = null, DataFolderCheck? check = null) + /// Where the folder in use and the pending move are recorded. + /// The Data folder this Febe started on (and holds the single-instance guard of). + /// Progress of the copy. + /// The checks of a Data folder (local disk, writable). + /// + /// Takes the single-instance guard of the new folder (spec §12: one Febe at a time on a Data folder). It is taken + /// before anything is written there, and before the new folder is recorded: a launch that reads the new folder must + /// find this Febe, never start a second one on it. When another Febe holds it the move does not happen. A guard + /// taken for a move that fails is given back. Null: no guard (tests of the copy alone). + /// + public static DataFolderMoveResult ApplyPending(IDataFolderLocationStore store, string current, IProgress? progress = null, DataFolderCheck? check = null, InstanceGuardFactory? claimTarget = null) { ArgumentNullException.ThrowIfNull(store); ArgumentException.ThrowIfNullOrWhiteSpace(current); @@ -124,6 +142,40 @@ public static class DataFolderMove return new DataFolderMoveResult(DataFolderMoveOutcome.Failed, from, $"La cartella dei dati non è stata spostata in {to}: {reason} Febe usa ancora {from}."); } + IDisposable? guard = null; + if (claimTarget is not null) + { + guard = claimTarget(to); + if (guard is null) + { + store.SetPending(null); + return new DataFolderMoveResult( + DataFolderMoveOutcome.Failed, + from, + $"La cartella dei dati non è stata spostata in {to}: un altro Febe la sta già usando. Febe usa ancora {from}."); + } + } + + try + { + var result = Move(store, from, to, progress); + if (result.Outcome == DataFolderMoveOutcome.Failed) + { + guard?.Dispose(); + return result; + } + + return result with { TargetGuard = guard }; + } + catch + { + guard?.Dispose(); + throw; + } + } + + private static DataFolderMoveResult Move(IDataFolderLocationStore store, string from, string to, IProgress? progress) + { if (!Directory.Exists(from)) { // Nothing to copy (Febe never ran here): the new folder is simply used from now on. diff --git a/src/Febe.Desktop.Core/DesktopPlatform.cs b/src/Febe.Desktop.Core/DesktopPlatform.cs index 3f7d0c6..d65691c 100644 --- a/src/Febe.Desktop.Core/DesktopPlatform.cs +++ b/src/Febe.Desktop.Core/DesktopPlatform.cs @@ -47,6 +47,13 @@ public interface IDesktopShell /// Moves the main window of a process (Edge) out of view, still open: never minimised (S2). Task HideProcessWindowAsync(int processId, CancellationToken ct); + + /// + /// Ties a process Febe started (Edge) to the life of Febe.exe: Windows ends it, with the processes it opens, when + /// Febe ends — also after a crash or «Termina attività», so that it never stays behind holding the profile and the + /// debugging port. False when Windows refused (the process then lives on its own, as before). + /// + bool EndWithFebe(System.Diagnostics.Process process); } /// @@ -160,7 +167,9 @@ public sealed class DesktopPlatform : IFebePlatform /// /// Edge for the last fallback of S2: the same as Docker, with its fixed DevTools /// port on 127.0.0.1, a profile of its own inside Dati\browser (so «Scollega» deletes both), preferences - /// with password saving and autofill off, and the switches of S2. + /// with password saving and autofill off, and the switches of S2. Every Edge started is tied to the life of + /// Febe.exe (): an Edge left behind by a crash would keep the port, and every + /// later start would find it «occupata». /// private ChromiumBrowser CreateEdge(FebePlatformContext context, string executable) => new( new ChromiumBrowserSettings @@ -177,6 +186,13 @@ public sealed class DesktopPlatform : IFebePlatform ExtraArguments = BrowserArguments.ForEdge(), SessionCookie = _options.Site.SessionCookie, SeedProfilePreferences = true, + ProcessStarted = process => + { + if (!_shell.EndWithFebe(process)) + { + context.Log.Warn("browser", "Windows non ha legato Edge a Febe: se Febe si chiudesse all'improvviso, Edge resterebbe aperto (chiudilo dal Gestione attività)."); + } + }, }, }, context.Clock, diff --git a/src/Febe.Desktop.Core/SingleInstance.cs b/src/Febe.Desktop.Core/SingleInstance.cs index bb61e20..0160024 100644 --- a/src/Febe.Desktop.Core/SingleInstance.cs +++ b/src/Febe.Desktop.Core/SingleInstance.cs @@ -27,6 +27,12 @@ public static class InstanceIdentity public static string PipeName(string dataFolder) => For(dataFolder); } +/// +/// Takes the single-instance guard of a Data folder (on Windows the named mutex and pipe of ) +/// for this Febe; null when another Febe already holds it. Disposing the guard gives it back. +/// +public delegate IDisposable? InstanceGuardFactory(string dataFolder); + /// What a second launch asks the running Febe. public enum InstanceRequest { diff --git a/src/Febe.Desktop/DesktopApplication.cs b/src/Febe.Desktop/DesktopApplication.cs index 4c96c07..ba701ef 100644 --- a/src/Febe.Desktop/DesktopApplication.cs +++ b/src/Febe.Desktop/DesktopApplication.cs @@ -26,9 +26,13 @@ internal sealed class DesktopApplication : Application private readonly DesktopFolders _folders; private readonly IDataFolderLocationStore _locations; private readonly bool _dataFolderFixed; - private readonly SingleInstanceGuard _instance; + + // The single-instance guards this Febe holds: the one of the folder it started on (taken by Program, disposed there) + // and, after a move, the one of the new folder — which every later launch finds recorded. + private readonly List _instances; private readonly CancellationTokenSource _lifetime = new(); private string _dataFolder; + private DataFolderLock? _dataLock; private ImageSource? _iconImage; private TrayIcon? _tray; private DesktopPlatform? _platform; @@ -44,7 +48,7 @@ internal sealed class DesktopApplication : Application _locations = locations; _dataFolder = dataFolder; _dataFolderFixed = dataFolderFixed; - _instance = instance; + _instances = [instance]; ShutdownMode = ShutdownMode.OnExplicitShutdown; DispatcherUnhandledException += OnDispatcherUnhandledException; TaskScheduler.UnobservedTaskException += (_, e) => e.SetObserved(); @@ -85,13 +89,34 @@ internal sealed class DesktopApplication : Application { moved = await MoveDataFolderAsync().ConfigureAwait(true); _dataFolder = moved.DataFolder; + if (moved.TargetGuard is SingleInstanceGuard guard) + { + _instances.Add(guard); + } + if (moved.Message is { } message) { _tray.Notify("Cartella dei dati", message, moved.Outcome != DataFolderMoveOutcome.Moved); } } - var native = new WindowsShell(Dispatcher, () => _main, () => _tray); + // The folder itself is locked too: the guards are named after its path, the lock is the folder (spec §12). + if (DataFolderLock.TryAcquire(_dataFolder, out _dataLock) == DataFolderLockOutcome.HeldByAnother) + { + if (!_options.StartHidden) + { + MessageBox.Show( + $"Febe è già aperto con questa cartella dei dati ({_dataFolder}): cercalo nell'area di notifica, accanto all'orologio.", + "Febe", + MessageBoxButton.OK, + MessageBoxImage.Information); + } + + await ExitAsync().ConfigureAwait(true); + return; + } + + var native = new WindowsShell(Dispatcher, () => _main, () => _tray, _dataFolderFixed ? _dataFolder : null); var shell = new DesktopShell(Dispatcher, _iconImage, native); _platform = new DesktopPlatform(_options, shell, _locations, _dataFolderFixed); _app = await FebeApp.StartAsync(_options.AppOptions(_dataFolder, _folders), _platform, new FebeAppHooks(), _lifetime.Token).ConfigureAwait(true); @@ -124,13 +149,17 @@ internal sealed class DesktopApplication : Application return; } - _instance.Listen(request => Dispatcher.InvokeAsync(() => + foreach (var instance in _instances) { - if (request == InstanceRequest.Show) + instance.Listen(request => Dispatcher.InvokeAsync(() => { - ShowMain(); - } - })); + if (request == InstanceRequest.Show) + { + ShowMain(); + } + })); + } + _ = Task.Run(() => FollowEngineAsync(_lifetime.Token)); if (!_options.StartHidden || _app.Problems.Count > 0) @@ -298,7 +327,7 @@ internal sealed class DesktopApplication : Application bar.Value = p.FilesDone; }); var current = _dataFolder; - return await Task.Run(() => DataFolderMove.ApplyPending(_locations, current, progress)).ConfigureAwait(true); + return await Task.Run(() => DataFolderMove.ApplyPending(_locations, current, progress, claimTarget: SingleInstanceGuard.TryAcquire)).ConfigureAwait(true); } finally { @@ -335,6 +364,21 @@ internal sealed class DesktopApplication : Application _tray = null; } + /// + /// Everything has stopped: the lock of the Data folder and the guard of a moved folder go last. The guard of the + /// folder Febe started on belongs to Program, which disposes it when the application returns. + /// + protected override void OnExit(ExitEventArgs e) + { + _dataLock?.Dispose(); + foreach (var instance in _instances.Skip(1)) + { + instance.Dispose(); + } + + base.OnExit(e); + } + /// Windows is shutting down or Alberto logs off: stop in order while the messages still flow (S3). private void OnSessionEnding(object sender, SessionEndingCancelEventArgs e) { diff --git a/src/Febe.Desktop/DesktopShell.cs b/src/Febe.Desktop/DesktopShell.cs index 5dd1289..7891c07 100644 --- a/src/Febe.Desktop/DesktopShell.cs +++ b/src/Febe.Desktop/DesktopShell.cs @@ -89,6 +89,8 @@ internal sealed class DesktopShell(Dispatcher ui, ImageSource? icon, INativeShel Win32.SetWindowPos(window, IntPtr.Zero, x, y, 0, 0, Win32.SwpNoSize | Win32.SwpNoZOrder | Win32.SwpNoActivate); }).Task; + public bool EndWithFebe(Process process) => ProcessJob.Add(process); + private static IntPtr? MainWindowOf(int processId) { try diff --git a/src/Febe.Desktop/Native/ProcessJob.cs b/src/Febe.Desktop/Native/ProcessJob.cs new file mode 100644 index 0000000..4aab2e0 --- /dev/null +++ b/src/Febe.Desktop/Native/ProcessJob.cs @@ -0,0 +1,116 @@ +using System.Diagnostics; +using System.Runtime.InteropServices; +using Microsoft.Win32.SafeHandles; + +namespace Febe.Desktop.Native; + +/// +/// A job object of Windows with «kill on job close»: the processes put in it end when Febe.exe ends, however it ends +/// (Esci, a crash, «Termina attività»), because Windows closes the job's only handle with the process. The processes +/// they start join the job too. Used for Edge, the last fallback of S2 (spec §6.6): without it an Edge left behind keeps +/// the profile and the debugging port 9222, and every later start of Febe finds the port «occupata». +/// +internal static class ProcessJob +{ + private const int JobObjectExtendedLimitInformation = 9; + private const uint JobObjectLimitKillOnJobClose = 0x00002000; + + private static readonly Lazy Job = new(Create, LazyThreadSafetyMode.ExecutionAndPublication); + + /// Puts in the job; false when Windows refuses (the process then lives on its own). + public static bool Add(Process process) + { + ArgumentNullException.ThrowIfNull(process); + if (Job.Value is not { IsInvalid: false } job) + { + return false; + } + + try + { + return AssignProcessToJobObject(job, process.Handle); + } + catch (Exception ex) when (ex is InvalidOperationException or System.ComponentModel.Win32Exception or NotSupportedException) + { + // The process is already gone. + return false; + } + } + + /// The job, created once and never closed: closing it would end the processes inside it. + private static SafeFileHandle? Create() + { + var job = CreateJobObject(IntPtr.Zero, null); + if (job.IsInvalid) + { + job.Dispose(); + return null; + } + + var limits = new ExtendedLimitInformation { BasicLimitInformation = new BasicLimitInformation { LimitFlags = JobObjectLimitKillOnJobClose } }; + var size = Marshal.SizeOf(); + var buffer = Marshal.AllocHGlobal(size); + try + { + Marshal.StructureToPtr(limits, buffer, fDeleteOld: false); + if (!SetInformationJobObject(job, JobObjectExtendedLimitInformation, buffer, (uint)size)) + { + job.Dispose(); + return null; + } + } + finally + { + Marshal.FreeHGlobal(buffer); + } + + return job; + } + + [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)] + private static extern SafeFileHandle CreateJobObject(IntPtr attributes, string? name); + + [DllImport("kernel32.dll", SetLastError = true)] + [return: MarshalAs(UnmanagedType.Bool)] + private static extern bool SetInformationJobObject(SafeFileHandle job, int infoClass, IntPtr info, uint length); + + [DllImport("kernel32.dll", SetLastError = true)] + [return: MarshalAs(UnmanagedType.Bool)] + private static extern bool AssignProcessToJobObject(SafeFileHandle job, IntPtr process); + + [StructLayout(LayoutKind.Sequential)] + private struct BasicLimitInformation + { + public long PerProcessUserTimeLimit; + public long PerJobUserTimeLimit; + public uint LimitFlags; + public UIntPtr MinimumWorkingSetSize; + public UIntPtr MaximumWorkingSetSize; + public uint ActiveProcessLimit; + public UIntPtr Affinity; + public uint PriorityClass; + public uint SchedulingClass; + } + + [StructLayout(LayoutKind.Sequential)] + private struct IoCounters + { + public ulong ReadOperationCount; + public ulong WriteOperationCount; + public ulong OtherOperationCount; + public ulong ReadTransferCount; + public ulong WriteTransferCount; + public ulong OtherTransferCount; + } + + [StructLayout(LayoutKind.Sequential)] + private struct ExtendedLimitInformation + { + public BasicLimitInformation BasicLimitInformation; + public IoCounters IoInfo; + public UIntPtr ProcessMemoryLimit; + public UIntPtr JobMemoryLimit; + public UIntPtr PeakProcessMemoryUsed; + public UIntPtr PeakJobMemoryUsed; + } +} diff --git a/src/Febe.Desktop/SingleInstanceGuard.cs b/src/Febe.Desktop/SingleInstanceGuard.cs index 220a52b..e84b109 100644 --- a/src/Febe.Desktop/SingleInstanceGuard.cs +++ b/src/Febe.Desktop/SingleInstanceGuard.cs @@ -6,7 +6,9 @@ namespace Febe.Desktop; /// /// One Febe at a time for a Data folder (spec §12): a named mutex in the session namespace, and a named pipe (current -/// user only) through which a second launch asks the first to show its window, then exits. +/// user only) through which a second launch asks the first to show its window, then exits. What counts is that the +/// mutex exists, not which thread owns it: a guard can be taken on any thread (the move of the Data folder takes the +/// guard of the new folder on a worker thread) and lives until it is disposed or the process ends. /// internal sealed class SingleInstanceGuard : IDisposable { @@ -24,7 +26,8 @@ internal sealed class SingleInstanceGuard : IDisposable /// The guard of the first instance, or null when another Febe already runs on this Data folder. public static SingleInstanceGuard? TryAcquire(string dataFolder) { - var mutex = new Mutex(initiallyOwned: true, InstanceIdentity.MutexName(dataFolder), out var created); + // Not owned: ownership belongs to a thread, while the guard belongs to the process. + var mutex = new Mutex(initiallyOwned: false, InstanceIdentity.MutexName(dataFolder), out var created); if (!created) { mutex.Dispose(); @@ -69,15 +72,6 @@ internal sealed class SingleInstanceGuard : IDisposable { } - try - { - _mutex.ReleaseMutex(); - } - catch (ApplicationException) - { - // Released on another thread already: Windows releases it when the process ends. - } - _mutex.Dispose(); _stop.Dispose(); } diff --git a/src/Febe.Desktop/WindowsShell.cs b/src/Febe.Desktop/WindowsShell.cs index c46f1eb..7b7b7ce 100644 --- a/src/Febe.Desktop/WindowsShell.cs +++ b/src/Febe.Desktop/WindowsShell.cs @@ -12,9 +12,11 @@ namespace Febe.Desktop; /// «Mostra nella cartella» (explorer.exe /select,"…"), addresses in the default browser (shell execute), Windows /// notifications (balloon tips of the notification-area icon: the alerts of spec §13.3 arrive here through /// , and «Invia una prova») and start with the computer -/// (HKCU\…\Run, value Febe). Paths and addresses never come from the page: the web layer resolves them. +/// (HKCU\…\Run, value Febe, or Febe-… with --dati for a Febe started on a Data folder of +/// its own: , see ). Paths and addresses never come from the +/// page: the web layer resolves them. /// -internal sealed class WindowsShell(Dispatcher ui, Func owner, Func tray) : INativeShell +internal sealed class WindowsShell(Dispatcher ui, Func owner, Func tray, string? fixedDataFolder) : INativeShell { public bool CanPickFolder => true; @@ -85,8 +87,8 @@ internal sealed class WindowsShell(Dispatcher ui, Func owner, Func GetAutostartAsync(CancellationToken ct) { using var key = Registry.CurrentUser.OpenSubKey(Autostart.RunKey, writable: false); - var value = key?.GetValue(Autostart.ValueName) as string; - return Task.FromResult(Environment.ProcessPath is { } exe && Autostart.PointsTo(value, exe)); + var value = key?.GetValue(Autostart.ValueNameFor(fixedDataFolder)) as string; + return Task.FromResult(Environment.ProcessPath is { } exe && Autostart.PointsTo(value, exe, fixedDataFolder)); } public Task SetAutostartAsync(bool enabled, CancellationToken ct) @@ -95,11 +97,11 @@ internal sealed class WindowsShell(Dispatcher ui, Func owner, Func + endpoints.MapPost("/api/uscita", (HttpContext context, FebeWebOptions options) => { context.RequestServices.GetService()?.Logout(context.Request.Cookies[PasswordAccess.CookieName]); - context.Response.Cookies.Delete(PasswordAccess.CookieName, new CookieOptions { Path = "/", SameSite = SameSiteMode.Strict, HttpOnly = true }); + context.Response.Cookies.Delete(PasswordAccess.CookieName, new CookieOptions + { + Path = "/", + SameSite = SameSiteMode.Strict, + HttpOnly = true, + Secure = RequestScheme.IsHttps(context.Request, options), + }); return ApiHttp.Message("Sei uscito da Febe."); }); } diff --git a/src/Febe.Web/Security/LoginReturn.cs b/src/Febe.Web/Security/LoginReturn.cs new file mode 100644 index 0000000..37c0241 --- /dev/null +++ b/src/Febe.Web/Security/LoginReturn.cs @@ -0,0 +1,57 @@ +using Microsoft.AspNetCore.Http; + +namespace Febe.Web.Security; + +/// +/// Where the login page goes back after the password (spec §13.1): /accesso?torna=…. Only a page of this +/// interface, never another site. A browser reads //host as an address of another site, and turns /\host +/// into //host as well (a backslash counts as a slash, tabs and new lines are dropped), so the value must be one +/// path that starts with a single slash and holds no backslash, blank or control character. The login page script +/// (js/core/return-path.js) applies the same rule. +/// +public static class LoginReturn +{ + /// The name of the query parameter of the login page. + public const string QueryName = "torna"; + + /// The longest path accepted (a real page address is much shorter). + public const int MaxLength = 2048; + + /// when it is a path of this interface; null otherwise. + public static string? Sanitize(string? value) => IsSafe(value) ? value : null; + + /// True when can only lead to a page of this interface. + public static bool IsSafe(string? value) + { + if (string.IsNullOrEmpty(value) || value.Length > MaxLength || value[0] != '/') + { + return false; + } + + if (value.Length > 1 && value[1] is '/' or '\\') + { + return false; + } + + foreach (var c in value) + { + if (c == '\\' || c <= ' ' || c == '\u007f' || char.IsWhiteSpace(c) || char.IsControl(c)) + { + return false; + } + } + + return true; + } + + /// The address of the login page that goes back to (or just the login page). + public static string LoginAddress(string? path) => + Sanitize(path) is { } safe ? "/accesso?" + QueryName + "=" + Uri.EscapeDataString(safe) : "/accesso"; + + /// True when the request carries a torna that is not a path of this interface. + public static bool HasUnsafeReturn(HttpRequest request) + { + ArgumentNullException.ThrowIfNull(request); + return request.Query.TryGetValue(QueryName, out var values) && values.Any(v => !IsSafe(v)); + } +} diff --git a/src/Febe.Web/Security/RequestScheme.cs b/src/Febe.Web/Security/RequestScheme.cs new file mode 100644 index 0000000..f8c687e --- /dev/null +++ b/src/Febe.Web/Security/RequestScheme.cs @@ -0,0 +1,32 @@ +using Microsoft.AspNetCore.Http; + +namespace Febe.Web.Security; + +/// +/// Whether a request reached Febe over HTTPS, for the Secure flag of its cookies (spec §11, §13.1). Febe itself +/// listens on plain HTTP; remote access goes through a proxy with HTTPS in front, which terminates TLS. Only that trusted +/// proxy (FEBE_PROXY_FIDATO=1) can say so, with X-Forwarded-Proto: https: from anyone else the header is +/// ignored. +/// +public static class RequestScheme +{ + /// True when the browser talked HTTPS: directly, or to the trusted proxy in front of Febe. + public static bool IsHttps(HttpRequest request, FebeWebOptions options) + { + ArgumentNullException.ThrowIfNull(request); + ArgumentNullException.ThrowIfNull(options); + if (request.IsHttps) + { + return true; + } + + if (!options.TrustForwardedHost) + { + return false; + } + + // The first value is the one the proxy closest to the browser wrote. + var forwarded = request.Headers["X-Forwarded-Proto"].ToString().Split(',')[0].Trim(); + return string.Equals(forwarded, Uri.UriSchemeHttps, StringComparison.OrdinalIgnoreCase); + } +} diff --git a/src/Febe.Web/Security/SecurityMiddleware.cs b/src/Febe.Web/Security/SecurityMiddleware.cs index 05cff20..980d603 100644 --- a/src/Febe.Web/Security/SecurityMiddleware.cs +++ b/src/Febe.Web/Security/SecurityMiddleware.cs @@ -47,6 +47,14 @@ public sealed class SecurityMiddleware(RequestDelegate next, FebeWebOptions opti return; } + // The login page with a «torna» that leads out of the interface (a crafted link: «/\host», «//host»): the + // value is dropped before the page even shows, so after the password Febe goes only to its own pages. + if (IsLoginPage(request) && LoginReturn.HasUnsafeReturn(request)) + { + response.Redirect("/accesso"); + return; + } + switch (options.Access) { case AccessMode.Token: @@ -85,7 +93,7 @@ public sealed class SecurityMiddleware(RequestDelegate next, FebeWebOptions opti { HttpOnly = true, SameSite = SameSiteMode.Strict, - Secure = request.IsHttps, + Secure = RequestScheme.IsHttps(request, options), Path = "/", IsEssential = true, }); @@ -141,12 +149,19 @@ public sealed class SecurityMiddleware(RequestDelegate next, FebeWebOptions opti } else { - context.Response.Redirect("/accesso?torna=" + Uri.EscapeDataString(path)); + // Back to this page after the password; a path that would lead out of the interface is not carried. + context.Response.Redirect(LoginReturn.LoginAddress(path)); } return false; } + /// The login page: /accesso, or its file /accesso.html served as it is. + private static bool IsLoginPage(HttpRequest request) => + (HttpMethods.IsGet(request.Method) || HttpMethods.IsHead(request.Method)) + && (string.Equals(request.Path.Value, "/accesso", StringComparison.OrdinalIgnoreCase) + || string.Equals(request.Path.Value, "/accesso.html", StringComparison.OrdinalIgnoreCase)); + private static bool IsApi(HttpRequest request) => request.Path.StartsWithSegments("/api", StringComparison.OrdinalIgnoreCase); /// What may be read without a password: the error page and what it needs, never a command. diff --git a/src/Febe.Web/wwwroot/js/accesso.js b/src/Febe.Web/wwwroot/js/accesso.js index 79d18ae..8065795 100644 --- a/src/Febe.Web/wwwroot/js/accesso.js +++ b/src/Febe.Web/wwwroot/js/accesso.js @@ -3,6 +3,7 @@ import { h, fill, brand } from './core/dom.js'; import { loadTexts, t } from './core/text.js'; +import { returnAddress } from './core/return-path.js'; async function boot() { await loadTexts('it'); @@ -31,8 +32,8 @@ async function boot() { }); const data = await response.json().catch(() => ({})); if (response.ok && data.ok) { - const back = new URLSearchParams(location.search).get('torna'); - location.href = back && back.startsWith('/') && !back.startsWith('//') ? back : '/libreria'; + // Back to the page Alberto was opening: only a page of this interface, never another site. + location.href = returnAddress(new URLSearchParams(location.search).get('torna'), location.origin); return; } message.textContent = data.message || t('accesso.sbagliata'); diff --git a/src/Febe.Web/wwwroot/js/core/return-path.js b/src/Febe.Web/wwwroot/js/core/return-path.js new file mode 100644 index 0000000..775a9c6 --- /dev/null +++ b/src/Febe.Web/wwwroot/js/core/return-path.js @@ -0,0 +1,24 @@ +// Where the login page goes after the password (spec §13.1): the page Alberto was opening («?torna=/account/12»), +// never another site. A link can hide another site in many ways: «//host», «/\host» (a backslash counts as a slash), +// «/%09/host» (tabs and new lines are dropped). The same rule as the server (Febe.Web.Security.LoginReturn): one path +// that starts with a single slash, without backslashes, blanks or control characters; then the address it resolves to +// must still be on this origin, and the page goes to that absolute address (nothing left to read twice). + +const SAFE = /^\/(?![\/\\])[^\\\s\u0000-\u001f\u007f-\u009f]*$/; + +export const DEFAULT_PAGE = '/libreria'; + +/** The absolute address to open after the login, on only; the library when is missing or unsafe. */ +export function returnAddress(value, origin) { + const fallback = new URL(DEFAULT_PAGE, origin).href; + if (typeof value !== 'string' || value.length > 2048 || !SAFE.test(value)) { + return fallback; + } + + try { + const target = new URL(value, origin); + return target.origin === new URL(origin).origin ? target.href : fallback; + } catch { + return fallback; + } +} diff --git a/tests/Febe.Tests/Desktop/DesktopCompositionTests.cs b/tests/Febe.Tests/Desktop/DesktopCompositionTests.cs index 104e132..9b28c33 100644 --- a/tests/Febe.Tests/Desktop/DesktopCompositionTests.cs +++ b/tests/Febe.Tests/Desktop/DesktopCompositionTests.cs @@ -305,4 +305,43 @@ public sealed class DesktopCompositionTests await DesktopTestBed.WaitUntilAsync(() => browser.LastError is not null, TimeSpan.FromSeconds(10), "il tentativo di avviare Edge"); Assert.IsFalse(browser.IsAvailable, "the fake msedge.exe does not exist: the browser is retried, nothing else breaks"); } + + [TestMethod] + [Timeout(60_000, CooperativeCancellation = true)] + public async Task EveryEdgeFebeStartsIsTiedToFebeSoACrashLeavesNoEdgeHoldingThePort() + { + if (!OperatingSystem.IsLinux()) + { + Assert.Inconclusive("Il finto msedge.exe di questa prova è uno script di shell."); + return; + } + + // An «Edge» that starts and closes at once: every start must be tied to Febe before anything else happens, also + // the starts that fail and the ones after (pkg-6: an Edge left behind by a crash keeps the port 9222). + using var temp = new TempFolder("desktop-edge"); + var edge = temp.Combine("Edge", "msedge.exe"); + Directory.CreateDirectory(Path.GetDirectoryName(edge)!); + await File.WriteAllTextAsync(edge, "#!/bin/sh\nexit 3\n", TestContext.CancellationToken); + File.SetUnixFileMode(edge, UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.UserExecute); + var shell = new FakeDesktopShell { EdgePath = edge, TieSucceeds = false }; + await using var bed = await DesktopTestBed.StartAsync(["--browser", "edge"], shell, temp, adjust: o => o with { EdgeDebugPort = FreePort() }); + await DesktopTestBed.WaitUntilAsync(() => !shell.TiedToFebe.IsEmpty, TimeSpan.FromSeconds(20), "Edge legato alla vita di Febe"); + var browser = (EdgeBrowser)bed.App.Browser!; + await DesktopTestBed.WaitUntilAsync(() => browser.LastError is not null, TimeSpan.FromSeconds(20), "il primo avvio di Edge, che si chiude subito"); + Assert.IsFalse(browser.IsAvailable); + await bed.StopAsync(); + + // Windows refused: the log says what to do, in Italian. + var log = string.Concat(Directory.EnumerateFiles(Path.Combine(bed.Folders.DefaultDataFolder, "registro")).Select(File.ReadAllText)); + StringAssert.Contains(log, "Windows non ha legato Edge a Febe"); + } + + private static int FreePort() + { + var listener = new System.Net.Sockets.TcpListener(IPAddress.Loopback, 0); + listener.Start(); + var port = ((IPEndPoint)listener.LocalEndpoint).Port; + listener.Stop(); + return port; + } } diff --git a/tests/Febe.Tests/Desktop/DesktopLogicTests.cs b/tests/Febe.Tests/Desktop/DesktopLogicTests.cs index 1e7998b..697c99f 100644 --- a/tests/Febe.Tests/Desktop/DesktopLogicTests.cs +++ b/tests/Febe.Tests/Desktop/DesktopLogicTests.cs @@ -295,6 +295,170 @@ public sealed class DesktopLogicTests Assert.IsNull(store.Pending); } + [TestMethod] + public void AfterAMoveThisFebeHoldsTheNewFolderSoASecondLaunchDoesNotStartASecondFebe() + { + // pkg-1: the guard is named after the Data folder. After a move every launch reads the new folder: this Febe + // must hold its guard, or the next launch would start a second interface, browser and engine on it. + using var temp = new TempFolder("desktop-sposta"); + var from = temp.Combine("vecchia"); + var to = temp.Combine("nuova"); + Directory.CreateDirectory(from); + File.WriteAllText(Path.Combine(from, "febe.sqlite"), "database"); + var guards = new FakeInstanceGuards(); + var store = new MemoryLocationStore { Pending = to }; + using var started = guards.TryAcquire(from); + Assert.IsNotNull(started, "Program: the guard of the folder this Febe started on"); + + (string? Recorded, bool Written)? atClaim = null; + var result = DataFolderMove.ApplyPending(store, from, claimTarget: folder => + { + atClaim = (store.Current, Directory.Exists(folder)); + return guards.TryAcquire(folder); + }); + Assert.AreEqual(DataFolderMoveOutcome.Moved, result.Outcome, result.Message); + Assert.AreEqual((null, false), atClaim, "the guard comes before the folder is recorded and before anything is written in it"); + Assert.IsNotNull(result.TargetGuard); + Assert.AreEqual(Path.GetFullPath(to), store.Current); + + // The next launch (Start menu, a start with the computer) reads the recorded folder and finds this Febe. + Assert.IsNull(guards.TryAcquire(store.Current!), "a second launch signals this Febe instead of starting another"); + result.TargetGuard!.Dispose(); + using var afterExit = guards.TryAcquire(store.Current!); + Assert.IsNotNull(afterExit, "after Esci the folder is free again"); + } + + [TestMethod] + public void AMoveIntoAFolderAnotherFebeHoldsDoesNotHappenAndAFailedMoveGivesTheGuardBack() + { + using var temp = new TempFolder("desktop-sposta"); + var from = temp.Combine("vecchia"); + Directory.CreateDirectory(from); + File.WriteAllText(Path.Combine(from, "febe.sqlite"), "database"); + var guards = new FakeInstanceGuards(); + + // Another Febe (started with --dati) already holds the new folder: nothing is copied, the old folder stays. + var taken = temp.Combine("presa"); + using (guards.TryAcquire(taken)) + { + var store = new MemoryLocationStore { Pending = taken }; + var refused = DataFolderMove.ApplyPending(store, from, claimTarget: guards.TryAcquire); + Assert.AreEqual(DataFolderMoveOutcome.Failed, refused.Outcome); + StringAssert.Contains(refused.Message, "un altro Febe la sta già usando"); + Assert.IsNull(refused.TargetGuard); + Assert.IsNull(store.Pending); + Assert.IsNull(store.Current); + Assert.IsFalse(Directory.Exists(taken), "nothing written there"); + Assert.IsTrue(File.Exists(Path.Combine(from, "febe.sqlite"))); + } + + // A copy that fails: Febe stays on the old folder and does not keep the guard of the new one. + var halfway = temp.Combine("a-meta"); + var failing = new MemoryLocationStore { Pending = halfway }; + var failed = DataFolderMove.ApplyPending(failing, from, new SyncProgress(_ => throw new IOException("disco pieno")), claimTarget: guards.TryAcquire); + Assert.AreEqual(DataFolderMoveOutcome.Failed, failed.Outcome); + Assert.IsNull(failed.TargetGuard); + using var free = guards.TryAcquire(halfway); + Assert.IsNotNull(free, "the guard of a move that did not happen is given back"); + } + + [TestMethod] + public void TheDataFolderLockLetsOneFebeOpenTheFolderWhateverItsSpelling() + { + using var temp = new TempFolder("desktop-blocco"); + var data = temp.Combine("dati"); + Assert.AreEqual(DataFolderLockOutcome.Acquired, DataFolderLock.TryAcquire(data, out var first, TimeSpan.Zero)); + Assert.IsNotNull(first); + Assert.AreEqual(Path.Combine(data, DataFolderLock.FileName), first.Path); + Assert.IsTrue(File.Exists(first.Path)); + + // The same folder under another name (on Windows: a short 8.3 name, subst, a junction; here a symbolic link): + // the guards are named after the path and differ, the lock is the same file. + var alias = temp.Combine("alias"); + Directory.CreateSymbolicLink(alias, data); + Assert.AreNotEqual(InstanceIdentity.For(data), InstanceIdentity.For(alias)); + Assert.AreEqual(DataFolderLockOutcome.HeldByAnother, DataFolderLock.TryAcquire(alias, out var second, TimeSpan.Zero)); + Assert.IsNull(second); + + // Held for a moment only (an antivirus looking at the file): the start waits instead of giving up. + var release = Task.Run(async () => + { + await Task.Delay(300, TestContext.CancellationToken); + first.Dispose(); + }, TestContext.CancellationToken); + Assert.AreEqual(DataFolderLockOutcome.Acquired, DataFolderLock.TryAcquire(alias, out var later, TimeSpan.FromSeconds(10))); + release.Wait(TestContext.CancellationToken); + later!.Dispose(); + + // A Data folder where nothing can be written: the start-up checks explain it, the lock does not decide. + var file = temp.Combine("un-file"); + File.WriteAllText(file, "x"); + Assert.AreEqual(DataFolderLockOutcome.Unavailable, DataFolderLock.TryAcquire(file, out var none, TimeSpan.Zero)); + Assert.IsNull(none); + } + + [TestMethod] + public void AFebeStartedWithItsOwnDataFolderHasItsOwnStartWithTheComputer() + { + // pkg-5: «Febe.exe --dati D:\FebeSecondo» (a second account) must start that folder at the next login, and its + // switch must neither show nor remove the start of the usual Febe. + var exe = Path.Combine(Path.GetTempPath(), "Programmi", "Febe", "Febe.exe"); + var second = Path.Combine(Path.GetTempPath(), "Febe Secondo"); + Assert.AreEqual("Febe", Autostart.ValueNameFor(null)); + Assert.AreEqual(InstanceIdentity.For(second), Autostart.ValueNameFor(second)); + StringAssert.StartsWith(Autostart.ValueNameFor(second), "Febe-"); + Assert.AreNotEqual(Autostart.ValueNameFor(second), Autostart.ValueNameFor(second + "2")); + + var command = Autostart.Command(exe, second); + Assert.AreEqual($"\"{exe}\" --nascosto --dati \"{second}\"", command); + Assert.IsTrue(Autostart.PointsTo(command, exe, second)); + Assert.IsTrue(Autostart.PointsTo(command, exe, second + Path.DirectorySeparatorChar), "the same folder"); + Assert.IsFalse(Autostart.PointsTo(command, exe), "the usual Febe does not take it for its own"); + Assert.IsFalse(Autostart.PointsTo(Autostart.Command(exe), exe, second), "nor the reverse: that command starts the usual folder"); + Assert.IsFalse(Autostart.PointsTo(Autostart.Command(exe, second + "2"), exe, second), "another account"); + Assert.IsFalse(Autostart.PointsTo($"\"{exe}\" --nascosto --dati", exe, second)); + + // Febe.exe reads the command back as written: hidden, on that Data folder. + var words = Autostart.Split(command)!; + Assert.AreEqual(exe, words[0]); + Assert.IsTrue(DesktopCommandLine.TryParse([.. words.Skip(1)], out var options, out var problem), problem); + Assert.IsTrue(options.StartHidden); + Assert.AreEqual(Path.GetFullPath(second), options.DataFolder); + + // A folder at the root of a drive: the backslash before the closing quote is doubled, so it reads back whole. + CollectionAssert.AreEqual(new[] { exe, "--nascosto", "--dati", @"D:\" }, Autostart.Split(Autostart.Command(exe, @"D:\"))); + CollectionAssert.AreEqual(new[] { "a", "b\"c", @"d\e" }, Autostart.Split("a \"b\\\"c\" d\\e")); + Assert.ThrowsExactly(() => Autostart.Command(exe, "C:\\a\"b")); + } + + /// The single-instance guards of Windows (named mutexes), by Data folder, in memory. + private sealed class FakeInstanceGuards + { + private readonly HashSet _held = []; + + public IDisposable? TryAcquire(string dataFolder) + { + var name = InstanceIdentity.MutexName(dataFolder); + lock (_held) + { + return _held.Add(name) ? new Guard(this, name) : null; + } + } + + private void Release(string name) + { + lock (_held) + { + _held.Remove(name); + } + } + + private sealed class Guard(FakeInstanceGuards owner, string name) : IDisposable + { + public void Dispose() => owner.Release(name); + } + } + private sealed class SyncProgress(Action report) : IProgress { public void Report(DataFolderMoveProgress value) => report(value); diff --git a/tests/Febe.Tests/Desktop/Support/DesktopTestBed.cs b/tests/Febe.Tests/Desktop/Support/DesktopTestBed.cs index 36ae8d9..de26c41 100644 --- a/tests/Febe.Tests/Desktop/Support/DesktopTestBed.cs +++ b/tests/Febe.Tests/Desktop/Support/DesktopTestBed.cs @@ -47,7 +47,12 @@ internal sealed class DesktopTestBed : IAsyncDisposable public string Origin => $"{App.Address.Scheme}://{App.Address.Authority}"; - public static async Task StartAsync(string[]? args = null, FakeDesktopShell? shell = null, TempFolder? temp = null, MemoryLocationStore? locations = null) + /// The command line of Febe.exe. + /// The fake Windows-only part. + /// The folder of «AppData» and «Immagini»; null: a new one, deleted with the bed. + /// The registry values of the Data folder. + /// Options the command line cannot give (the debugging port of Edge). + public static async Task StartAsync(string[]? args = null, FakeDesktopShell? shell = null, TempFolder? temp = null, MemoryLocationStore? locations = null, Func? adjust = null) { var ownsTemp = temp is null; temp ??= new TempFolder("desktop"); @@ -58,6 +63,8 @@ internal sealed class DesktopTestBed : IAsyncDisposable throw new ArgumentException(problem); } + options = adjust?.Invoke(options) ?? options; + var folders = new DesktopFolders(temp.Combine("AppData", "Local"), temp.Combine("Immagini")); var platform = new DesktopPlatform(options, shell, locations, dataFolderFixed: options.DataFolder is not null); var app = await FebeApp.StartAsync(options.AppOptions(options.DataFolder ?? folders.DefaultDataFolder, folders), platform, new FebeAppHooks { ShutdownTimeout = TimeSpan.FromSeconds(1) }); diff --git a/tests/Febe.Tests/Desktop/Support/FakeDesktopShell.cs b/tests/Febe.Tests/Desktop/Support/FakeDesktopShell.cs index e155f56..5d97ce9 100644 --- a/tests/Febe.Tests/Desktop/Support/FakeDesktopShell.cs +++ b/tests/Febe.Tests/Desktop/Support/FakeDesktopShell.cs @@ -50,6 +50,18 @@ internal sealed class FakeDesktopShell : IDesktopShell ProcessWindows.Enqueue("nascondi " + processId); return Task.CompletedTask; } + + /// The processes the platform asked to tie to Febe's life (Edge), by id. + public ConcurrentQueue TiedToFebe { get; } = new(); + + /// What «Windows» answers when a process is tied to Febe. + public bool TieSucceeds { get; set; } = true; + + public bool EndWithFebe(System.Diagnostics.Process process) + { + TiedToFebe.Enqueue(process.Id); + return TieSucceeds; + } } /// Folder picker, explorer, default browser, notifications (the Windows alerts) and autostart, faked. diff --git a/tests/Febe.Tests/Packaging/PackagingTests.cs b/tests/Febe.Tests/Packaging/PackagingTests.cs new file mode 100644 index 0000000..91e923d --- /dev/null +++ b/tests/Febe.Tests/Packaging/PackagingTests.cs @@ -0,0 +1,298 @@ +using System.Diagnostics; +using System.Text.RegularExpressions; +using System.Xml.Linq; +using Febe.Tests.Desktop.Support; +using Febe.Tests.Support; + +namespace Febe.Tests.Packaging; + +/// +/// What ships Febe (spec §11, §12): the start of the container as root never follows what the unprivileged user can +/// plant in /dati (pkg-2); the seccomp profile Docker reads on the server stays outside the Data volume (pkg-2); +/// the release waits for the tests and for the image, and says when the image was not published (pkg-3); Docker Compose +/// is released with the profile it points to (pkg-4); the image lives on the registry of the Gitea at home, in HTTP. +/// +[TestClass] +public sealed partial class PackagingTests +{ + private const string Registry = "192.168.30.23:3000"; + private const int Nobody = 65534; + + public TestContext TestContext { get; set; } = null!; + + [TestMethod] + [Timeout(60_000, CooperativeCancellation = true)] + public async Task TheStartOfTheContainerNeverFollowsLinksPlantedInTheDataFolder() + { + var reason = EntrypointUnavailableReason(); + if (reason is not null) + { + Assert.Inconclusive(reason); + } + + using var temp = new TempFolder("avvio-contenitore"); + + // What a compromised browser (running as PUID) could leave in /dati before a restart: /dati/home pointing to + // a folder of the container, /dati/seccomp.json pointing to one of its files. + var victimFolder = temp.Combine("vittima"); + Directory.CreateDirectory(victimFolder); + var victimFile = temp.Combine("vittima.txt"); + await File.WriteAllTextAsync(victimFile, "originale", TestContext.CancellationToken); + var data = temp.Combine("dati"); + Directory.CreateDirectory(data); + await RunAsync("chown", $"{Nobody}:{Nobody}", data); + File.CreateSymbolicLink(Path.Combine(data, "home"), victimFolder); + File.CreateSymbolicLink(Path.Combine(data, "seccomp.json"), victimFile); + var before = (Folder: await StatAsync(victimFolder), File: await StatAsync(victimFile)); + + var (code, _, errors) = await RunEntrypointAsync(temp, "true"); + Assert.AreEqual(0, code, errors); + Assert.AreEqual(before.Folder, await StatAsync(victimFolder), "a folder of the container never changes owner or mode"); + Assert.AreEqual(before.File, await StatAsync(victimFile)); + Assert.AreEqual("originale", await File.ReadAllTextAsync(victimFile, TestContext.CancellationToken), "nor is a file written through a link"); + StringAssert.Contains(errors, "/dati/seccomp.json non si aggiorna più", "the old profile in /dati is pointed out"); + } + + [TestMethod] + [Timeout(60_000, CooperativeCancellation = true)] + public async Task TheStartOfTheContainerPreparesTheDataFolderAsTheUserAndKeepsTheProfileOut() + { + var reason = EntrypointUnavailableReason(); + if (reason is not null) + { + Assert.Inconclusive(reason); + } + + // A first start: /dati and /libreria just created by Docker (root), a folder of photos inside the library. + using var temp = new TempFolder("avvio-contenitore"); + Directory.CreateDirectory(temp.Combine("libreria", "foto")); + var whoAmI = temp.Combine("dati", "home", "chi"); + var (code, _, errors) = await RunEntrypointAsync(temp, "/bin/sh", "-c", $"id -u > '{whoAmI}'"); + Assert.AreEqual(0, code, errors); + Assert.AreEqual($"{Nobody}:{Nobody} 750", await StatAsync(temp.Combine("dati"))); + Assert.AreEqual($"{Nobody}:{Nobody} 700", await StatAsync(temp.Combine("dati", "home")), "HOME of Chromium, made by the user"); + Assert.AreEqual(Nobody.ToString(System.Globalization.CultureInfo.InvariantCulture), (await File.ReadAllTextAsync(whoAmI, TestContext.CancellationToken)).Trim(), "Febe runs as PUID"); + Assert.IsFalse(File.Exists(temp.Combine("dati", "seccomp.json")), "the profile Docker reads stays out of /dati"); + Assert.AreEqual($"{Nobody}:{Nobody}", (await StatAsync(temp.Combine("libreria"))).Split(' ')[0]); + Assert.AreEqual("0:0", (await StatAsync(temp.Combine("libreria", "foto"))).Split(' ')[0], "the library is never changed recursively"); + + // A /dati/home left by a start as root (a real folder): given back to the user. + await RunAsync("chown", "0:0", temp.Combine("dati", "home")); + (code, _, errors) = await RunEntrypointAsync(temp, "true"); + Assert.AreEqual(0, code, errors); + Assert.AreEqual($"{Nobody}:{Nobody} 700", await StatAsync(temp.Combine("dati", "home"))); + } + + [TestMethod] + public void TheUnraidTemplateUsesTheRegistryAtHomeAndKeepsTheSeccompProfileOutOfTheDataFolder() + { + var template = XDocument.Load(Repository.PathOf("docker", "unraid", "febe.xml")).Root!; + string Field(string name) => template.Element(name)?.Value.Trim() ?? string.Empty; + Assert.AreEqual($"{Registry}/alby96/febe:latest", Field("Repository")); + foreach (var name in new[] { "Registry", "Support", "Project", "TemplateURL", "Icon" }) + { + StringAssert.StartsWith(Field(name), $"http://{Registry}/Alby96/", name); + } + + StringAssert.EndsWith(Field("TemplateURL"), "/raw/branch/main/docker/unraid/febe.xml"); + StringAssert.EndsWith(Field("Icon"), "/raw/branch/main/docker/unraid/febe.png"); + StringAssert.Contains(Field("Requires"), "insecure-registries"); + + // pkg-2: Docker reads the profile on the server when it creates the container; inside the Data volume the user + // of the container could loosen it. + var data = template.Elements("Config").Single(c => (string?)c.Attribute("Target") == "/dati").Value.Trim(); + var profile = SeccompProfile().Match(Field("ExtraParams")); + Assert.IsTrue(profile.Success, Field("ExtraParams")); + var path = profile.Groups["path"].Value; + Assert.IsFalse(path.StartsWith(data.TrimEnd('/') + "/", StringComparison.Ordinal), $"{path} is inside {data}"); + StringAssert.Contains(Field("Requires"), path, "the template says how to put the profile there"); + StringAssert.Contains(Field("Requires"), "/usr/share/febe/seccomp.json"); + } + + [TestMethod] + public void TheComposeFilePointsToTheRegistryAtHomeAndToAProfileOutsideTheDataVolume() + { + var compose = File.ReadAllText(Repository.PathOf("docker", "compose.yml")); + StringAssert.Contains(compose, $"image: {Registry}/alby96/febe:latest"); + StringAssert.Contains(compose, "- seccomp=./chromium/seccomp.json"); + Assert.IsTrue(File.Exists(Repository.PathOf("docker", "chromium", "seccomp.json")), "the profile is next to compose.yml"); + StringAssert.Contains(compose, ":/dati"); + Assert.DoesNotContain("seccomp.json:/dati", compose); + } + + [TestMethod] + public void TheReleaseWaitsForTheTestsAndTheImageAndShipsComposeWithItsProfile() + { + var workflow = Workflow("rilascio.yml"); + var prove = Job(workflow, "prove"); + StringAssert.Contains(prove, "dotnet build Febe.slnx -c Release -nologo -warnaserror"); + StringAssert.Contains(prove, "dotnet test tests/Febe.Tests -c Release --no-build"); + StringAssert.Contains(Job(workflow, "windows"), "needs: prove"); + var image = Job(workflow, "immagine"); + StringAssert.Contains(image, "needs: prove"); + + // pkg-3: the release needs the tests, the installer and the image job, which says whether it published. + var release = Job(workflow, "release"); + StringAssert.Contains(release, "needs: [prove, windows, immagine]"); + Assert.DoesNotContain("if:", release, "no «always()»: a failed build or push stops the release"); + StringAssert.Contains(image, "pubblicata: ${{ steps.pubblicazione.outputs.pubblicata }}"); + StringAssert.Contains(release, "PUBBLICATA: ${{ needs.immagine.outputs.pubblicata }}"); + StringAssert.Contains(release, "non è stata pubblicata"); + + // Without the secret the image is built and tested, and the job still succeeds: the release says so. + var secret = Step(image, "Segreto per il registro"); + Assert.DoesNotContain("exit 1", secret); + StringAssert.Contains(secret, "presente=no"); + StringAssert.Contains(Step(image, "Pubblicazione sul registro di Gitea"), "if: steps.segreto.outputs.presente == 'si'"); + + // The registry at home answers in HTTP: buildx with its own builder, told so, and no «docker login». + StringAssert.Contains(image, "uses: docker/setup-buildx-action@v3"); + StringAssert.Contains(image, "http = true"); + StringAssert.Contains(image, "insecure = true"); + StringAssert.Contains(image, "--push"); + Assert.DoesNotContain("docker login", image); + Assert.DoesNotContain("docker push", image); + + // pkg-4: compose.yml goes out with chromium/seccomp.json next to it, never alone. + StringAssert.Contains(release, "cp docker/compose.yml \"$COMPOSE/compose.yml\""); + StringAssert.Contains(release, "cp docker/chromium/seccomp.json \"$COMPOSE/chromium/seccomp.json\""); + StringAssert.Contains(release, "\"$COMPOSE.tar.gz\""); + Assert.DoesNotContain("febe-compose-$VERSION.yml", release); + } + + /// Why the entrypoint cannot be run here (it needs Linux, root, setpriv and the user «nobody»); null when it can. + private static string? EntrypointUnavailableReason() + { + if (!OperatingSystem.IsLinux()) + { + return "L'avvio del contenitore si prova solo su Linux."; + } + + if (Environment.UserName != "root") + { + return "L'avvio del contenitore gira come root: la prova si salta senza root."; + } + + foreach (var tool in new[] { "sh", "setpriv", "stat", "chown", "getent" }) + { + if (FindOnPath(tool) is null) + { + return $"Manca {tool}: la prova dell'avvio del contenitore si salta."; + } + } + + // The entrypoint creates the user and the group when they are missing: never on the machine of the tests. + return Run("getent", "passwd", Nobody.ToString(System.Globalization.CultureInfo.InvariantCulture)) && Run("getent", "group", Nobody.ToString(System.Globalization.CultureInfo.InvariantCulture)) + ? null + : $"L'utente o il gruppo {Nobody} non esistono qui: la prova si salta per non crearli."; + } + + /// The real entrypoint, with /dati, /libreria and the profile of the image moved into . + private async Task<(int Code, string Output, string Errors)> RunEntrypointAsync(TempFolder temp, params string[] command) + { + var text = await File.ReadAllTextAsync(Repository.PathOf("docker", "entrypoint.sh"), TestContext.CancellationToken); + var image = temp.Combine("immagine-seccomp.json"); + await File.WriteAllTextAsync(image, "{}", TestContext.CancellationToken); + var relocated = text + .Replace("/usr/share/febe/seccomp.json", image, StringComparison.Ordinal) + .Replace("/dati", temp.Combine("dati"), StringComparison.Ordinal) + .Replace("/libreria", temp.Combine("libreria"), StringComparison.Ordinal) + .Replace("groupadd ", ": groupadd ", StringComparison.Ordinal) + .Replace("useradd ", ": useradd ", StringComparison.Ordinal); + var script = temp.Combine("avvio.sh"); + await File.WriteAllTextAsync(script, relocated, TestContext.CancellationToken); + var start = new ProcessStartInfo("sh") { RedirectStandardOutput = true, RedirectStandardError = true }; + start.ArgumentList.Add(script); + foreach (var part in command) + { + start.ArgumentList.Add(part); + } + + start.Environment["PUID"] = Nobody.ToString(System.Globalization.CultureInfo.InvariantCulture); + start.Environment["PGID"] = Nobody.ToString(System.Globalization.CultureInfo.InvariantCulture); + using var process = Process.Start(start)!; + var output = process.StandardOutput.ReadToEndAsync(TestContext.CancellationToken); + var errors = process.StandardError.ReadToEndAsync(TestContext.CancellationToken); + await process.WaitForExitAsync(TestContext.CancellationToken); + return (process.ExitCode, await output, await errors); + } + + /// Owner, group and mode of a path, without following a final link («0:0 755»). + private async Task StatAsync(string path) + { + var start = new ProcessStartInfo("stat") { RedirectStandardOutput = true }; + foreach (var part in new[] { "-c", "%u:%g %a", path }) + { + start.ArgumentList.Add(part); + } + + using var process = Process.Start(start)!; + var text = await process.StandardOutput.ReadToEndAsync(TestContext.CancellationToken); + await process.WaitForExitAsync(TestContext.CancellationToken); + Assert.AreEqual(0, process.ExitCode, path); + return text.Trim(); + } + + private async Task RunAsync(string program, params string[] arguments) + { + using var process = Process.Start(new ProcessStartInfo(program, arguments))!; + await process.WaitForExitAsync(TestContext.CancellationToken); + Assert.AreEqual(0, process.ExitCode, $"{program} {string.Join(' ', arguments)}"); + } + + private static bool Run(string program, params string[] arguments) + { + using var process = Process.Start(new ProcessStartInfo(program, arguments) { RedirectStandardOutput = true, RedirectStandardError = true })!; + process.StandardOutput.ReadToEnd(); + process.StandardError.ReadToEnd(); + process.WaitForExit(); + return process.ExitCode == 0; + } + + /// A workflow of .gitea/workflows; inconclusive in the build of the image, whose context leaves .gitea out. + private static string Workflow(string name) + { + var path = Repository.PathOf(".gitea", "workflows", name); + var root = Repository.Root()!; + if (!File.Exists(path) && !Directory.Exists(Path.Combine(root, ".git")) && !File.Exists(Path.Combine(root, ".git"))) + { + Assert.Inconclusive("Questa copia del repository non ha .gitea/ (costruzione dell'immagine Docker)."); + } + + return File.ReadAllText(path).Replace("\r\n", "\n", StringComparison.Ordinal); + } + + /// The block of a job: from « name:» to the next job. + private static string Job(string workflow, string name) + { + var match = Regex.Match(workflow, $@"^ {Regex.Escape(name)}:\n(?(?:(?: .*|\s*)\n)*)", RegexOptions.Multiline); + Assert.IsTrue(match.Success, $"manca il lavoro {name}"); + return match.Groups["body"].Value; + } + + /// The block of a step, from its «- name:» to the next step. + private static string Step(string job, string name) + { + var start = job.IndexOf("- name: " + name, StringComparison.Ordinal); + Assert.IsGreaterThanOrEqualTo(0, start, $"manca il passo «{name}»"); + var next = job.IndexOf("\n - ", start + 1, StringComparison.Ordinal); + return next < 0 ? job[start..] : job[start..next]; + } + + private static string? FindOnPath(string name) + { + foreach (var folder in (Environment.GetEnvironmentVariable("PATH") ?? string.Empty).Split(Path.PathSeparator, StringSplitOptions.RemoveEmptyEntries)) + { + var path = Path.Combine(folder, name); + if (File.Exists(path)) + { + return path; + } + } + + return null; + } + + [GeneratedRegex(@"--security-opt seccomp=(?\S+)")] + private static partial Regex SeccompProfile(); +} diff --git a/tests/Febe.Tests/Web/LoginSecurityTests.cs b/tests/Febe.Tests/Web/LoginSecurityTests.cs new file mode 100644 index 0000000..85fef46 --- /dev/null +++ b/tests/Febe.Tests/Web/LoginSecurityTests.cs @@ -0,0 +1,219 @@ +using System.Diagnostics; +using System.Net; +using System.Text.Json; +using Febe.Tests.Desktop.Support; +using Febe.Tests.Support; +using Febe.Tests.Web.Support; +using Febe.Web; +using Febe.Web.Security; + +namespace Febe.Tests.Web; + +/// +/// The login page of the Docker interface (spec §13.1): after the password it goes back only to a page of the interface +/// («torna»), never to another site (websec-2, web-8); the session cookie is Secure whenever the browser talked +/// HTTPS, also through the trusted proxy of FEBE_PROXY_FIDATO (websec-3). +/// +[TestClass] +public sealed class LoginSecurityTests +{ + private const string Password = "una password lunga"; + + /// Values of «torna» a crafted link could carry, each of which a browser resolves to another site. + private static readonly string[] Foreign = + [ + "//evil.example", + "/\\evil.example", + "/\\/evil.example", + "/\t/evil.example", + "/\n/evil.example", + "/\r/evil.example", + "\\\\evil.example", + "/./\\evil.example", + "http://evil.example/", + "https:evil.example", + "javascript:alert(1)", + " /libreria", + "/libreria\u0000", + "libreria", + "", + ]; + + /// Paths of the interface, which must still work. + private static readonly string[] Own = ["/libreria", "/account/12", "/impostazioni/collegamento", "/libreria?tipo=foto#x", "/%5Cnon-un-sito", "/.//dentro"]; + + public TestContext TestContext { get; set; } = null!; + + [TestMethod] + public void TheServerAcceptsOnlyPathsOfTheInterface() + { + foreach (var value in Foreign) + { + Assert.IsFalse(LoginReturn.IsSafe(value), JsonSerializer.Serialize(value)); + Assert.AreEqual("/accesso", LoginReturn.LoginAddress(value)); + } + + Assert.IsFalse(LoginReturn.IsSafe(null)); + Assert.IsFalse(LoginReturn.IsSafe("/" + new string('a', LoginReturn.MaxLength))); + foreach (var value in Own) + { + Assert.IsTrue(LoginReturn.IsSafe(value), value); + } + + Assert.AreEqual("/accesso?torna=%2Faccount%2F12", LoginReturn.LoginAddress("/account/12")); + } + + [TestMethod] + public async Task ACraftedLinkToTheLoginPageLosesItsReturnBeforeThePageShows() + { + await using var server = await StartAsync(trustProxy: false); + foreach (var page in new[] { "/accesso", "/accesso.html" }) + { + foreach (var value in new[] { "/\\evil.example", "//evil.example", "/\t/evil.example", "http://evil.example/" }) + { + using var response = await server.Client.GetAsync($"{page}?torna={Uri.EscapeDataString(value)}", TestContext.CancellationToken); + Assert.AreEqual(HttpStatusCode.Redirect, response.StatusCode, $"{page} {JsonSerializer.Serialize(value)}"); + Assert.AreEqual("/accesso", response.Headers.Location?.OriginalString); + } + } + + using (var own = await server.Client.GetAsync("/accesso?torna=%2Faccount%2F12", TestContext.CancellationToken)) + { + Assert.AreEqual(HttpStatusCode.OK, own.StatusCode, "a page of the interface stays"); + } + + // A page asked through an address that a browser would read as another site: the login page, without «torna». + using (var crafted = await server.Client.GetAsync("/%5Cevil.example", TestContext.CancellationToken)) + { + Assert.AreEqual(HttpStatusCode.Redirect, crafted.StatusCode); + Assert.AreEqual("/accesso", crafted.Headers.Location?.OriginalString); + } + + using (var normal = await server.Client.GetAsync("/account/12", TestContext.CancellationToken)) + { + Assert.AreEqual("/accesso?torna=%2Faccount%2F12", normal.Headers.Location?.OriginalString); + } + } + + [TestMethod] + public void TheLoginPageGoesBackOnlyToAPageOfTheInterface() + { + var accesso = File.ReadAllText(Repository.PathOf("src", "Febe.Web", "wwwroot", "js", "accesso.js")); + StringAssert.Contains(accesso, "import { returnAddress } from './core/return-path.js';"); + StringAssert.Contains(accesso, "location.href = returnAddress("); + Assert.DoesNotContain("startsWith('//')", accesso, "the old check let «/\\host» through"); + + var node = FindOnPath("node"); + if (node is null) + { + Assert.Inconclusive("Node non è installato: la regola della pagina di accesso si prova solo dove c'è (CI, sviluppo)."); + } + + const string origin = "http://tower:8480"; + List<(string? Value, string Expected)> cases = + [ + .. Foreign.Select(v => ((string?)v, origin + "/libreria")), + (null, origin + "/libreria"), + ("/account/12", origin + "/account/12"), + ("/libreria?tipo=foto#x", origin + "/libreria?tipo=foto#x"), + ("/%5Cnon-un-sito", origin + "/%5Cnon-un-sito"), + // The path is normalised to «//dentro», but the page goes to the absolute address: still this site. + ("/.//dentro", origin + "//dentro"), + ]; + + using var temp = new TempFolder("accesso-js"); + var script = temp.Combine("prova.mjs"); + var module = new Uri(Repository.PathOf("src", "Febe.Web", "wwwroot", "js", "core", "return-path.js")).AbsoluteUri; + File.WriteAllText(script, $$""" + import { returnAddress } from '{{module}}'; + const cases = JSON.parse(process.argv[2]); + console.log(JSON.stringify(cases.map(v => returnAddress(v, '{{origin}}')))); + """); + var start = new ProcessStartInfo(node) { RedirectStandardOutput = true, RedirectStandardError = true }; + start.ArgumentList.Add(script); + start.ArgumentList.Add(JsonSerializer.Serialize(cases.Select(c => c.Value))); + using var process = Process.Start(start)!; + var output = process.StandardOutput.ReadToEnd(); + var errors = process.StandardError.ReadToEnd(); + process.WaitForExit(); + Assert.AreEqual(0, process.ExitCode, errors); + var results = JsonSerializer.Deserialize(output)!; + for (var i = 0; i < cases.Count; i++) + { + Assert.AreEqual(cases[i].Expected, results[i], JsonSerializer.Serialize(cases[i].Value)); + Assert.AreEqual("tower:8480", new Uri(results[i]).Authority, "never another site"); + } + } + + [TestMethod] + public async Task TheSessionCookieIsSecureBehindTheTrustedProxyWithHttps() + { + // Plain HTTP on the network of home: no Secure, or the browser would drop the cookie. + await using (var plain = await StartAsync(trustProxy: false)) + { + Assert.IsFalse(IsSecure(await LoginAsync(plain, origin: null, forwardedHost: null, forwardedProto: null))); + + // Without FEBE_PROXY_FIDATO the header is anybody's: it changes nothing. + Assert.IsFalse(IsSecure(await LoginAsync(plain, origin: null, forwardedHost: null, forwardedProto: "https"))); + } + + await using var proxied = await StartAsync(trustProxy: true); + Assert.IsTrue(IsSecure(await LoginAsync(proxied, origin: "https://febe.example.org", forwardedHost: "febe.example.org", forwardedProto: "https"))); + Assert.IsTrue(IsSecure(await LoginAsync(proxied, origin: null, forwardedHost: null, forwardedProto: "https, http")), "the value the proxy next to the browser wrote"); + Assert.IsFalse(IsSecure(await LoginAsync(proxied, origin: null, forwardedHost: null, forwardedProto: "http")), "the proxy says the browser used HTTP"); + var session = await LoginAsync(proxied, origin: null, forwardedHost: null, forwardedProto: null); + Assert.IsFalse(IsSecure(session), "LAN access next to the proxy"); + + using var logout = proxied.Request(HttpMethod.Post, "/api/uscita"); + logout.Headers.TryAddWithoutValidation("Cookie", session.Split(';')[0]); + logout.Headers.TryAddWithoutValidation("X-Forwarded-Proto", "https"); + using var response = await proxied.Client.SendAsync(logout, TestContext.CancellationToken); + Assert.IsTrue(IsSecure(response.Headers.GetValues("Set-Cookie").Single()), "the logout clears the same cookie"); + } + + private static Task StartAsync(bool trustProxy) => WebTestServer.StartAsync(new FebeWebOptions + { + Access = AccessMode.Password, + Password = Password, + TrustForwardedHost = trustProxy, + Lockout = new LockoutOptions { AttemptsPerClient = 50, AttemptsOverall = 50 }, + }); + + private async Task LoginAsync(WebTestServer server, string? origin, string? forwardedHost, string? forwardedProto) + { + using var request = server.Request(HttpMethod.Post, "/api/accesso", new { password = Password }, origin ?? string.Empty); + if (forwardedHost is not null) + { + request.Headers.TryAddWithoutValidation("X-Forwarded-Host", forwardedHost); + } + + if (forwardedProto is not null) + { + request.Headers.TryAddWithoutValidation("X-Forwarded-Proto", forwardedProto); + } + + using var response = await server.Client.SendAsync(request, TestContext.CancellationToken); + Assert.AreEqual(HttpStatusCode.OK, response.StatusCode, await response.Content.ReadAsStringAsync(TestContext.CancellationToken)); + return response.Headers.GetValues("Set-Cookie").Single(); + } + + private static bool IsSecure(string setCookie) => + setCookie.Split(';').Any(part => string.Equals(part.Trim(), "secure", StringComparison.OrdinalIgnoreCase)); + + private static string? FindOnPath(string name) + { + foreach (var folder in (Environment.GetEnvironmentVariable("PATH") ?? string.Empty).Split(Path.PathSeparator, StringSplitOptions.RemoveEmptyEntries)) + { + foreach (var candidate in new[] { name, name + ".exe" }) + { + var path = Path.Combine(folder, candidate); + if (File.Exists(path)) + { + return path; + } + } + } + + return null; + } +}