Redirige les visiteurs anonymes vers la connexion (fixe la favicon nativefier)

Un visiteur anonyme sur une page du module (ex. /lignes) reçoit maintenant
un 302 vers /user/login au lieu d'un 403 brut -- même périmètre que le
hide_admin_chrome existant (_figli_compta_ledger_front_end_routes(),
extraite en fonction partagée), pas les endpoints JSON API du module.

Corrige au passage `nativefier --upgrade` (empaquetage du site en app
desktop), qui n'arrivait pas à récupérer la favicon : sa détection
d'icône (page-icon) fait un GET anonyme brut de l'URL cible et
n'inspecte le <head> que si la réponse est 2xx -- un 403 anonyme sur /
(suite au durcissement des permissions, AUDIT-2026-09-09.md) la faisait
échouer silencieusement, alors que le bon <link rel="icon"> était bien
présent dans le HTML de cette page 403. Vérifié en direct : GET / -> 403
(lien favicon présent mais inaccessible à axios) ; GET /user/login -> 200
avec le même lien, même thème.

Testé : anonyme sur page du module -> 302 puis 200 avec favicon ; anonyme
sur API JSON -> reste 403 sans redirection (ne casse pas la gestion
d'expiration de session de home.js/dashboard.js) ; connecté sans la
permission -> reste 403 normal (pas de redirection vers login pour
quelqu'un déjà connecté) ; connecté avec permission -> 200 inchangé.
This commit is contained in:
2026-09-19 18:49:48 +02:00
parent 7382e4feec
commit aa0bbae98d
3 changed files with 114 additions and 11 deletions
@@ -535,6 +535,28 @@ function figli_compta_ledger_theme($existing, $type, $theme, $path) {
];
}
/**
* This module's own front-end (non-admin, non-API) page routes -- shared
* between figli_compta_ledger_page_attachments() below (which routes get
* the admin chrome hidden) and AnonymousAccessDeniedSubscriber (which
* routes redirect an anonymous visitor to the login form instead of a
* bare 403). Deliberately excludes this module's JSON API endpoints
* (/lignes/api/*, /dashboard/api/*, the inline-edit POST routes) -- those
* are fetch()ed by home.js/dashboard.js, not navigated to.
*/
function _figli_compta_ledger_front_end_routes(): array {
return [
'figli_compta_ledger.home',
'figli_compta_ledger.dashboard',
'figli_compta_ledger.dashboard_repartition',
'figli_compta_ledger.dashboard_compte',
'figli_compta_ledger.history',
'figli_compta_ledger.link_entree',
'figli_compta_ledger.releve_import_form',
'figli_compta_ledger.releve_import_result',
];
}
/**
* Implements hook_page_attachments().
*
@@ -547,17 +569,7 @@ function figli_compta_ledger_theme($existing, $type, $theme, $path) {
function figli_compta_ledger_page_attachments(array &$attachments) {
$attachments['#attached']['library'][] = 'figli_compta_ledger/admin_chrome';
$front_end_routes = [
'figli_compta_ledger.home',
'figli_compta_ledger.dashboard',
'figli_compta_ledger.dashboard_repartition',
'figli_compta_ledger.dashboard_compte',
'figli_compta_ledger.history',
'figli_compta_ledger.link_entree',
'figli_compta_ledger.releve_import_form',
'figli_compta_ledger.releve_import_result',
];
if (in_array(\Drupal::routeMatch()->getRouteName(), $front_end_routes, TRUE)) {
if (in_array(\Drupal::routeMatch()->getRouteName(), _figli_compta_ledger_front_end_routes(), TRUE)) {
$attachments['#attached']['library'][] = 'figli_compta_ledger/hide_admin_chrome';
}
}
@@ -4,6 +4,16 @@ services:
tags:
- { name: event_subscriber }
# Redirects an anonymous visitor denied access to one of this module's
# own front-end pages to the login form instead of a bare 403 (see the
# class docblock -- this is also what fixes `nativefier --upgrade`'s
# favicon auto-detection).
figli_compta_ledger.anonymous_access_denied_subscriber:
class: Drupal\figli_compta_ledger\EventSubscriber\AnonymousAccessDeniedSubscriber
arguments: ['@current_user', '@redirect.destination']
tags:
- { name: event_subscriber }
# Request-scoped répartition-check opt-out (see the class docblock: unlike
# the historical state key, a skip held here is invisible to concurrent
# requests -- audited in AUDIT-2026-09-09.md §2.2).
@@ -0,0 +1,81 @@
<?php
namespace Drupal\figli_compta_ledger\EventSubscriber;
use Drupal\Core\Routing\RedirectDestinationInterface;
use Drupal\Core\Session\AccountProxyInterface;
use Drupal\Core\Url;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpKernel\Event\ExceptionEvent;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
use Symfony\Component\HttpKernel\KernelEvents;
/**
* An anonymous visitor hitting one of this module's own front-end pages
* (see _figli_compta_ledger_front_end_routes()) gets redirected to the
* login form instead of a bare 403 -- friendlier ("please log in" rather
* than "access denied"), and it also fixes `nativefier --upgrade`'s
* automatic favicon detection for the packaged desktop app:
*
* nativefier's icon inference (the `page-icon` npm dependency) does a
* plain *unauthenticated* GET of the app's target URL and only parses
* <head> for a <link rel="icon"> if the response status is 2xx (axios'
* default validateStatus rejects anything else outright, before the body
* is even read). Since the site's front page requires 'access figli
* ledger' (see AUDIT-2026-09-09.md §2.2's permission hardening) and
* anonymous no longer holds it, an anonymous GET of the site's own root
* URL returns 403 -- even though the *same* <link rel="icon"> tag is
* right there in that 403 page's markup (it's theme-level, rendered on
* every page including error pages), nativefier's fetch rejects before
* ever seeing it. Confirmed empirically against the live site: GET / →
* 403 (favicon link present in the body but unreachable to axios); GET
* /user/login → 200 with the identical favicon link, same active theme.
* Redirecting here (axios follows redirects by default) is what lets
* nativefier actually receive that 200 response and read the tag.
*
* Zero extra access granted by this: the destination is always the login
* form, never the page the visitor was actually trying to reach -- an
* anonymous visitor still can't see one byte of ledger data, they just
* land on a login prompt instead of a dead end. Scoped to this module's
* own front-end page routes only (see _figli_compta_ledger_front_end_
* routes()'s own docblock for why its JSON API endpoints are excluded).
*/
class AnonymousAccessDeniedSubscriber implements EventSubscriberInterface {
public function __construct(
private readonly AccountProxyInterface $currentUser,
private readonly RedirectDestinationInterface $redirectDestination,
) {}
/**
* {@inheritdoc}
*/
public static function getSubscribedEvents(): array {
return [KernelEvents::EXCEPTION => 'onException'];
}
/**
* Redirects to the login form in place of the default 403 response,
* only for an anonymous visitor denied access to one of this module's
* own front-end routes.
*/
public function onException(ExceptionEvent $event): void {
if (!$this->currentUser->isAnonymous()) {
return;
}
if (!$event->getThrowable() instanceof AccessDeniedHttpException) {
return;
}
$routeName = $event->getRequest()->attributes->get('_route');
if (!in_array($routeName, _figli_compta_ledger_front_end_routes(), TRUE)) {
return;
}
$url = Url::fromRoute('user.login', [], [
'query' => ['destination' => $this->redirectDestination->get()],
])->toString();
$event->setResponse(new RedirectResponse($url));
}
}