Sentry code to anonymize reports

Remove legacy kwaadpepper/exception-handler
This commit is contained in:
Jérémy Munsch 2022-12-13 12:13:21 +01:00
parent 167c54aa3a
commit 35a9db45ef
No known key found for this signature in database
GPG key ID: 18361AF3BFEC0FEC
8 changed files with 218 additions and 201 deletions

View file

@ -4,8 +4,7 @@ namespace App\Exceptions;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Mail;
use Throwable;
use Kwaadpepper\ExceptionHandler\Exceptions\ExceptionHandler;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Sentry\Laravel\Integration;
class Handler extends ExceptionHandler
@ -28,20 +27,19 @@ class Handler extends ExceptionHandler
];
/**
* Report or log an exception.
* Register the exception handling callbacks for the application.
*
* @param \Throwable $exception
* @return void
*/
public function report(Throwable $exception)
public function register()
{
Integration::captureUnhandledException($exception);
if ($exception instanceof CafelApiImageFetchException) {
$this->reportCafelApiImageErrorException($exception);
return;
}
parent::report($exception);
$this->reportable(function (\Throwable $e) {
Integration::captureUnhandledException($e);
if ($e instanceof CafelApiImageFetchException) {
$this->reportCafelApiImageErrorException($e);
return;
}
});
}
/**

View file

@ -1,89 +0,0 @@
<?php
namespace App\Lib;
use Throwable;
class Exceptions
{
/**
* Anonymize at least Sql queries
*
* @param string $message
* @return string
*/
public static function getAnonymizedMessage(string $message): string
{
$message = \preg_replace('/^(.*)( \(SQL:.*\))$/', '$1', $message) ?? $message;
return $message;
}
/**
* Anonymize stack trace
*
* @param \Exception $e
* @return string
*/
public static function getAnonymizedStackTrace(Throwable $e): string
{
$projectPath = \realpath(\sprintf('%s/../', \app_path()));
$traceStack = $e->getTrace();
$traceStr = '';
$maxStackStage = 0;
foreach ($traceStack as $stackStage => $stack) {
$maxStackStage = $stackStage;
$traceStr .= \sprintf(
'#%s %s(%d): ',
$stackStage,
str_replace($projectPath, '', $stack['file'] ?? ''),
$stack['line'] ?? ''
);
if (isset($stack['class'])) {
$traceStr .= "{$stack['class']}->{$stack['function']}(";
if (isset($stack['args'])) {
$traceStr .= self::handleArgs($stack);
}
$traceStr .= ")\n";
} elseif (isset($stack['function'])) {
$traceStr .= "{$stack['function']}(";
if (isset($stack['args'])) {
$traceStr .= self::handleArgs($stack);
}
$traceStr .= ")\n";
}
}
$maxStackStage++;
$traceStr .= "#$maxStackStage {main}";
return $traceStr;
}
/**
* Handle Args
*
* @param array $stack
* @return string
*/
public static function handleArgs(array $stack): string
{
$traceArgs = '';
$argsCount = count($stack['args']);
for ($i = 0; $i < $argsCount; $i++) {
$type = \gettype($stack['args'][$i]);
switch ($type) {
case 'object':
$traceArgs .= sprintf('Object(%s)', \get_class($stack['args'][$i]));
break;
case 'array':
$traceArgs .= sprintf('Array(%d)', \count($stack['args'][$i]));
break;
case 'string':
$traceArgs .= sprintf('String(%d)', \strlen($stack['args'][$i]));
break;
default:
$traceArgs .= \gettype($stack['args'][$i]);
}
$traceArgs .= ($i !== ($argsCount - 1) ? ',' : '');
}
return $traceArgs;
}
}

View file

