Skip to content

Commit c1b5fa1

Browse files
Merge pull request #59 from cloud-solutions/zend-sentry-inject-static-nonce
Zend sentry inject static nonce
2 parents 9b42711 + 8d98583 commit c1b5fa1

File tree

6 files changed

+167
-115
lines changed

6 files changed

+167
-115
lines changed

Module.php

Lines changed: 51 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,8 @@
1414

1515
use Zend\EventManager\EventManager;
1616
use Zend\Mvc\MvcEvent;
17+
use Zend\ServiceManager\ServiceManager;
18+
use Zend\View\Helper\HeadScript;
1719
use ZendSentry\Mvc\View\Http\ExceptionStrategy as SentryHttpStrategy;
1820
use ZendSentry\Mvc\View\Console\ExceptionStrategy as SentryConsoleStrategy;
1921
use Zend\Mvc\View\Http\ExceptionStrategy;
@@ -31,14 +33,14 @@ class Module
3133
* Translates Zend Framework log levels to Raven log levels.
3234
*/
3335
private $logLevels = [
34-
7 => Raven::DEBUG,
35-
6 => Raven::INFO,
36-
5 => Raven::INFO,
37-
4 => Raven::WARNING,
38-
3 => Raven::ERROR,
39-
2 => Raven::FATAL,
40-
1 => Raven::FATAL,
4136
0 => Raven::FATAL,
37+
1 => Raven::FATAL,
38+
2 => Raven::FATAL,
39+
3 => Raven::ERROR,
40+
4 => Raven::WARNING,
41+
5 => Raven::INFO,
42+
6 => Raven::INFO,
43+
7 => Raven::DEBUG,
4244
];
4345

4446
/**
@@ -64,7 +66,7 @@ class Module
6466
/**
6567
* @param MvcEvent $event
6668
*/
67-
public function onBootstrap(MvcEvent $event): void
69+
public function onBootstrap(MvcEvent $event)
6870
{
6971
// Setup RavenClient (provided by Sentry) and Sentry (provided by this module)
7072
$this->config = $event->getApplication()->getServiceManager()->get('Config');
@@ -80,13 +82,15 @@ public function onBootstrap(MvcEvent $event): void
8082
}
8183

8284
$sentryApiKey = $this->config['zend-sentry']['sentry-api-key'];
83-
$ravenClient = new Raven($sentryApiKey, $ravenConfig);
85+
$ravenClient = new Raven($sentryApiKey, $ravenConfig);
8486

8587
// Register the RavenClient as a application wide service
86-
/** @noinspection PhpUndefinedMethodInspection */
87-
$event->getApplication()->getServiceManager()->setService('raven', $ravenClient);
88+
/** @var ServiceManager $serviceManager */
89+
$serviceManager = $event->getApplication()->getServiceManager();
90+
$serviceManager->setService('raven', $ravenClient);
91+
8892
$this->ravenClient = $ravenClient;
89-
$this->zendSentry = new ZendSentry($ravenClient);
93+
$this->zendSentry = new ZendSentry($ravenClient);
9094

9195
// Get the eventManager and set it as a member for convenience
9296
$this->eventManager = $event->getApplication()->getEventManager();
@@ -126,7 +130,7 @@ public function getAutoloaderConfig(): array
126130
return [
127131
'Zend\Loader\StandardAutoloader' => [
128132
'namespaces' => [
129-
__NAMESPACE__ => __DIR__.'/src/'.__NAMESPACE__,
133+
__NAMESPACE__ => __DIR__ . '/src/' . __NAMESPACE__,
130134
]
131135
]
132136
];
@@ -137,7 +141,7 @@ public function getAutoloaderConfig(): array
137141
*/
138142
public function getConfig()
139143
{
140-
return include __DIR__.'/config/module.config.php';
144+
return include __DIR__ . '/config/module.config.php';
141145
}
142146

143147
/**
@@ -147,29 +151,32 @@ public function getConfig()
147151
*
148152
* @param MvcEvent $event
149153
*/
150-
protected function setupBasicLogging(MvcEvent $event): void
154+
protected function setupBasicLogging(MvcEvent $event)
151155
{
152156
// Get the shared event manager and attach a logging listener for the log event on application level
153157
$sharedManager = $this->eventManager->getSharedManager();
154-
$raven = $this->ravenClient;
155-
$logLevels = $this->logLevels;
158+
$raven = $this->ravenClient;
159+
$logLevels = $this->logLevels;
156160

157-
$sharedManager->attach('*', 'log', function($event) use ($raven, $logLevels) {
161+
$sharedManager->attach(
162+
'*', 'log', function ($event) use ($raven, $logLevels) {
158163
/** @var $event MvcEvent */
159164
if (\is_object($event->getTarget())) {
160165
$target = \get_class($event->getTarget());
161166
} else {
162-
$target = (string) $event->getTarget();
167+
$target = (string)$event->getTarget();
163168
}
164169
$message = $event->getParam('message', 'No message provided');
165-
$priority = (int) $event->getParam('priority', Logger::INFO);
170+
$priority = (int)$event->getParam('priority', Logger::INFO);
166171
$message = sprintf('%s: %s', $target, $message);
167172
$tags = $event->getParam('tags', []);
168-
$extra = $event->getParam('extra', []);
169-
$eventID = $raven->captureMessage($message, [], ['tags' => $tags, 'level' => $logLevels[$priority], 'extra' => $extra]
170-
);
173+
$extra = $event->getParam('extra', []);
174+
$eventID = $raven->captureMessage(
175+
$message, [], ['tags' => $tags, 'level' => $logLevels[$priority], 'extra' => $extra]
176+
);
171177
return $eventID;
172-
}, 2);
178+
}, 2
179+
);
173180
}
174181

