Template
Masquer toutes les erreurs : 404 doux, API blindée, aucune fuite PHP
- /api/bugs/ et tout chemin inconnu sous /api/ : 404 JSON propre - 403/404 Apache : ErrorDocument vers page.php, sans page Apache brute - fichiers internes (inc/, corps de pages, db.php, init.php...) : 404 - erreurs PHP : display_errors off, handlers exception/fatal, réponses JSON ou HTML discrètes, journalisation locale gitignorée
This commit is contained in:
1 parent
3b3127bb34
commit
82168e2678
6 files changed
+196
No files matched your search
@@ -23,3 +23,6 @@ p/assets/img/packages/
|
||||
|
||||
# Cache HTTP local du site (releases Gitea/GitHub, généré par inc/site.php)
|
||||
cache/
|
||||
|
||||
# Journal des erreurs PHP (filet de sécurité inc/errors.php)
|
||||
api/bugs/data/php-errors.log
|
||||
@@ -8,6 +8,25 @@ DirectoryIndex index.php page.php
|
||||
# Pas de listing de répertoires (ex : /p/, /api/, /admin/)
|
||||
Options -Indexes
|
||||
|
||||
# ── Erreurs Apache « douces » ────────────────────────────────────────────────
|
||||
# 403 (répertoire protégé, listing désactivé…) et 404 : jamais les pages
|
||||
# Apache brutes. page.php sert la page 404 du site ; le statut HTTP reste
|
||||
# correct (403/404) pour les navigateurs comme pour les clients d'API.
|
||||
ErrorDocument 403 /page.php?__e=403
|
||||
ErrorDocument 404 /page.php?__e=404
|
||||
|
||||
# ── Fichiers internes : traités comme introuvables ─────────────────────────
|
||||
# Tout fichier PHP qui n'est pas un point d'entrée légitime (bibliothèques,
|
||||
# corps de pages, config, logs…) répond 404 — on ne révèle même pas son
|
||||
# existence avec un 403. Les accès directs aux corps restent sinon gérés par
|
||||
# leurs shims de délégation vers page.php.
|
||||
RedirectMatch 404 ^/?(inc|cache)/
|
||||
RedirectMatch 404 ^/?api/bugs/(db|discord|config\.local)\.php$
|
||||
RedirectMatch 404 ^/?admin/bugs/init\.php$
|
||||
# Corps de pages et scripts internes sous p/ (hors assets). Les index.php
|
||||
# sont exclus : ils sont résolus en interne par DirectoryIndex (ex /p/dl/).
|
||||
RedirectMatch 404 ^/?p/(?!assets/)(?!.*index\.php$).*\.php$
|
||||
|
||||
# Types MIME manquants (selon la config Apache du conteneur)
|
||||
<IfModule mod_mime.c>
|
||||
AddType image/webp .webp
|
||||
|
||||
@@ -6,6 +6,10 @@
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
/* Filet de sécurité : aucune erreur PHP ne fuit jamais côté client
|
||||
* (JSON sous /api/, page HTML discrète sinon). */
|
||||
require_once dirname(__DIR__, 2) . '/inc/errors.php';
|
||||
|
||||
/* ───────────── UTF-8 (partagé avec inc/site.php, gardes function_exists) ── */
|
||||
|
||||
if (!function_exists('fws_utf8_str')) {
|
||||
|
||||
+149
@@ -0,0 +1,149 @@
|
||||
<?php
|
||||
/**
|
||||
* FWS — filet de sécurité des erreurs PHP.
|
||||
*
|
||||
* Inclu par inc/site.php (pages du site) et api/bugs/db.php (API + admin),
|
||||
* donc actif partout. Garanties :
|
||||
*
|
||||
* 1. Aucune erreur PHP n'est jamais affichée au client (display_errors off) ;
|
||||
* 2. Les erreurs sont journalisées dans api/bugs/data/php-errors.log
|
||||
* (répertoire interdit au web et gitignoré) ;
|
||||
* 3. Exception non interceptée ou erreur fatale → réponse propre :
|
||||
* JSON sous /api/, page HTML discrète sinon (jamais de stack trace,
|
||||
* jamais de chemin de fichier, jamais de message système).
|
||||
*
|
||||
* Idempotent : peut être inclus plusieurs fois sans risque.
|
||||
*/
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
/* ── 1/2. Journalisation locale, jamais d'affichage ────────────────────── */
|
||||
|
||||
ini_set('display_errors', '0');
|
||||
ini_set('display_startup_errors', '0');
|
||||
ini_set('log_errors', '1');
|
||||
error_reporting(E_ALL);
|
||||
|
||||
/* En CLI (scripts d'administration dans le conteneur), on affiche tout :
|
||||
* c'est interactif, l'opérateur doit voir les problèmes. */
|
||||
if (PHP_SAPI === 'cli') {
|
||||
ini_set('display_errors', '1');
|
||||
}
|
||||
|
||||
/* Journal : api/bugs/data/ (déjà interdit au web par .htaccess + gitigné). */
|
||||
$fwsErrorLogDir = dirname(__DIR__) . '/api/bugs/data';
|
||||
if (!is_dir($fwsErrorLogDir)) {
|
||||
@mkdir($fwsErrorLogDir, 0770, true);
|
||||
}
|
||||
if (is_dir($fwsErrorLogDir) && is_writable($fwsErrorLogDir)) {
|
||||
ini_set('error_log', $fwsErrorLogDir . '/php-errors.log');
|
||||
}
|
||||
unset($fwsErrorLogDir);
|
||||
|
||||
/* ── 3. Réponses d'erreur propres ──────────────────────────────────────── */
|
||||
|
||||
if (!function_exists('fws_error_wants_json')) {
|
||||
|
||||
/** Le client attend-il du JSON ? (sous /api/ ou requête JSON explicite) */
|
||||
function fws_error_wants_json(): bool
|
||||
{
|
||||
$path = (string) (parse_url((string) ($_SERVER['REQUEST_URI'] ?? '/'), PHP_URL_PATH) ?: '/');
|
||||
if (str_starts_with($path, '/api')) {
|
||||
return true;
|
||||
}
|
||||
$accept = (string) ($_SERVER['HTTP_ACCEPT'] ?? '');
|
||||
$ctype = (string) ($_SERVER['CONTENT_TYPE'] ?? '');
|
||||
return str_contains($accept, 'application/json') || str_contains($ctype, 'application/json');
|
||||
}
|
||||
|
||||
/**
|
||||
* Réponse d'erreur finale : JSON ou page HTML minimaliste, sans aucun
|
||||
* détail technique. Ne fait rien si les en-têtes sont déjà partis.
|
||||
*/
|
||||
function fws_error_render(int $status, string $message): void
|
||||
{
|
||||
if (headers_sent()) {
|
||||
return; /* trop tard pour propre : on referme silencieusement */
|
||||
}
|
||||
|
||||
http_response_code($status);
|
||||
|
||||
if (fws_error_wants_json()) {
|
||||
header('Content-Type: application/json; charset=utf-8');
|
||||
header('X-Content-Type-Options: nosniff');
|
||||
header('Cache-Control: no-store');
|
||||
echo json_encode(['ok' => false, 'error' => $message], JSON_UNESCAPED_UNICODE);
|
||||
return;
|
||||
}
|
||||
|
||||
header('Content-Type: text/html; charset=utf-8');
|
||||
header('Cache-Control: no-store');
|
||||
$msg = htmlspecialchars($message, ENT_QUOTES, 'UTF-8');
|
||||
echo <<<HTML
|
||||
<!doctype html>
|
||||
<html lang="fr">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<meta name="robots" content="noindex, nofollow">
|
||||
<title>Erreur | FWS Linux</title>
|
||||
<style>
|
||||
body{margin:0;min-height:100vh;display:flex;align-items:center;justify-content:center;
|
||||
font-family:system-ui,-apple-system,"Segoe UI",Roboto,sans-serif;
|
||||
background:#0f172a;color:#e2e8f0}
|
||||
main{text-align:center;padding:2rem}
|
||||
h1{font-size:2.2rem;color:#38bdf8;margin:0 0 .5rem}
|
||||
p{color:#94a3b8;margin:0 0 1.5rem}
|
||||
a{color:#38bdf8;text-decoration:none;font-weight:500}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<main>
|
||||
<h1>Oups…</h1>
|
||||
<p>{$msg}</p>
|
||||
<a href="/?p=index/">Retour à l'accueil</a>
|
||||
</main>
|
||||
</body>
|
||||
</html>
|
||||
HTML;
|
||||
}
|
||||
}
|
||||
|
||||
if (!function_exists('fws_error_install')) {
|
||||
|
||||
/** Pose les handlers (une seule fois, jamais en CLI). */
|
||||
function fws_error_install(): void
|
||||
{
|
||||
static $installed = false;
|
||||
if ($installed || PHP_SAPI === 'cli') {
|
||||
return;
|
||||
}
|
||||
$installed = true;
|
||||
|
||||
/* Exception non interceptée → 500 propre. */
|
||||
set_exception_handler(static function (Throwable $e): void {
|
||||
error_log('[fws] exception non interceptée : ' . $e->getMessage()
|
||||
. ' — ' . $e->getFile() . ':' . $e->getLine());
|
||||
fws_error_render(500, 'Une erreur inattendue est survenue. Merci de réessayer plus tard.');
|
||||
});
|
||||
|
||||
/* Erreur fatale (mémoire, parse, include manquant…) → 500 propre.
|
||||
* NB : les warnings/notices restent simplement journalisés — on ne
|
||||
* les transforme pas en exceptions pour ne pas casser les pages. */
|
||||
register_shutdown_function(static function (): void {
|
||||
$e = error_get_last();
|
||||
if ($e === null) {
|
||||
return;
|
||||
}
|
||||
$fatals = [E_ERROR, E_PARSE, E_CORE_ERROR, E_COMPILE_ERROR, E_USER_ERROR];
|
||||
if (!in_array((int) $e['type'], $fatals, true)) {
|
||||
return;
|
||||
}
|
||||
error_log('[fws] erreur fatale : ' . $e['message']
|
||||
. ' — ' . $e['file'] . ':' . $e['line']);
|
||||
fws_error_render(500, 'Une erreur inattendue est survenue. Merci de réessayer plus tard.');
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
fws_error_install();
|
||||
@@ -9,6 +9,9 @@
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
/* Filet de sécurité : aucune erreur PHP ne fuit jamais côté client. */
|
||||
require_once __DIR__ . '/errors.php';
|
||||
|
||||
define('FWS_SITE_ROOT', dirname(__DIR__));
|
||||
define('FWS_SITE_CACHE_DIR', FWS_SITE_ROOT . '/cache');
|
||||
define('FWS_SITE_CACHE_TTL', 600); // 10 minutes
|
||||
|
||||
@@ -62,6 +62,24 @@ if (preg_match('/^paquets\/(\d+)$/', $route, $m)) {
|
||||
|
||||
$is404 = $pageFile === null || !is_file($pageFile);
|
||||
|
||||
/* Erreurs Apache « douces » : les 403/404 déroutés ici via ErrorDocument
|
||||
* (voir .htaccess) rendent la page 404 du site — jamais de page Apache
|
||||
* brute, jamais de détail technique. */
|
||||
if (in_array((int) ($_GET['__e'] ?? 0), [403, 404], true)) {
|
||||
$pageFile = null;
|
||||
$is404 = true;
|
||||
header('Access-Control-Allow-Origin: *');
|
||||
header('Cache-Control: no-store');
|
||||
/* Chemins API : réponse JSON (jamais de HTML ni de détail technique). */
|
||||
$reqPath = (string) (parse_url((string) ($_SERVER['REQUEST_URI'] ?? '/'), PHP_URL_PATH) ?: '/');
|
||||
if (str_starts_with($reqPath, '/api')) {
|
||||
http_response_code(404);
|
||||
header('Content-Type: application/json; charset=utf-8');
|
||||
header('X-Content-Type-Options: nosniff');
|
||||
exit(json_encode(['ok' => false, 'error' => 'Ressource introuvable.'], JSON_UNESCAPED_UNICODE));
|
||||
}
|
||||
}
|
||||
|
||||
/* Paquets : une seule lecture DB + cache Gitea pour toute la page
|
||||
(le corps ET la nav déroulante les consomment). */
|
||||
$packages = fws_site_packages();
|
||||
|
||||
Reference in new issue
Block a user