|
| 1 | +<?php |
| 2 | + |
| 3 | +declare(strict_types=1); |
| 4 | + |
| 5 | +namespace Flowpack\ContentSecurityPolicy\Command; |
| 6 | + |
| 7 | +use Flowpack\ContentSecurityPolicy\Exceptions\InvalidDirectiveException; |
| 8 | +use Flowpack\ContentSecurityPolicy\Factory\PolicyFactory; |
| 9 | +use Flowpack\ContentSecurityPolicy\Model\Nonce; |
| 10 | +use Flowpack\ContentSecurityPolicy\Model\Policy; |
| 11 | +use Neos\Flow\Annotations as Flow; |
| 12 | +use Neos\Flow\Cli\CommandController; |
| 13 | +use Neos\Flow\Cli\Exception\StopCommandException; |
| 14 | + |
| 15 | +class CspConfigCommandController extends CommandController |
| 16 | +{ |
| 17 | + /** |
| 18 | + * @Flow\InjectConfiguration(path="enabled") |
| 19 | + */ |
| 20 | + protected bool $enabled; |
| 21 | + |
| 22 | + /** |
| 23 | + * @Flow\Inject |
| 24 | + */ |
| 25 | + protected Nonce $nonce; |
| 26 | + |
| 27 | + /** |
| 28 | + * @Flow\InjectConfiguration(path="content-security-policy") |
| 29 | + * @var mixed[] |
| 30 | + */ |
| 31 | + protected array $configuration; |
| 32 | + |
| 33 | + /** |
| 34 | + * Show CSP config |
| 35 | + * |
| 36 | + * Shows the generated config for the CSP. |
| 37 | + * @throws StopCommandException |
| 38 | + */ |
| 39 | + public function showCommand(): void |
| 40 | + { |
| 41 | + try { |
| 42 | + $backendPolicy = PolicyFactory::create( |
| 43 | + $this->nonce, |
| 44 | + $this->configuration['backend'], |
| 45 | + $this->configuration['custom-backend'] |
| 46 | + ); |
| 47 | + |
| 48 | + $frontendPolicy = PolicyFactory::create( |
| 49 | + $this->nonce, |
| 50 | + $this->configuration['default'], |
| 51 | + $this->configuration['custom'] |
| 52 | + ); |
| 53 | + } catch (InvalidDirectiveException $exception) { |
| 54 | + $this->outputLine( |
| 55 | + sprintf('<error>Invalid directive "%s" in configuration file.</error>', $exception->getMessage()) |
| 56 | + ); |
| 57 | + |
| 58 | + $this->quit(1); |
| 59 | + } |
| 60 | + |
| 61 | + $this->outputLine('<b>Backend CSP</b>'); |
| 62 | + $this->printPolicy($backendPolicy); |
| 63 | + |
| 64 | + $this->outputLine("\n<b>Frontend CSP</b>"); |
| 65 | + $this->printPolicy($frontendPolicy); |
| 66 | + $this->quit(); |
| 67 | + } |
| 68 | + |
| 69 | + private function printPolicy(Policy $policy): void |
| 70 | + { |
| 71 | + $directives = $policy->getDirectives(); |
| 72 | + $keys = array_keys($directives); |
| 73 | + |
| 74 | + $items = array_map(function ($values, $directive) { |
| 75 | + $value = implode(', ', $values); |
| 76 | + |
| 77 | + return "$directive: $value"; |
| 78 | + }, $directives, $keys); |
| 79 | + foreach ($items as $item) { |
| 80 | + $this->outputLine($item); |
| 81 | + } |
| 82 | + } |
| 83 | +} |
0 commit comments