From 35a9db45efc174ed46b8de6d6b69b27c60bf734c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=A9r=C3=A9my=20Munsch?= Date: Tue, 13 Dec 2022 12:13:21 +0100 Subject: [PATCH] Sentry code to anonymize reports Remove legacy kwaadpepper/exception-handler --- app/Exceptions/Handler.php | 22 ++-- app/Lib/Exceptions.php | 89 ---------------- app/Lib/ExceptionsHelper.php | 190 +++++++++++++++++++++++++++++++++++ composer.json | 1 - composer.lock | 63 +----------- config/exception-handler.php | 15 --- config/sentry.php | 33 +++--- routes/web-fo.php | 6 +- 8 files changed, 218 insertions(+), 201 deletions(-) delete mode 100644 app/Lib/Exceptions.php create mode 100644 app/Lib/ExceptionsHelper.php delete mode 100644 config/exception-handler.php diff --git a/app/Exceptions/Handler.php b/app/Exceptions/Handler.php index e1c734b..497ee04 100644 --- a/app/Exceptions/Handler.php +++ b/app/Exceptions/Handler.php @@ -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; + } + }); } /** diff --git a/app/Lib/Exceptions.php b/app/Lib/Exceptions.php deleted file mode 100644 index f943bf3..0000000 --- a/app/Lib/Exceptions.php +++ /dev/null @@ -1,89 +0,0 @@ -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; - } -} diff --git a/app/Lib/ExceptionsHelper.php b/app/Lib/ExceptionsHelper.php new file mode 100644 index 0000000..5b42252 --- /dev/null +++ b/app/Lib/ExceptionsHelper.php @@ -0,0 +1,190 @@ +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; + } +} diff --git a/composer.json b/composer.json index af6e09d..91dde85 100644 --- a/composer.json +++ b/composer.json @@ -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", diff --git a/composer.lock b/composer.lock index cd1fd78..8f4bb53 100644 --- a/composer.lock +++ b/composer.lock @@ -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", diff --git a/config/exception-handler.php b/config/exception-handler.php deleted file mode 100644 index 45d037f..0000000 --- a/config/exception-handler.php +++ /dev/null @@ -1,15 +0,0 @@ - !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')), -]; diff --git a/config/sentry.php b/config/sentry.php index 48871d7..90b0133 100644 --- a/config/sentry.php +++ b/config/sentry.php @@ -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'], ]; diff --git a/routes/web-fo.php b/routes/web-fo.php index a085b5e..43f889e 100644 --- a/routes/web-fo.php +++ b/routes/web-fo.php @@ -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');