Files
michaelschiemer/src/Framework/Http/Middlewares/HoneypotMiddleware.php
Michael Schiemer 55a330b223 Enable Discovery debug logging for production troubleshooting
- Add DISCOVERY_LOG_LEVEL=debug
- Add DISCOVERY_SHOW_PROGRESS=true
- Temporary changes for debugging InitializerProcessor fixes on production
2025-08-11 20:13:26 +02:00

81 lines
2.5 KiB
PHP

<?php
declare(strict_types=1);
namespace App\Framework\Http\Middlewares;
use App\Framework\Http\HttpMiddleware;
use App\Framework\Http\Method;
use App\Framework\Http\MiddlewareContext;
use App\Framework\Http\MiddlewarePriority;
use App\Framework\Http\MiddlewarePriorityAttribute;
use App\Framework\Http\Next;
use App\Framework\Http\Request;
use App\Framework\Http\RequestStateManager;
use App\Framework\Logging\Logger;
#[MiddlewarePriorityAttribute(MiddlewarePriority::SECURITY, -140)] // Nach CSRF, vor anderen Validierungen
final readonly class HoneypotMiddleware implements HttpMiddleware
{
public function __construct(
private ?Logger $logger = null
) {
}
public function __invoke(MiddlewareContext $context, Next $next, RequestStateManager $stateManager): MiddlewareContext
{
$request = $context->request;
if ($request->method === Method::POST) {
$this->validateHoneypot($request);
}
return $next($context);
}
private function validateHoneypot(Request $request): void
{
$honeypotName = $request->parsedBody->get('_honeypot_name');
if (! $honeypotName) {
$this->logSuspiciousActivity('Missing honeypot name', $request);
throw new \Exception('Spam-Schutz ausgelöst');
}
$honeypotValue = $request->parsedBody->get($honeypotName);
// Honeypot wurde ausgefüllt = Bot erkannt
if (! empty($honeypotValue)) {
$this->logSuspiciousActivity("Honeypot filled: {$honeypotName} = {$honeypotValue}", $request);
throw new \Exception('Spam-Schutz ausgelöst');
}
// Zusätzliche Zeit-basierte Validierung (optional)
$this->validateSubmissionTime($request);
}
private function validateSubmissionTime(Request $request): void
{
// Formulare, die zu schnell abgeschickt werden, sind verdächtig
$startTime = $request->parsedBody->get('_form_start_time');
if ($startTime && (time() - (int)$startTime) < 2) {
$this->logSuspiciousActivity('Form submitted too quickly', $request);
throw new \Exception('Spam-Schutz ausgelöst');
}
}
private function logSuspiciousActivity(string $reason, Request $request): void
{
$this->logger?->warning('Honeypot triggered', [
'reason' => $reason,
'ip' => $request->server->getClientIp()->isPrivate(),
'user_agent' => $request->headers->get('User-Agent') ?? 'unknown',
'url' => $request->path,
]);
}
}