3 namespace BookStack\Http\Middleware;
6 use Illuminate\Http\Request;
7 use Illuminate\Support\Str;
8 use Symfony\Component\HttpFoundation\Response;
14 * Handle an incoming request.
16 * @param Request $request
17 * @param Closure $next
21 public function handle($request, Closure $next)
23 $nonce = Str::random(24);
24 view()->share('cspNonce', $nonce);
26 // TODO - Assess whether image/style/iframe CSP rules should be set
27 // TODO - Extract nonce application to custom head content in a way that's cacheable.
28 // TODO - Fix remaining CSP issues and test lots
30 $response = $next($request);
32 $this->setFrameAncestors($response);
33 $this->setScriptSrc($response, $nonce);
39 * Sets CSP 'script-src' headers to restrict the forms of script that can
42 public function setScriptSrc(Response $response, string $nonce)
46 '\'nonce-' . $nonce . '\'',
49 $response->headers->set('Content-Security-Policy', 'script-src ' . implode(' ', $parts));
53 * Sets CSP "frame-ancestors" headers to restrict the hosts that BookStack can be
54 * iframed within. Also adjusts the cookie samesite options so that cookies will
55 * operate in the third-party context.
57 protected function setFrameAncestors(Response $response)
59 $iframeHosts = collect(explode(' ', config('app.iframe_hosts', '')))->filter();
61 if ($iframeHosts->count() > 0) {
62 config()->set('session.same_site', 'none');
65 $iframeHosts->prepend("'self'");
66 $cspValue = 'frame-ancestors ' . $iframeHosts->join(' ');
67 $response->headers->set('Content-Security-Policy', $cspValue);