diff --git a/src/GraphQl/Action/GraphiQlAction.php b/src/GraphQl/Action/GraphiQlAction.php index ca67f91e03..2858664777 100644 --- a/src/GraphQl/Action/GraphiQlAction.php +++ b/src/GraphQl/Action/GraphiQlAction.php @@ -40,9 +40,28 @@ public function __invoke(Request $request): Response 'title' => $this->title, 'graphiql_data' => ['entrypoint' => $this->router->generate('api_graphql_entrypoint')], 'assetPackage' => $this->assetPackage, + 'cspNonce' => $this->resolveCspNonce($request), ]), 200, ['content-type' => 'text/html']); } throw new BadRequestHttpException('GraphiQL is not enabled.'); } + + private function resolveCspNonce(Request $request): ?string + { + $nonce = $request->attributes->get('_csp_nonce'); + if (\is_string($nonce) && '' !== $nonce) { + return $nonce; + } + + // Reuse the nonce generated by NelmioSecurityBundle (or any bundle exposing a `csp_nonce` + // Twig function) so the emitted nonce matches the one added to the CSP response header. + if ($function = $this->twig->getFunction('csp_nonce')) { + $nonce = ($function->getCallable())('script'); + + return \is_string($nonce) && '' !== $nonce ? $nonce : null; + } + + return null; + } } diff --git a/src/GraphQl/Tests/Action/GraphiQlActionTest.php b/src/GraphQl/Tests/Action/GraphiQlActionTest.php index b2249a7cb9..2e43ad104b 100644 --- a/src/GraphQl/Tests/Action/GraphiQlActionTest.php +++ b/src/GraphQl/Tests/Action/GraphiQlActionTest.php @@ -52,6 +52,7 @@ private function getGraphiQlAction(bool $enabled): GraphiQlAction { $twigProphecy = $this->prophesize(TwigEnvironment::class); $twigProphecy->render(Argument::cetera())->willReturn(''); + $twigProphecy->getFunction('csp_nonce')->willReturn(null); $routerProphecy = $this->prophesize(RouterInterface::class); $routerProphecy->generate('api_graphql_entrypoint')->willReturn('/graphql'); diff --git a/src/Symfony/Bundle/Resources/views/Graphiql/index.html.twig b/src/Symfony/Bundle/Resources/views/Graphiql/index.html.twig index d901a7556b..60b6c06a4b 100644 --- a/src/Symfony/Bundle/Resources/views/Graphiql/index.html.twig +++ b/src/Symfony/Bundle/Resources/views/Graphiql/index.html.twig @@ -9,8 +9,10 @@