175182
/**
@@ -178,7 +185,7 @@ protected function setupBasicLogging(MvcEvent $event): void
178185
*
179186
* @param MvcEvent $event
180187
*/
181-
protected function setupExceptionLogging(MvcEvent $event): void
188+
protected function setupExceptionLogging(MvcEvent $event)
182189
{
183190
// Register Sentry as exception handler for exception that bubble up to the top
184191
$this->zendSentry->registerExceptionHandler($this->config['zend-sentry']['call-existing-exception-handler']);
@@ -201,35 +208,42 @@ protected function setupExceptionLogging(MvcEvent $event): void
201208
$ravenClient = $this->ravenClient;
202209

203210
// Attach an exception listener for the ZendSentry exception strategy, can be triggered from anywhere else too
204-
$this->eventManager->getSharedManager()->attach('*', 'logException', function($event) use ($ravenClient) {
211+
$this->eventManager->getSharedManager()->attach(
212+
'*', 'logException', function ($event) use ($ravenClient) {
205213
/** @var $event MvcEvent */
206214
$exception = $event->getParam('exception');
207-
$tags = $event->getParam('tags', []);
215+
$tags = $event->getParam('tags', []);
208216
return $ravenClient->captureException($exception, ['tags' => $tags]);
209-
});
217+
}
218+
);
210219
}
211220

212221
/**
213222
* Adds the necessary javascript, tries to prepend
214223
*
215224
* @param MvcEvent $event
216225
*/
217-
protected function setupJavascriptLogging(MvcEvent $event): void
226+
protected function setupJavascriptLogging(MvcEvent $event)
218227
{
219-
$viewHelper = $event->getApplication()->getServiceManager()->get('ViewHelperManager')->get('headscript');
228+
/** @var HeadScript $headScript */
229+
$headScript = $event->getApplication()->getServiceManager()->get('ViewHelperManager')->get('headscript');
220230
$useRavenjsCDN = $this->config['zend-sentry']['use-ravenjs-cdn'];
231+
221232
if (!isset($useRavenjsCDN) || $useRavenjsCDN) {
222-
/** @noinspection PhpUndefinedMethodInspection */
223-
$viewHelper->offsetSetFile(0, '//cdn.ravenjs.com/3.26.2/raven.min.js');
233+
$headScript->offsetSetFile(0, '//cdn.ravenjs.com/3.26.2/raven.min.js');
224234
}
225-
$publicApiKey = $this->convertKeyToPublic($this->config['zend-sentry']['sentry-api-key']);
235+
236+
$publicApiKey = $this->convertKeyToPublic($this->config['zend-sentry']['sentry-api-key']);
226237
$ravenjsConfig = json_encode($this->config['zend-sentry']['ravenjs-config']);
227-
/** @noinspection PhpUndefinedMethodInspection */
228-
$viewHelper->offsetSetScript(1, sprintf("if (typeof Raven !== 'undefined') Raven.config('%s', %s).install()", $publicApiKey, $ravenjsConfig));
238+
239+
$attributes = \is_null($this->zendSentry->getCSPNonce()) ? [] : ['nonce' => $this->zendSentry->getCSPNonce()];
240+
241+
$headScript->offsetSetScript(1, sprintf("if (typeof Raven !== 'undefined') Raven.config('%s', %s).install()", $publicApiKey, $ravenjsConfig), 'text/javascript', $attributes);
229242
}
230243

231244
/**
232245
* @param string $key
246+
*
233247
* @return string $publicKey
234248
*/
235249
private function convertKeyToPublic($key): string
@@ -240,8 +254,8 @@ private function convertKeyToPublic($key): string
240254
}
241255
// If legacy DSN with private part is configured...
242256
// ...find private part
243-
$start = strpos($key, ':', 6);
244-
$end = strpos($key, '@');
257+
$start = strpos($key, ':', 6);
258+
$end = strpos($key, '@');
245259
$privatePart = substr($key, $start, $end - $start);
246260

247261
// ... replace it with an empty string

src/ZendSentry/Log/Writer/Sentry.php