@ -0,0 +1,190 @@
<?php
namespace App\Lib;
class ExceptionsHelper
{
/**
* Handle sentry event
*
* @param \Sentry\Event $event
* @return null|\Sentry\Event
*/
public static function sentryEventHandler(\Sentry\Event $event): ?\Sentry\Event
{
// Remove unwanted reports.
$event->setModules([]);
$event->setOsContext(null);
/** @var \Sentry\ExceptionDataBag[] */
$exceptionBag = [];
foreach ($event->getExceptions() as $exceptionDataBag) {
$exceptionBag[] = self::getAnonymizedSentryException($exceptionDataBag);
}
$event->setExceptions($exceptionBag);
return $event;
}
/**
* Anonimize Sentry Exception bag
*
* @param \Sentry\ExceptionDataBag $exceptionDataBag
* @return \Sentry\ExceptionDataBag
*/
private static function getAnonymizedSentryException(
\Sentry\ExceptionDataBag $exceptionDataBag
): \Sentry\ExceptionDataBag {
$exceptionDataBag->setValue(self::getAnonymizedMessage($exceptionDataBag->getValue()));
if ($stackTrace = $exceptionDataBag->getStacktrace()) {
$exceptionDataBag->setStacktrace(self::getAnonymizedSentryStackTrace($stackTrace));
}
return $exceptionDataBag;
}
/**
* Anonymise sentry stacktrace
*
* @param \Sentry\Stacktrace $stackTrace
* @return \Sentry\Stacktrace
*/
private static function getAnonymizedSentryStackTrace(\Sentry\Stacktrace $stackTrace): \Sentry\Stacktrace
{
/** @var \Sentry\Frame[] */
$frames = \array_reverse($stackTrace->getFrames(), true);
$i = \count($frames) - 1;
// * Remove all but keep first (index.php).
while ($i-- > 0) {
$stackTrace->removeFrame(count($stackTrace->getFrames()) - 1);
}
foreach ($frames as $index => $frame) {
$frame->setPostContext([]);
$frame->setPreContext([]);
$frame->setContextLine('');
$frame->setVars(self::getAnonymizedSentryParams($frame->getVars()));
$stackTrace->addFrame($frame);
if ($index === 0) {
$stackTrace->removeFrame(count($stackTrace->getFrames()) - 1);
}
}
return $stackTrace;
}
/**
* Get anonymized sentry params
*
* @param mixed[] $params
* @return string[]
*/
private static function getAnonymizedSentryParams(array $params): array
{
foreach ($params as &$param) {
$type = \strtolower(\gettype($param));
if (\is_string($param)) {
$type = \explode(' ', \trim($param))[0] ?? null;
}
switch ($type) {
case 'Lambda':
case 'Object':
continue 2;
case 'array':
$param = sprintf('Array(%d)', \count($param));
continue 2;
default:
if (\is_numeric($param)) {
$param = \ucfirst($type);
continue 2;
}
if (\is_string($param)) {
$param = sprintf('String(%d)', \strlen($param));
continue 2;
}
} //end switch
} //end foreach
return $params;
}
/**
* Anonymize at least Sql queries
*
* @param string $message
* @return string
*/
public static function getAnonymizedMessage(string $message): string
{
$message = \preg_replace('/^(.*)( \(SQL:.*\))$/', '$1', $message) ?? $message;
if ($sqlPos = \strpos($message, 'to use near')) {
$message = \mb_strcut($message, 0, $sqlPos);
}
return $message;
}
/**
* Anonymize stack trace
*
* @param \Throwable $e
* @return string
*/
public static function getAnonymizedStackTrace(\Throwable $e): string
{
$projectPath = \realpath(\sprintf('%s/../', \app_path()));
$traceStack = $e->getTrace();
$traceStr = '';
$maxStackStage = 0;
foreach ($traceStack as $stackStage => $stack) {
$maxStackStage = $stackStage;
$traceStr .= \sprintf(
'#%s %s(%d): ',
$stackStage,
str_replace($projectPath, '', $stack['file'] ?? ''),
$stack['line'] ?? ''
);
if (isset($stack['class'])) {
$traceStr .= "{$stack['class']}->{$stack['function']}(";
if (isset($stack['args'])) {
$traceStr .= self::handleArgs($stack);
}
$traceStr .= ")\n";
} elseif (isset($stack['function'])) {
$traceStr .= "{$stack['function']}(";
if (isset($stack['args'])) {
$traceStr .= self::handleArgs($stack);
}
$traceStr .= ")\n";
}
} //end foreach
$maxStackStage++;
$traceStr .= "#$maxStackStage {main}";
return $traceStr;
}
/**
* Handle Args
*
* @param array $stack
* @return string
*/
public static function handleArgs(array $stack): string
{
$traceArgs = '';
$argsCount = count($stack['args']);
for ($i = 0; $i < $argsCount; $i++) {
$type = \gettype($stack['args'][$i]);
switch ($type) {
case 'object':
$traceArgs .= sprintf('Object(%s)', \get_class($stack['args'][$i]));
break;
case 'array':
$traceArgs .= sprintf('Array(%d)', \count($stack['args'][$i]));
break;
case 'string':
$traceArgs .= sprintf('String(%d)', \strlen($stack['args'][$i]));
break;
default:
$traceArgs .= \gettype($stack['args'][$i]);
}
$traceArgs .= ($i !== ($argsCount - 1) ? ',' : '');
}
return $traceArgs;
}
}

