From d9eee9e15a85dd3f56e2f8c60eaf3a47acf51c00 Mon Sep 17 00:00:00 2001 From: Oliver Hader Date: Tue, 30 Apr 2024 22:23:57 +0200 Subject: [PATCH] [TASK] Add possibility to create HashValue from actual payload The new factory method `HashValue::hash('test')` creates the hash from the raw payload `'test'`. This is a simpler shortcut for using `HashValue::create(hash('sha256', 'test', true))`. Resolves: #103772 Releases: main, 12.4 Change-Id: Id201e166eeabc856b8d8dc498cc73cde8d5eb801 Reviewed-on: https://review.typo3.org/c/Packages/TYPO3.CMS/+/84100 Tested-by: core-ci Reviewed-by: Benni Mack Tested-by: Georg Ringer Reviewed-by: Georg Ringer Tested-by: Benni Mack Reviewed-by: Markus Klein --- .../Security/ContentSecurityPolicy/HashValue.php | 6 ++++++ .../Security/ContentSecurityPolicy/PolicyTest.php | 12 +++++++++--- 2 files changed, 15 insertions(+), 3 deletions(-) diff --git a/typo3/sysext/core/Classes/Security/ContentSecurityPolicy/HashValue.php b/typo3/sysext/core/Classes/Security/ContentSecurityPolicy/HashValue.php index 8a392eecc4e..bda5b5e0217 100644 --- a/typo3/sysext/core/Classes/Security/ContentSecurityPolicy/HashValue.php +++ b/typo3/sysext/core/Classes/Security/ContentSecurityPolicy/HashValue.php @@ -27,6 +27,12 @@ final class HashValue implements \Stringable, SourceValueInterface { public readonly string $value; + public static function hash(string $payload, HashType $type = HashType::sha256): self + { + $value = hash($type->value, $payload, true); + return self::create($value, $type); + } + public static function create(string $value, HashType $type = HashType::sha256): self { return new self($value, $type); diff --git a/typo3/sysext/core/Tests/Functional/Security/ContentSecurityPolicy/PolicyTest.php b/typo3/sysext/core/Tests/Functional/Security/ContentSecurityPolicy/PolicyTest.php index 09bc69d6be7..f702ef14b45 100644 --- a/typo3/sysext/core/Tests/Functional/Security/ContentSecurityPolicy/PolicyTest.php +++ b/typo3/sysext/core/Tests/Functional/Security/ContentSecurityPolicy/PolicyTest.php @@ -59,12 +59,18 @@ public function hashProxyIsCompiled(): void } #[Test] - public function hashValueIsCompiled(): void + public function hashValueIsCompiledUsingHashFactory(): void + { + $policy = (new Policy())->extend(Directive::ScriptSrc, HashValue::hash('test')); + self::assertSame("script-src 'sha256-n4bQgYhMfWWaL+qgxVrQFaO/TxsrC4Is0V1sFbDwCgg='", $policy->compile($this->nonce)); + } + + #[Test] + public function hashValueIsCompiledUsingCreateFactory(): void { $hash = hash('sha256', 'test', true); - $hashB64 = base64_encode($hash); $policy = (new Policy())->extend(Directive::ScriptSrc, HashValue::create($hash)); - self::assertSame("script-src 'sha256-$hashB64'", $policy->compile($this->nonce)); + self::assertSame("script-src 'sha256-n4bQgYhMfWWaL+qgxVrQFaO/TxsrC4Is0V1sFbDwCgg='", $policy->compile($this->nonce)); } #[Test]