Lines changed: 13 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -20,22 +20,21 @@
2020
*/
2121
class Sentry extends AbstractWriter
2222
{
23+
protected $raven;
2324
/**
2425
* Translates Zend Framework log levels to Raven log levels.
2526
*/
2627
private $logLevels = [
27-
'DEBUG' => Raven::DEBUG,
28-
'INFO' => Raven::INFO,
29-
'NOTICE' => Raven::INFO,
30-
'WARN' => Raven::WARNING,
31-
'ERR' => Raven::ERROR,
32-
'CRIT' => Raven::FATAL,
33-
'ALERT' => Raven::FATAL,
34-
'EMERG' => Raven::FATAL,
28+
'DEBUG' => Raven::DEBUG,
29+
'INFO' => Raven::INFO,
30+
'NOTICE' => Raven::INFO,
31+
'WARN' => Raven::WARNING,
32+
'ERR' => Raven::ERROR,
33+
'CRIT' => Raven::FATAL,
34+
'ALERT' => Raven::FATAL,
35+
'EMERG' => Raven::FATAL,
3536
];
3637

37-
protected $raven;
38-
3938
/**
4039
* Sentry constructor.
4140
*
@@ -52,13 +51,14 @@ public function __construct(Raven $raven, $options = null)
5251
* Write a message to the log
5352
*
5453
* @param array $event log data event
54+
*
5555
* @return string $eventID the event ID
5656
*/
57-
protected function doWrite(array $event)
57+
protected function doWrite(array $event): string
5858
{
59-
$extra = [];
59+
$extra = [];
6060
$extra['timestamp'] = $event['timestamp'];
61-
$eventID = $this->raven->captureMessage($event['message'], [], $this->logLevels[$event['priorityName']], false, $event['extra']);
61+
$eventID = $this->raven->captureMessage($event['message'], [], $this->logLevels[$event['priorityName']], false, $event['extra']);
6262

6363
return $eventID;
6464
}

src/ZendSentry/Mvc/View/Console/ExceptionStrategy.php

Lines changed: 23 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -29,18 +29,21 @@ class ExceptionStrategy extends AbstractListenerAggregate
2929
{
3030
/**
3131
* Display exceptions?
32+
*
3233
* @var bool
3334
*/
3435
protected $displayExceptions = false;
3536

3637
/**
3738
* Default Exception Message
39+
*
3840
* @var string
3941
*/
4042
protected $defaultExceptionMessage = "Oh no. Something went wrong, but we have been notified.\n";
4143

4244
/**
4345
* A template for message to show in console when an exception has occurred.
46+
*
4447
* @var string|callable
4548
*/
4649
protected $message = <<<EOT
@@ -72,11 +75,12 @@ public function attach(EventManagerInterface $events, $priority = 1)
7275
* Flag: display exceptions in error pages?
7376
*
7477
* @param bool $displayExceptions
78+
*
7579
* @return ExceptionStrategy
7680
*/
7781
public function setDisplayExceptions($displayExceptions): ExceptionStrategy
7882
{
79-
$this->displayExceptions = (bool) $displayExceptions;
83+
$this->displayExceptions = (bool)$displayExceptions;
8084
return $this;
8185
}
8286

@@ -100,17 +104,6 @@ public function getMessage(): string
100104
return $this->message;
101105
}
102106

103-
/**
104-
* Set the default exception message
105-
* @param string $defaultExceptionMessage
106-
* @return self
107-
*/
108-
public function setDefaultExceptionMessage($defaultExceptionMessage): self
109-
{
110-
$this->defaultExceptionMessage = $defaultExceptionMessage;
111-
return $this;
112-
}
113-
114107
/**
115108
* Set template for message that will be shown in Console.
116109
* The message can be a string (template) or a callable (i.e. a closure).
@@ -128,7 +121,8 @@ public function setDefaultExceptionMessage($defaultExceptionMessage): self
128121
* :line - the line where the exception has been thrown
129122
* :stack - full exception stack
130123
*
131-
* @param string|callable $message
124+
* @param string|callable $message
125+
*
132126
* @return ExceptionStrategy
133127
*/
134128
public function setMessage($message): ExceptionStrategy
@@ -137,13 +131,27 @@ public function setMessage($message): ExceptionStrategy
137131
return $this;
138132
}
139133

134+
/**
135+
* Set the default exception message
136+
*
137+
* @param string $defaultExceptionMessage
138+
*
139+
* @return self
140+
*/
141+
public function setDefaultExceptionMessage($defaultExceptionMessage): self
142+
{
143+
$this->defaultExceptionMessage = $defaultExceptionMessage;
144+
return $this;
145+
}
146+
140147
/**
141148
* Create an exception view model, and set the console status code
142149
*
143150
* @param MvcEvent $e
151+
*
144152
* @return void
145153
*/
146-
public function prepareExceptionViewModel(MvcEvent $e): void
154+
public function prepareExceptionViewModel(MvcEvent $e)
147155
{
148156
// Do nothing if no error in the event
149157
$error = $e->getError();
@@ -175,7 +183,7 @@ public function prepareExceptionViewModel(MvcEvent $e): void
175183

176184
if (\is_callable($this->message)) {
177185
$callback = $this->message;
178-
$message = (string) $callback($exception, $this->displayExceptions);
186+
$message = (string)$callback($exception, $this->displayExceptions);
179187
} elseif ($this->displayExceptions && $exception instanceof \Exception) {
180188
/* @var $exception \Exception */
181189
$message = str_replace(

0 commit comments

Comments
 (0)