Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
100.00% covered (success)
100.00%
7 / 7
100.00% covered (success)
100.00%
3 / 3
CRAP
100.00% covered (success)
100.00%
1 / 1
CspNonceManager
100.00% covered (success)
100.00%
6 / 6
100.00% covered (success)
100.00%
3 / 3
5
100.00% covered (success)
100.00%
1 / 1
 getNonce
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
3
 regenerateNonce
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
1
 generateNonce
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
1<?php
2
3declare(strict_types=1);
4
5/** @license For full copyright and license information, please see the LICENSE.md file. */
6
7namespace App\Core\Security\Csp;
8
9defined('AMMONLY_APP') || exit('Direct script access is forbidden.');
10
11/**
12 * Standard In-Memory CSP Nonce Manager.
13 *
14 * Implements CspNonceManagerInterface producing cryptographically secure 128-bit
15 * base64-encoded nonces per request in accordance with OWASP ASVS v5 V14.4.3.
16 *
17 * @package App\Core\Security\Csp
18 */
19final class CspNonceManager implements CspNonceManagerInterface
20{
21    private const int NONCE_BYTE_LENGTH = 16;
22
23    private ?string $currentNonce = null;
24
25    /**
26     * {@inheritdoc}
27     */
28    public function getNonce(): string
29    {
30        if ($this->currentNonce === null || $this->currentNonce === '') {
31            $this->currentNonce = $this->generateNonce();
32        }
33
34        return $this->currentNonce;
35    }
36
37    /**
38     * {@inheritdoc}
39     */
40    public function regenerateNonce(): string
41    {
42        $this->currentNonce = $this->generateNonce();
43        return $this->currentNonce;
44    }
45
46    /**
47     * Generates a cryptographically strong 16-byte base64-encoded string.
48     */
49    private function generateNonce(): string
50    {
51        return base64_encode(random_bytes(self::NONCE_BYTE_LENGTH));
52    }
53}