View file

@ -17,7 +17,6 @@
"fideloper/proxy": "^4.0",
"guzzlehttp/guzzle": "^7.4",
"kwaadpepper/enum": "^2.1",
"kwaadpepper/exception-handler": "^0.0.6",
"kwaadpepper/refresh-sitemap": "^1.0",
"laravel/framework": "^8.0",
"laravel/tinker": "^2.0",

63
composer.lock generated
View file

@ -4,7 +4,7 @@
"Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies",
"This file is @generated automatically"
],
"content-hash": "545c553dbab2ba69ec88affd9467650f",
"content-hash": "3f2fa59ef64f72b47a4cbfa337719a44",
"packages": [
{
"name": "arondeparon/laravel-request-sanitizer",
@ -1586,67 +1586,6 @@
},
"time": "2022-07-28T15:18:54+00:00"
},
{
"name": "kwaadpepper/exception-handler",
"version": "0.0.6",
"source": {
"type": "git",
"url": "https://github.com/Kwaadpepper/exception-handler.git",
"reference": "9e17a9c0a43755d91cb98717e3fc7ba17db0c1c7"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/Kwaadpepper/exception-handler/zipball/9e17a9c0a43755d91cb98717e3fc7ba17db0c1c7",
"reference": "9e17a9c0a43755d91cb98717e3fc7ba17db0c1c7",
"shasum": ""
},
"require": {
"illuminate/support": "~7|~8",
"laravel/framework": "~7|~8"
},
"require-dev": {
"orchestra/testbench": "^6.13",
"phpunit/phpunit": "~9.0",
"squizlabs/php_codesniffer": "^3.5"
},
"type": "library",
"extra": {
"laravel": {
"providers": [
"Kwaadpepper\\ExceptionHandler\\ExceptionHandlerServiceProvider"
]
}
},
"autoload": {
"psr-4": {
"Kwaadpepper\\ExceptionHandler\\": "src/"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Jérémy Munsch",
"email": "github@jeremydev.ovh",
"homepage": "https://jeremydev.ovh"
}
],
"description": "Send emails when exceptions occurs",
"homepage": "https://github.com/kwaadpepper/exception-handler",
"keywords": [
"email",
"exception",
"laravel",
"policies"
],
"support": {
"issues": "https://github.com/Kwaadpepper/exception-handler/issues",
"source": "https://github.com/Kwaadpepper/exception-handler/tree/0.0.6"
},
"time": "2021-12-01T08:54:11+00:00"
},
{
"name": "kwaadpepper/refresh-sitemap",
"version": "1.0.0",

View file

@ -1,15 +0,0 @@
<?php
return [
/**
* Send mail when app debug is turn off
* so you can be warned if an unhandled exception occurs
*/
'enableMaiLog' => !config('app.debug'),
/**
* Put a developper secured mailbox in here
* so you can receive email if things go mad
*/
'contactsList' => explode(',', env('MAIL_LIST_SERVICEWEB', 'equipe.web@ldc.fr')),
];

View file

@ -5,49 +5,49 @@ return [
'dsn' => env('SENTRY_LARAVEL_DSN', env('SENTRY_DSN')),
// The release version of your application
// Example with dynamic git hash: trim(exec('git --git-dir ' . base_path('.git') . ' log --pretty="%h" -n1 HEAD'))
// Example with dynamic git hash: trim(exec('git --git-dir ' . base_path('.git') . ' log --pretty="%h" -n1 HEAD')).
'release' => env('SENTRY_RELEASE'),
// When left empty or `null` the Laravel environment will be used
// When left empty or `null` the Laravel environment will be used.
'environment' => env('SENTRY_ENVIRONMENT'),
'breadcrumbs' => [
// Capture Laravel logs in breadcrumbs
// Capture Laravel logs in breadcrumbs.
'logs' => true,
// Capture SQL queries in breadcrumbs
// Capture SQL queries in breadcrumbs.
'sql_queries' => true,
// Capture bindings on SQL queries logged in breadcrumbs
// Capture bindings on SQL queries logged in breadcrumbs.
'sql_bindings' => true,
// Capture queue job information in breadcrumbs
// Capture queue job information in breadcrumbs.
'queue_info' => true,
// Capture command information in breadcrumbs
// Capture command information in breadcrumbs.
'command_info' => true,
],
'tracing' => [
// Trace queue jobs as their own transactions
// Trace queue jobs as their own transactions.
'queue_job_transactions' => env('SENTRY_TRACE_QUEUE_ENABLED', false),
// Capture queue jobs as spans when executed on the sync driver
// Capture queue jobs as spans when executed on the sync driver.
'queue_jobs' => true,
// Capture SQL queries as spans
// Capture SQL queries as spans.
'sql_queries' => true,
// Try to find out where the SQL query originated from and add it to the query spans
// Try to find out where the SQL query originated from and add it to the query spans.
'sql_origin' => true,
// Capture views as spans
// Capture views as spans.
'views' => true,
// Indicates if the tracing integrations supplied by Sentry should be loaded
// Indicates if the tracing integrations supplied by Sentry should be loaded.
'default_integrations' => true,
// Indicates that requests without a matching route should be traced
// Indicates that requests without a matching route should be traced.
'missing_routes' => false,
],
@ -57,9 +57,6 @@ return [
// @see: https://docs.sentry.io/platforms/php/guides/laravel/configuration/options/#traces-sample-rate
'traces_sample_rate' => env('SENTRY_TRACES_SAMPLE_RATE') === null ? null : (float)env('SENTRY_TRACES_SAMPLE_RATE'),
'before_send' => function (\Sentry\Event $event): ?\Sentry\Event {
dd($event);
return $event;
},
'before_send' => [\App\Lib\ExceptionsHelper::class, 'sentryEventHandler'],
];

View file

@ -4,6 +4,7 @@ use App\Http\Controllers\Fo\BreederController;
use App\Http\Controllers\Fo\EggController;
use App\Http\Controllers\Fo\InfoController;
use App\Http\Controllers\Fo\TraceaPoultryController;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Route;
use function Clue\StreamFilter\fun;
@ -24,10 +25,7 @@ Route::domain(config('app.domain'))->group(function () {
Route::name('poultry.')->group(function () {
//Route::view('/', 'front.poultry.search')->name('search');
Route::get('/', function () {
$toto = function (int $id, string $pwd) {
var_dump("test");
};
$toto("ddd", 3);
DB::select(DB::raw('select * from `poultry_packshots` wher toto = 1;'));
})->name('search');
Route::post('/', [TraceaPoultryController::class, 'searchSubmit'])->name('searchSubmit');
Route::get('tracabilite/volaille', [TraceaPoultryController::class, 'show'])->name('show');